flat-cache 6.1.22 → 6.1.23

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,495 +1,485 @@
1
- "use strict";
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ //#region \0rolldown/runtime.js
2
6
  var __create = Object.create;
3
7
  var __defProp = Object.defineProperty;
4
8
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
9
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
10
  var __getProtoOf = Object.getPrototypeOf;
7
11
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
12
  var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
13
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
14
+ key = keys[i];
15
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
+ get: ((k) => from[k]).bind(null, key),
17
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
+ });
19
+ }
20
+ return to;
19
21
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- FlatCache: () => FlatCache,
34
- FlatCacheEvents: () => FlatCacheEvents,
35
- clearAll: () => clearAll,
36
- clearCacheById: () => clearCacheById,
37
- create: () => create,
38
- createFromFile: () => createFromFile,
39
- default: () => FlatCacheDefault
40
- });
41
- module.exports = __toCommonJS(index_exports);
42
- var import_node_fs = __toESM(require("fs"), 1);
43
- var import_node_path = __toESM(require("path"), 1);
44
- var import_cacheable = require("cacheable");
45
- var import_flatted = require("flatted");
46
- var import_hookified = require("hookified");
47
- var FlatCacheEvents = /* @__PURE__ */ ((FlatCacheEvents2) => {
48
- FlatCacheEvents2["SAVE"] = "save";
49
- FlatCacheEvents2["LOAD"] = "load";
50
- FlatCacheEvents2["DELETE"] = "delete";
51
- FlatCacheEvents2["CLEAR"] = "clear";
52
- FlatCacheEvents2["DESTROY"] = "destroy";
53
- FlatCacheEvents2["ERROR"] = "error";
54
- FlatCacheEvents2["EXPIRED"] = "expired";
55
- return FlatCacheEvents2;
56
- })(FlatCacheEvents || {});
57
- var FlatCache = class extends import_hookified.Hookified {
58
- _cache = new import_cacheable.CacheableMemory();
59
- _cacheDir = ".cache";
60
- _cacheId = "cache1";
61
- _persistInterval = 0;
62
- _persistTimer;
63
- _changesSinceLastSave = false;
64
- _parse = import_flatted.parse;
65
- _stringify = import_flatted.stringify;
66
- constructor(options) {
67
- super();
68
- if (options) {
69
- this._cache = new import_cacheable.CacheableMemory({
70
- ttl: options.ttl,
71
- useClone: options.useClone,
72
- lruSize: options.lruSize,
73
- checkInterval: options.expirationInterval
74
- });
75
- }
76
- if (options?.cacheDir) {
77
- this._cacheDir = options.cacheDir;
78
- }
79
- if (options?.cacheId) {
80
- this._cacheId = options.cacheId;
81
- }
82
- if (options?.persistInterval) {
83
- this._persistInterval = options.persistInterval;
84
- this.startAutoPersist();
85
- }
86
- if (options?.deserialize) {
87
- this._parse = options.deserialize;
88
- }
89
- if (options?.serialize) {
90
- this._stringify = options.serialize;
91
- }
92
- }
93
- /**
94
- * The cache object
95
- * @property cache
96
- * @type {CacheableMemory}
97
- */
98
- get cache() {
99
- return this._cache;
100
- }
101
- /**
102
- * The cache directory
103
- * @property cacheDir
104
- * @type {String}
105
- * @default '.cache'
106
- */
107
- get cacheDir() {
108
- return this._cacheDir;
109
- }
110
- /**
111
- * Set the cache directory
112
- * @property cacheDir
113
- * @type {String}
114
- * @default '.cache'
115
- */
116
- set cacheDir(value) {
117
- this._cacheDir = value;
118
- }
119
- /**
120
- * The cache id
121
- * @property cacheId
122
- * @type {String}
123
- * @default 'cache1'
124
- */
125
- get cacheId() {
126
- return this._cacheId;
127
- }
128
- /**
129
- * Set the cache id
130
- * @property cacheId
131
- * @type {String}
132
- * @default 'cache1'
133
- */
134
- set cacheId(value) {
135
- this._cacheId = value;
136
- }
137
- /**
138
- * The flag to indicate if there are changes since the last save
139
- * @property changesSinceLastSave
140
- * @type {Boolean}
141
- * @default false
142
- */
143
- get changesSinceLastSave() {
144
- return this._changesSinceLastSave;
145
- }
146
- /**
147
- * The interval to persist the cache to disk. 0 means no timed persistence
148
- * @property persistInterval
149
- * @type {Number}
150
- * @default 0
151
- */
152
- get persistInterval() {
153
- return this._persistInterval;
154
- }
155
- /**
156
- * Set the interval to persist the cache to disk. 0 means no timed persistence
157
- * @property persistInterval
158
- * @type {Number}
159
- * @default 0
160
- */
161
- set persistInterval(value) {
162
- this._persistInterval = value;
163
- }
164
- /**
165
- * Load a cache identified by the given Id. If the element does not exists, then initialize an empty
166
- * cache storage. If specified `cacheDir` will be used as the directory to persist the data to. If omitted
167
- * then the cache module directory `.cacheDir` will be used instead
168
- *
169
- * @method load
170
- * @param cacheId {String} the id of the cache, would also be used as the name of the file cache
171
- * @param cacheDir {String} directory for the cache entry
172
- */
173
- load(cacheId, cacheDir) {
174
- try {
175
- const filePath = import_node_path.default.resolve(
176
- `${cacheDir ?? this._cacheDir}/${cacheId ?? this._cacheId}`
177
- );
178
- this.loadFile(filePath);
179
- this.emit("load" /* LOAD */);
180
- } catch (error) {
181
- this.emit("error" /* ERROR */, error);
182
- }
183
- }
184
- /**
185
- * Load the cache from the provided file
186
- * @method loadFile
187
- * @param {String} pathToFile the path to the file containing the info for the cache
188
- */
189
- loadFile(pathToFile) {
190
- if (import_node_fs.default.existsSync(pathToFile)) {
191
- const data = import_node_fs.default.readFileSync(pathToFile, "utf8");
192
- const items = this._parse(data);
193
- if (Array.isArray(items)) {
194
- for (const item of items) {
195
- if (item && typeof item === "object" && "key" in item) {
196
- if (item.expires) {
197
- this._cache.set(item.key, item.value, { expire: item.expires });
198
- } else if (item.timestamp) {
199
- this._cache.set(item.key, item.value, { expire: item.timestamp });
200
- } else {
201
- this._cache.set(item.key, item.value);
202
- }
203
- }
204
- }
205
- } else {
206
- for (const key of Object.keys(items)) {
207
- const item = items[key];
208
- if (item && typeof item === "object" && "key" in item) {
209
- this._cache.set(item.key, item.value, {
210
- expire: item.expires
211
- });
212
- } else {
213
- if (item && typeof item === "object" && item.timestamp) {
214
- this._cache.set(key, item, { expire: item.timestamp });
215
- } else {
216
- this._cache.set(key, item);
217
- }
218
- }
219
- }
220
- }
221
- this._changesSinceLastSave = true;
222
- }
223
- }
224
- loadFileStream(pathToFile, onProgress, onEnd, onError) {
225
- if (import_node_fs.default.existsSync(pathToFile)) {
226
- const stats = import_node_fs.default.statSync(pathToFile);
227
- const total = stats.size;
228
- let loaded = 0;
229
- let streamData = "";
230
- const readStream = import_node_fs.default.createReadStream(pathToFile, { encoding: "utf8" });
231
- readStream.on("data", (chunk) => {
232
- loaded += chunk.length;
233
- streamData += chunk;
234
- onProgress(loaded, total);
235
- });
236
- readStream.on("end", () => {
237
- const items = this._parse(streamData);
238
- for (const key of Object.keys(items)) {
239
- this._cache.set(items[key].key, items[key].value, {
240
- expire: items[key].expires
241
- });
242
- }
243
- this._changesSinceLastSave = true;
244
- onEnd();
245
- });
246
- readStream.on("error", (error) => {
247
- this.emit("error" /* ERROR */, error);
248
- if (onError) {
249
- onError(error);
250
- }
251
- });
252
- } else {
253
- const error = new Error(`Cache file ${pathToFile} does not exist`);
254
- this.emit("error" /* ERROR */, error);
255
- if (onError) {
256
- onError(error);
257
- }
258
- }
259
- }
260
- /**
261
- * Returns the entire persisted object
262
- * @method all
263
- * @returns {*}
264
- */
265
- all() {
266
- const result = {};
267
- const items = [...this._cache.items];
268
- for (const item of items) {
269
- result[item.key] = item.value;
270
- }
271
- return result;
272
- }
273
- /**
274
- * Returns an array with all the items in the cache { key, value, expires }
275
- * @method items
276
- * @returns {Array}
277
- */
278
- // biome-ignore lint/suspicious/noExplicitAny: cache items can store any value
279
- get items() {
280
- return [...this._cache.items];
281
- }
282
- /**
283
- * Returns the path to the file where the cache is persisted
284
- * @method cacheFilePath
285
- * @returns {String}
286
- */
287
- get cacheFilePath() {
288
- return import_node_path.default.resolve(`${this._cacheDir}/${this._cacheId}`);
289
- }
290
- /**
291
- * Returns the path to the cache directory
292
- * @method cacheDirPath
293
- * @returns {String}
294
- */
295
- get cacheDirPath() {
296
- return import_node_path.default.resolve(this._cacheDir);
297
- }
298
- /**
299
- * Returns an array with all the keys in the cache
300
- * @method keys
301
- * @returns {Array}
302
- */
303
- keys() {
304
- return [...this._cache.keys];
305
- }
306
- /**
307
- * (Legacy) set key method. This method will be deprecated in the future
308
- * @method setKey
309
- * @param key {string} the key to set
310
- * @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify
311
- */
312
- // biome-ignore lint/suspicious/noExplicitAny: type format
313
- setKey(key, value, ttl) {
314
- this.set(key, value, ttl);
315
- }
316
- /**
317
- * Sets a key to a given value
318
- * @method set
319
- * @param key {string} the key to set
320
- * @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify
321
- * @param [ttl] {number} the time to live in milliseconds
322
- */
323
- // biome-ignore lint/suspicious/noExplicitAny: type format
324
- set(key, value, ttl) {
325
- this._cache.set(key, value, ttl);
326
- this._changesSinceLastSave = true;
327
- }
328
- /**
329
- * (Legacy) Remove a given key from the cache. This method will be deprecated in the future
330
- * @method removeKey
331
- * @param key {String} the key to remove from the object
332
- */
333
- removeKey(key) {
334
- this.delete(key);
335
- }
336
- /**
337
- * Remove a given key from the cache
338
- * @method delete
339
- * @param key {String} the key to remove from the object
340
- */
341
- delete(key) {
342
- this._cache.delete(key);
343
- this._changesSinceLastSave = true;
344
- this.emit("delete" /* DELETE */, key);
345
- }
346
- /**
347
- * (Legacy) Return the value of the provided key. This method will be deprecated in the future
348
- * @method getKey<T>
349
- * @param key {String} the name of the key to retrieve
350
- * @returns {*} at T the value from the key
351
- */
352
- getKey(key) {
353
- return this.get(key);
354
- }
355
- /**
356
- * Return the value of the provided key
357
- * @method get<T>
358
- * @param key {String} the name of the key to retrieve
359
- * @returns {*} at T the value from the key
360
- */
361
- get(key) {
362
- return this._cache.get(key);
363
- }
364
- /**
365
- * Clear the cache and save the state to disk
366
- * @method clear
367
- */
368
- clear() {
369
- try {
370
- this._cache.clear();
371
- this._changesSinceLastSave = true;
372
- this.save();
373
- this.emit("clear" /* CLEAR */);
374
- } catch (error) {
375
- this.emit("error" /* ERROR */, error);
376
- }
377
- }
378
- /**
379
- * Save the state of the cache identified by the docId to disk
380
- * as a JSON structure
381
- * @method save
382
- */
383
- save(force = false) {
384
- try {
385
- if (this._changesSinceLastSave || force) {
386
- const filePath = this.cacheFilePath;
387
- const items = [...this._cache.items];
388
- const data = this._stringify(items);
389
- if (!import_node_fs.default.existsSync(this._cacheDir)) {
390
- import_node_fs.default.mkdirSync(this._cacheDir, { recursive: true });
391
- }
392
- import_node_fs.default.writeFileSync(filePath, data);
393
- this._changesSinceLastSave = false;
394
- this.emit("save" /* SAVE */);
395
- }
396
- } catch (error) {
397
- this.emit("error" /* ERROR */, error);
398
- }
399
- }
400
- /**
401
- * Remove the file where the cache is persisted
402
- * @method removeCacheFile
403
- * @return {Boolean} true or false if the file was successfully deleted
404
- */
405
- removeCacheFile() {
406
- try {
407
- if (import_node_fs.default.existsSync(this.cacheFilePath)) {
408
- import_node_fs.default.rmSync(this.cacheFilePath);
409
- return true;
410
- }
411
- } catch (error) {
412
- this.emit("error" /* ERROR */, error);
413
- }
414
- return false;
415
- }
416
- /**
417
- * Destroy the cache. This will remove the directory, file, and memory cache
418
- * @method destroy
419
- * @param [includeCacheDir=false] {Boolean} if true, the cache directory will be removed
420
- * @return {undefined}
421
- */
422
- destroy(includeCacheDirectory = false) {
423
- try {
424
- this._cache.clear();
425
- this.stopAutoPersist();
426
- if (includeCacheDirectory) {
427
- import_node_fs.default.rmSync(this.cacheDirPath, { recursive: true, force: true });
428
- } else {
429
- import_node_fs.default.rmSync(this.cacheFilePath, { recursive: true, force: true });
430
- }
431
- this._changesSinceLastSave = false;
432
- this.emit("destroy" /* DESTROY */);
433
- } catch (error) {
434
- this.emit("error" /* ERROR */, error);
435
- }
436
- }
437
- /**
438
- * Start the auto persist interval
439
- * @method startAutoPersist
440
- */
441
- startAutoPersist() {
442
- if (this._persistInterval > 0) {
443
- if (this._persistTimer) {
444
- clearInterval(this._persistTimer);
445
- this._persistTimer = void 0;
446
- }
447
- this._persistTimer = setInterval(() => {
448
- this.save();
449
- }, this._persistInterval);
450
- }
451
- }
452
- /**
453
- * Stop the auto persist interval
454
- * @method stopAutoPersist
455
- */
456
- stopAutoPersist() {
457
- if (this._persistTimer) {
458
- clearInterval(this._persistTimer);
459
- this._persistTimer = void 0;
460
- }
461
- }
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+ //#endregion
27
+ let node_fs = require("node:fs");
28
+ node_fs = __toESM(node_fs, 1);
29
+ let node_path = require("node:path");
30
+ node_path = __toESM(node_path, 1);
31
+ let cacheable = require("cacheable");
32
+ let flatted = require("flatted");
33
+ let hookified = require("hookified");
34
+ //#region src/index.ts
35
+ let FlatCacheEvents = /* @__PURE__ */ function(FlatCacheEvents) {
36
+ FlatCacheEvents["SAVE"] = "save";
37
+ FlatCacheEvents["LOAD"] = "load";
38
+ FlatCacheEvents["DELETE"] = "delete";
39
+ FlatCacheEvents["CLEAR"] = "clear";
40
+ FlatCacheEvents["DESTROY"] = "destroy";
41
+ FlatCacheEvents["ERROR"] = "error";
42
+ FlatCacheEvents["EXPIRED"] = "expired";
43
+ return FlatCacheEvents;
44
+ }({});
45
+ var FlatCache = class extends hookified.Hookified {
46
+ _cache = new cacheable.CacheableMemory();
47
+ _cacheDir = ".cache";
48
+ _cacheId = "cache1";
49
+ _persistInterval = 0;
50
+ _persistTimer;
51
+ _changesSinceLastSave = false;
52
+ _parse = flatted.parse;
53
+ _stringify = flatted.stringify;
54
+ constructor(options) {
55
+ super();
56
+ if (options) this._cache = new cacheable.CacheableMemory({
57
+ ttl: options.ttl,
58
+ useClone: options.useClone,
59
+ lruSize: options.lruSize,
60
+ checkInterval: options.expirationInterval
61
+ });
62
+ if (options?.cacheDir) this._cacheDir = options.cacheDir;
63
+ if (options?.cacheId) this._cacheId = options.cacheId;
64
+ if (options?.persistInterval) {
65
+ this._persistInterval = options.persistInterval;
66
+ this.startAutoPersist();
67
+ }
68
+ if (options?.deserialize) this._parse = options.deserialize;
69
+ if (options?.serialize) this._stringify = options.serialize;
70
+ }
71
+ /**
72
+ * The cache object
73
+ * @property cache
74
+ * @type {CacheableMemory}
75
+ */
76
+ get cache() {
77
+ return this._cache;
78
+ }
79
+ /**
80
+ * The cache directory
81
+ * @property cacheDir
82
+ * @type {String}
83
+ * @default '.cache'
84
+ */
85
+ get cacheDir() {
86
+ return this._cacheDir;
87
+ }
88
+ /**
89
+ * Set the cache directory
90
+ * @property cacheDir
91
+ * @type {String}
92
+ * @default '.cache'
93
+ */
94
+ set cacheDir(value) {
95
+ this._cacheDir = value;
96
+ }
97
+ /**
98
+ * The cache id
99
+ * @property cacheId
100
+ * @type {String}
101
+ * @default 'cache1'
102
+ */
103
+ get cacheId() {
104
+ return this._cacheId;
105
+ }
106
+ /**
107
+ * Set the cache id
108
+ * @property cacheId
109
+ * @type {String}
110
+ * @default 'cache1'
111
+ */
112
+ set cacheId(value) {
113
+ this._cacheId = value;
114
+ }
115
+ /**
116
+ * The flag to indicate if there are changes since the last save
117
+ * @property changesSinceLastSave
118
+ * @type {Boolean}
119
+ * @default false
120
+ */
121
+ get changesSinceLastSave() {
122
+ return this._changesSinceLastSave;
123
+ }
124
+ /**
125
+ * The interval to persist the cache to disk. 0 means no timed persistence
126
+ * @property persistInterval
127
+ * @type {Number}
128
+ * @default 0
129
+ */
130
+ get persistInterval() {
131
+ return this._persistInterval;
132
+ }
133
+ /**
134
+ * Set the interval to persist the cache to disk. 0 means no timed persistence
135
+ * @property persistInterval
136
+ * @type {Number}
137
+ * @default 0
138
+ */
139
+ set persistInterval(value) {
140
+ this._persistInterval = value;
141
+ }
142
+ /**
143
+ * Load a cache identified by the given Id. If the element does not exists, then initialize an empty
144
+ * cache storage. If specified `cacheDir` will be used as the directory to persist the data to. If omitted
145
+ * then the cache module directory `.cacheDir` will be used instead
146
+ *
147
+ * @method load
148
+ * @param cacheId {String} the id of the cache, would also be used as the name of the file cache
149
+ * @param cacheDir {String} directory for the cache entry
150
+ */
151
+ load(cacheId, cacheDir) {
152
+ try {
153
+ const filePath = node_path.default.resolve(`${cacheDir ?? this._cacheDir}/${cacheId ?? this._cacheId}`);
154
+ this.loadFile(filePath);
155
+ this.emit("load");
156
+ } catch (error) {
157
+ /* v8 ignore next -- @preserve */
158
+ this.emit("error", error);
159
+ }
160
+ }
161
+ /**
162
+ * Load the cache from the provided file
163
+ * @method loadFile
164
+ * @param {String} pathToFile the path to the file containing the info for the cache
165
+ */
166
+ loadFile(pathToFile) {
167
+ if (node_fs.default.existsSync(pathToFile)) {
168
+ const data = node_fs.default.readFileSync(pathToFile, "utf8");
169
+ const items = this._parse(data);
170
+ if (Array.isArray(items)) {
171
+ for (const item of items) if (item && typeof item === "object" && "key" in item) if (item.expires) this._cache.set(item.key, item.value, { expire: item.expires });
172
+ else if (item.timestamp)
173
+ /* v8 ignore next -- @preserve */
174
+ this._cache.set(item.key, item.value, { expire: item.timestamp });
175
+ else this._cache.set(item.key, item.value);
176
+ } else for (const key of Object.keys(items)) {
177
+ const item = items[key];
178
+ /* v8 ignore next -- @preserve */
179
+ if (item && typeof item === "object" && "key" in item) this._cache.set(item.key, item.value, { expire: item.expires });
180
+ else if (item && typeof item === "object" && item.timestamp)
181
+ /* v8 ignore next -- @preserve */
182
+ this._cache.set(key, item, { expire: item.timestamp });
183
+ else this._cache.set(key, item);
184
+ }
185
+ this._changesSinceLastSave = true;
186
+ }
187
+ }
188
+ loadFileStream(pathToFile, onProgress, onEnd, onError) {
189
+ if (node_fs.default.existsSync(pathToFile)) {
190
+ const total = node_fs.default.statSync(pathToFile).size;
191
+ let loaded = 0;
192
+ let streamData = "";
193
+ const readStream = node_fs.default.createReadStream(pathToFile, { encoding: "utf8" });
194
+ readStream.on("data", (chunk) => {
195
+ loaded += chunk.length;
196
+ streamData += chunk;
197
+ onProgress(loaded, total);
198
+ });
199
+ readStream.on("end", () => {
200
+ const items = this._parse(streamData);
201
+ for (const key of Object.keys(items)) this._cache.set(items[key].key, items[key].value, { expire: items[key].expires });
202
+ this._changesSinceLastSave = true;
203
+ onEnd();
204
+ });
205
+ /* v8 ignore next -- @preserve */
206
+ readStream.on("error", (error) => {
207
+ this.emit("error", error);
208
+ if (onError) onError(error);
209
+ });
210
+ } else {
211
+ const error = /* @__PURE__ */ new Error(`Cache file ${pathToFile} does not exist`);
212
+ this.emit("error", error);
213
+ /* v8 ignore next -- @preserve */
214
+ if (onError) onError(error);
215
+ }
216
+ }
217
+ /**
218
+ * Returns the entire persisted object
219
+ * @method all
220
+ * @returns {*}
221
+ */
222
+ all() {
223
+ const result = {};
224
+ const items = [...this._cache.items];
225
+ for (const item of items) result[item.key] = item.value;
226
+ return result;
227
+ }
228
+ /**
229
+ * Returns an array with all the items in the cache { key, value, expires }
230
+ * @method items
231
+ * @returns {Array}
232
+ */
233
+ get items() {
234
+ return [...this._cache.items];
235
+ }
236
+ /**
237
+ * Returns the path to the file where the cache is persisted
238
+ * @method cacheFilePath
239
+ * @returns {String}
240
+ */
241
+ get cacheFilePath() {
242
+ return node_path.default.resolve(`${this._cacheDir}/${this._cacheId}`);
243
+ }
244
+ /**
245
+ * Returns the path to the cache directory
246
+ * @method cacheDirPath
247
+ * @returns {String}
248
+ */
249
+ get cacheDirPath() {
250
+ return node_path.default.resolve(this._cacheDir);
251
+ }
252
+ /**
253
+ * Returns an array with all the keys in the cache
254
+ * @method keys
255
+ * @returns {Array}
256
+ */
257
+ keys() {
258
+ return [...this._cache.keys];
259
+ }
260
+ /**
261
+ * (Legacy) set key method. This method will be deprecated in the future
262
+ * @method setKey
263
+ * @param key {string} the key to set
264
+ * @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify
265
+ */
266
+ setKey(key, value, ttl) {
267
+ this.set(key, value, ttl);
268
+ }
269
+ /**
270
+ * Sets a key to a given value
271
+ * @method set
272
+ * @param key {string} the key to set
273
+ * @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify
274
+ * @param [ttl] {number} the time to live in milliseconds
275
+ */
276
+ set(key, value, ttl) {
277
+ this._cache.set(key, value, ttl);
278
+ this._changesSinceLastSave = true;
279
+ }
280
+ /**
281
+ * (Legacy) Remove a given key from the cache. This method will be deprecated in the future
282
+ * @method removeKey
283
+ * @param key {String} the key to remove from the object
284
+ */
285
+ removeKey(key) {
286
+ this.delete(key);
287
+ }
288
+ /**
289
+ * Remove a given key from the cache
290
+ * @method delete
291
+ * @param key {String} the key to remove from the object
292
+ */
293
+ delete(key) {
294
+ this._cache.delete(key);
295
+ this._changesSinceLastSave = true;
296
+ this.emit("delete", key);
297
+ }
298
+ /**
299
+ * (Legacy) Return the value of the provided key. This method will be deprecated in the future
300
+ * @method getKey<T>
301
+ * @param key {String} the name of the key to retrieve
302
+ * @returns {*} at T the value from the key
303
+ */
304
+ getKey(key) {
305
+ return this.get(key);
306
+ }
307
+ /**
308
+ * Return the value of the provided key
309
+ * @method get<T>
310
+ * @param key {String} the name of the key to retrieve
311
+ * @returns {*} at T the value from the key
312
+ */
313
+ get(key) {
314
+ return this._cache.get(key);
315
+ }
316
+ /**
317
+ * Clear the cache and save the state to disk
318
+ * @method clear
319
+ */
320
+ clear() {
321
+ try {
322
+ this._cache.clear();
323
+ this._changesSinceLastSave = true;
324
+ this.save();
325
+ this.emit("clear");
326
+ } catch (error) {
327
+ /* v8 ignore next -- @preserve */
328
+ this.emit("error", error);
329
+ }
330
+ }
331
+ /**
332
+ * Save the state of the cache identified by the docId to disk
333
+ * as a JSON structure
334
+ * @method save
335
+ */
336
+ save(force = false) {
337
+ try {
338
+ /* v8 ignore next -- @preserve */
339
+ if (this._changesSinceLastSave || force) {
340
+ const filePath = this.cacheFilePath;
341
+ const items = [...this._cache.items];
342
+ const data = this._stringify(items);
343
+ if (!node_fs.default.existsSync(this._cacheDir)) node_fs.default.mkdirSync(this._cacheDir, { recursive: true });
344
+ node_fs.default.writeFileSync(filePath, data);
345
+ this._changesSinceLastSave = false;
346
+ this.emit("save");
347
+ }
348
+ } catch (error) {
349
+ /* v8 ignore next -- @preserve */
350
+ this.emit("error", error);
351
+ }
352
+ }
353
+ /**
354
+ * Remove the file where the cache is persisted
355
+ * @method removeCacheFile
356
+ * @return {Boolean} true or false if the file was successfully deleted
357
+ */
358
+ removeCacheFile() {
359
+ try {
360
+ if (node_fs.default.existsSync(this.cacheFilePath)) {
361
+ node_fs.default.rmSync(this.cacheFilePath);
362
+ return true;
363
+ }
364
+ } catch (error) {
365
+ /* v8 ignore next -- @preserve */
366
+ this.emit("error", error);
367
+ }
368
+ return false;
369
+ }
370
+ /**
371
+ * Destroy the cache. This will remove the directory, file, and memory cache
372
+ * @method destroy
373
+ * @param [includeCacheDir=false] {Boolean} if true, the cache directory will be removed
374
+ * @return {undefined}
375
+ */
376
+ destroy(includeCacheDirectory = false) {
377
+ try {
378
+ this._cache.clear();
379
+ this.stopAutoPersist();
380
+ if (includeCacheDirectory) node_fs.default.rmSync(this.cacheDirPath, {
381
+ recursive: true,
382
+ force: true
383
+ });
384
+ else node_fs.default.rmSync(this.cacheFilePath, {
385
+ recursive: true,
386
+ force: true
387
+ });
388
+ this._changesSinceLastSave = false;
389
+ this.emit("destroy");
390
+ } catch (error) {
391
+ /* v8 ignore next -- @preserve */
392
+ this.emit("error", error);
393
+ }
394
+ }
395
+ /**
396
+ * Start the auto persist interval
397
+ * @method startAutoPersist
398
+ */
399
+ startAutoPersist() {
400
+ /* v8 ignore next -- @preserve */
401
+ if (this._persistInterval > 0) {
402
+ if (this._persistTimer) {
403
+ clearInterval(this._persistTimer);
404
+ this._persistTimer = void 0;
405
+ }
406
+ this._persistTimer = setInterval(() => {
407
+ this.save();
408
+ }, this._persistInterval);
409
+ }
410
+ }
411
+ /**
412
+ * Stop the auto persist interval
413
+ * @method stopAutoPersist
414
+ */
415
+ stopAutoPersist() {
416
+ if (this._persistTimer) {
417
+ clearInterval(this._persistTimer);
418
+ this._persistTimer = void 0;
419
+ }
420
+ }
462
421
  };
463
422
  var FlatCacheDefault = class {
464
- static create = create;
465
- static createFromFile = createFromFile;
466
- static clearCacheById = clearCacheById;
467
- static clearAll = clearAll;
423
+ static create = create;
424
+ static createFromFile = createFromFile;
425
+ static clearCacheById = clearCacheById;
426
+ static clearAll = clearAll;
468
427
  };
428
+ /**
429
+ * Load a cache identified by the given Id. If the element does not exists, then initialize an empty
430
+ * cache storage.
431
+ *
432
+ * @method create
433
+ * @param docId {String} the id of the cache, would also be used as the name of the file cache
434
+ * @param cacheDirectory {String} directory for the cache entry
435
+ * @param options {FlatCacheOptions} options for the cache
436
+ * @returns {cache} cache instance
437
+ */
469
438
  function create(options) {
470
- const cache = new FlatCache(options);
471
- cache.load();
472
- return cache;
439
+ const cache = new FlatCache(options);
440
+ cache.load();
441
+ return cache;
473
442
  }
443
+ /**
444
+ * Load a cache from the provided file
445
+ * @method createFromFile
446
+ * @param {String} filePath the path to the file containing the info for the cache
447
+ * @param options {FlatCacheOptions} options for the cache
448
+ * @returns {cache} cache instance
449
+ */
474
450
  function createFromFile(filePath, options) {
475
- const cache = new FlatCache(options);
476
- cache.loadFile(filePath);
477
- return cache;
451
+ const cache = new FlatCache(options);
452
+ cache.loadFile(filePath);
453
+ return cache;
478
454
  }
455
+ /**
456
+ * Clear the cache identified by the given Id. This will only remove the cache from disk.
457
+ * @method clearCacheById
458
+ * @param cacheId {String} the id of the cache
459
+ * @param cacheDirectory {String} directory for the cache entry
460
+ */
479
461
  function clearCacheById(cacheId, cacheDirectory) {
480
- const cache = new FlatCache({ cacheId, cacheDir: cacheDirectory });
481
- cache.destroy();
462
+ new FlatCache({
463
+ cacheId,
464
+ cacheDir: cacheDirectory
465
+ }).destroy();
482
466
  }
467
+ /**
468
+ * Clear the cache directory
469
+ * @method clearAll
470
+ * @param cacheDir {String} directory for the cache entry
471
+ */
483
472
  function clearAll(cacheDirectory) {
484
- import_node_fs.default.rmSync(cacheDirectory ?? ".cache", { recursive: true, force: true });
473
+ node_fs.default.rmSync(cacheDirectory ?? ".cache", {
474
+ recursive: true,
475
+ force: true
476
+ });
485
477
  }
486
- // Annotate the CommonJS export names for ESM import in node:
487
- 0 && (module.exports = {
488
- FlatCache,
489
- FlatCacheEvents,
490
- clearAll,
491
- clearCacheById,
492
- create,
493
- createFromFile
494
- });
495
- /* v8 ignore next -- @preserve */
478
+ //#endregion
479
+ exports.FlatCache = FlatCache;
480
+ exports.FlatCacheEvents = FlatCacheEvents;
481
+ exports.clearAll = clearAll;
482
+ exports.clearCacheById = clearCacheById;
483
+ exports.create = create;
484
+ exports.createFromFile = createFromFile;
485
+ exports.default = FlatCacheDefault;