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