flat-cache 6.1.17 → 6.1.18

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,471 +1 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- 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
- 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;
19
- };
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
- for (const key of Object.keys(items)) {
194
- this._cache.set(items[key].key, items[key].value, {
195
- expire: items[key].expires
196
- });
197
- }
198
- this._changesSinceLastSave = true;
199
- }
200
- }
201
- loadFileStream(pathToFile, onProgress, onEnd, onError) {
202
- if (import_node_fs.default.existsSync(pathToFile)) {
203
- const stats = import_node_fs.default.statSync(pathToFile);
204
- const total = stats.size;
205
- let loaded = 0;
206
- let streamData = "";
207
- const readStream = import_node_fs.default.createReadStream(pathToFile, { encoding: "utf8" });
208
- readStream.on("data", (chunk) => {
209
- loaded += chunk.length;
210
- streamData += chunk;
211
- onProgress(loaded, total);
212
- });
213
- readStream.on("end", () => {
214
- const items = this._parse(streamData);
215
- for (const key of Object.keys(items)) {
216
- this._cache.set(items[key].key, items[key].value, {
217
- expire: items[key].expires
218
- });
219
- }
220
- this._changesSinceLastSave = true;
221
- onEnd();
222
- });
223
- readStream.on("error", (error) => {
224
- this.emit("error" /* ERROR */, error);
225
- if (onError) {
226
- onError(error);
227
- }
228
- });
229
- } else {
230
- const error = new Error(`Cache file ${pathToFile} does not exist`);
231
- this.emit("error" /* ERROR */, error);
232
- if (onError) {
233
- onError(error);
234
- }
235
- }
236
- }
237
- /**
238
- * Returns the entire persisted object
239
- * @method all
240
- * @returns {*}
241
- */
242
- all() {
243
- const result = {};
244
- const items = [...this._cache.items];
245
- for (const item of items) {
246
- result[item.key] = item.value;
247
- }
248
- return result;
249
- }
250
- /**
251
- * Returns an array with all the items in the cache { key, value, expires }
252
- * @method items
253
- * @returns {Array}
254
- */
255
- // biome-ignore lint/suspicious/noExplicitAny: cache items can store any value
256
- get items() {
257
- return [...this._cache.items];
258
- }
259
- /**
260
- * Returns the path to the file where the cache is persisted
261
- * @method cacheFilePath
262
- * @returns {String}
263
- */
264
- get cacheFilePath() {
265
- return import_node_path.default.resolve(`${this._cacheDir}/${this._cacheId}`);
266
- }
267
- /**
268
- * Returns the path to the cache directory
269
- * @method cacheDirPath
270
- * @returns {String}
271
- */
272
- get cacheDirPath() {
273
- return import_node_path.default.resolve(this._cacheDir);
274
- }
275
- /**
276
- * Returns an array with all the keys in the cache
277
- * @method keys
278
- * @returns {Array}
279
- */
280
- keys() {
281
- return [...this._cache.keys];
282
- }
283
- /**
284
- * (Legacy) set key method. This method will be deprecated in the future
285
- * @method setKey
286
- * @param key {string} the key to set
287
- * @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify
288
- */
289
- // biome-ignore lint/suspicious/noExplicitAny: type format
290
- setKey(key, value, ttl) {
291
- this.set(key, value, ttl);
292
- }
293
- /**
294
- * Sets a key to a given value
295
- * @method set
296
- * @param key {string} the key to set
297
- * @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify
298
- * @param [ttl] {number} the time to live in milliseconds
299
- */
300
- // biome-ignore lint/suspicious/noExplicitAny: type format
301
- set(key, value, ttl) {
302
- this._cache.set(key, value, ttl);
303
- this._changesSinceLastSave = true;
304
- }
305
- /**
306
- * (Legacy) Remove a given key from the cache. This method will be deprecated in the future
307
- * @method removeKey
308
- * @param key {String} the key to remove from the object
309
- */
310
- removeKey(key) {
311
- this.delete(key);
312
- }
313
- /**
314
- * Remove a given key from the cache
315
- * @method delete
316
- * @param key {String} the key to remove from the object
317
- */
318
- delete(key) {
319
- this._cache.delete(key);
320
- this._changesSinceLastSave = true;
321
- this.emit("delete" /* DELETE */, key);
322
- }
323
- /**
324
- * (Legacy) Return the value of the provided key. This method will be deprecated in the future
325
- * @method getKey<T>
326
- * @param key {String} the name of the key to retrieve
327
- * @returns {*} at T the value from the key
328
- */
329
- getKey(key) {
330
- return this.get(key);
331
- }
332
- /**
333
- * Return the value of the provided key
334
- * @method get<T>
335
- * @param key {String} the name of the key to retrieve
336
- * @returns {*} at T the value from the key
337
- */
338
- get(key) {
339
- return this._cache.get(key);
340
- }
341
- /**
342
- * Clear the cache and save the state to disk
343
- * @method clear
344
- */
345
- clear() {
346
- try {
347
- this._cache.clear();
348
- this._changesSinceLastSave = true;
349
- this.save();
350
- this.emit("clear" /* CLEAR */);
351
- } catch (error) {
352
- this.emit("error" /* ERROR */, error);
353
- }
354
- }
355
- /**
356
- * Save the state of the cache identified by the docId to disk
357
- * as a JSON structure
358
- * @method save
359
- */
360
- save(force = false) {
361
- try {
362
- if (this._changesSinceLastSave || force) {
363
- const filePath = this.cacheFilePath;
364
- const items = [...this._cache.items];
365
- const data = this._stringify(items);
366
- if (!import_node_fs.default.existsSync(this._cacheDir)) {
367
- import_node_fs.default.mkdirSync(this._cacheDir, { recursive: true });
368
- }
369
- import_node_fs.default.writeFileSync(filePath, data);
370
- this._changesSinceLastSave = false;
371
- this.emit("save" /* SAVE */);
372
- }
373
- } catch (error) {
374
- this.emit("error" /* ERROR */, error);
375
- }
376
- }
377
- /**
378
- * Remove the file where the cache is persisted
379
- * @method removeCacheFile
380
- * @return {Boolean} true or false if the file was successfully deleted
381
- */
382
- removeCacheFile() {
383
- try {
384
- if (import_node_fs.default.existsSync(this.cacheFilePath)) {
385
- import_node_fs.default.rmSync(this.cacheFilePath);
386
- return true;
387
- }
388
- } catch (error) {
389
- this.emit("error" /* ERROR */, error);
390
- }
391
- return false;
392
- }
393
- /**
394
- * Destroy the cache. This will remove the directory, file, and memory cache
395
- * @method destroy
396
- * @param [includeCacheDir=false] {Boolean} if true, the cache directory will be removed
397
- * @return {undefined}
398
- */
399
- destroy(includeCacheDirectory = false) {
400
- try {
401
- this._cache.clear();
402
- this.stopAutoPersist();
403
- if (includeCacheDirectory) {
404
- import_node_fs.default.rmSync(this.cacheDirPath, { recursive: true, force: true });
405
- } else {
406
- import_node_fs.default.rmSync(this.cacheFilePath, { recursive: true, force: true });
407
- }
408
- this._changesSinceLastSave = false;
409
- this.emit("destroy" /* DESTROY */);
410
- } catch (error) {
411
- this.emit("error" /* ERROR */, error);
412
- }
413
- }
414
- /**
415
- * Start the auto persist interval
416
- * @method startAutoPersist
417
- */
418
- startAutoPersist() {
419
- if (this._persistInterval > 0) {
420
- if (this._persistTimer) {
421
- clearInterval(this._persistTimer);
422
- this._persistTimer = void 0;
423
- }
424
- this._persistTimer = setInterval(() => {
425
- this.save();
426
- }, this._persistInterval);
427
- }
428
- }
429
- /**
430
- * Stop the auto persist interval
431
- * @method stopAutoPersist
432
- */
433
- stopAutoPersist() {
434
- if (this._persistTimer) {
435
- clearInterval(this._persistTimer);
436
- this._persistTimer = void 0;
437
- }
438
- }
439
- };
440
- var FlatCacheDefault = class {
441
- static create = create;
442
- static createFromFile = createFromFile;
443
- static clearCacheById = clearCacheById;
444
- static clearAll = clearAll;
445
- };
446
- function create(options) {
447
- const cache = new FlatCache(options);
448
- cache.load();
449
- return cache;
450
- }
451
- function createFromFile(filePath, options) {
452
- const cache = new FlatCache(options);
453
- cache.loadFile(filePath);
454
- return cache;
455
- }
456
- function clearCacheById(cacheId, cacheDirectory) {
457
- const cache = new FlatCache({ cacheId, cacheDir: cacheDirectory });
458
- cache.destroy();
459
- }
460
- function clearAll(cacheDirectory) {
461
- import_node_fs.default.rmSync(cacheDirectory ?? ".cache", { recursive: true, force: true });
462
- }
463
- // Annotate the CommonJS export names for ESM import in node:
464
- 0 && (module.exports = {
465
- FlatCache,
466
- FlatCacheEvents,
467
- clearAll,
468
- clearCacheById,
469
- create,
470
- createFromFile
471
- });
1
+ "use strict";var F=Object.create;var u=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var L=Object.getPrototypeOf,k=Object.prototype.hasOwnProperty;var A=(s,e)=>{for(var t in e)u(s,t,{get:e[t],enumerable:!0})},y=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of C(e))!k.call(s,i)&&i!==t&&u(s,i,{get:()=>e[i],enumerable:!(r=O(e,i))||r.enumerable});return s};var g=(s,e,t)=>(t=s!=null?F(L(s)):{},y(e||!s||!s.__esModule?u(t,"default",{value:s,enumerable:!0}):t,s)),P=s=>y(u({},"__esModule",{value:!0}),s);var T={};A(T,{FlatCache:()=>l,FlatCacheEvents:()=>S,clearAll:()=>E,clearCacheById:()=>x,create:()=>I,createFromFile:()=>R,default:()=>p});module.exports=P(T);var a=g(require("fs"),1),o=g(require("path"),1),v=require("cacheable"),m=require("flatted"),b=require("hookified"),S=(h=>(h.SAVE="save",h.LOAD="load",h.DELETE="delete",h.CLEAR="clear",h.DESTROY="destroy",h.ERROR="error",h.EXPIRED="expired",h))(S||{}),l=class extends b.Hookified{_cache=new v.CacheableMemory;_cacheDir=".cache";_cacheId="cache1";_persistInterval=0;_persistTimer;_changesSinceLastSave=!1;_parse=m.parse;_stringify=m.stringify;constructor(e){super(),e&&(this._cache=new v.CacheableMemory({ttl:e.ttl,useClone:e.useClone,lruSize:e.lruSize,checkInterval:e.expirationInterval})),e?.cacheDir&&(this._cacheDir=e.cacheDir),e?.cacheId&&(this._cacheId=e.cacheId),e?.persistInterval&&(this._persistInterval=e.persistInterval,this.startAutoPersist()),e?.deserialize&&(this._parse=e.deserialize),e?.serialize&&(this._stringify=e.serialize)}get cache(){return this._cache}get cacheDir(){return this._cacheDir}set cacheDir(e){this._cacheDir=e}get cacheId(){return this._cacheId}set cacheId(e){this._cacheId=e}get changesSinceLastSave(){return this._changesSinceLastSave}get persistInterval(){return this._persistInterval}set persistInterval(e){this._persistInterval=e}load(e,t){try{let r=o.default.resolve(`${t??this._cacheDir}/${e??this._cacheId}`);this.loadFile(r),this.emit("load")}catch(r){this.emit("error",r)}}loadFile(e){if(a.default.existsSync(e)){let t=a.default.readFileSync(e,"utf8"),r=this._parse(t);if(Array.isArray(r))for(let i of r)i&&typeof i=="object"&&"key"in i&&(i.expires?this._cache.set(i.key,i.value,{expire:i.expires}):i.timestamp?this._cache.set(i.key,i.value,{expire:i.timestamp}):this._cache.set(i.key,i.value));else for(let i of Object.keys(r)){let c=r[i];c&&typeof c=="object"&&"key"in c?this._cache.set(c.key,c.value,{expire:c.expires}):c&&typeof c=="object"&&c.timestamp?this._cache.set(i,c,{expire:c.timestamp}):this._cache.set(i,c)}this._changesSinceLastSave=!0}}loadFileStream(e,t,r,i){if(a.default.existsSync(e)){let D=a.default.statSync(e).size,h=0,d="",f=a.default.createReadStream(e,{encoding:"utf8"});f.on("data",n=>{h+=n.length,d+=n,t(h,D)}),f.on("end",()=>{let n=this._parse(d);for(let _ of Object.keys(n))this._cache.set(n[_].key,n[_].value,{expire:n[_].expires});this._changesSinceLastSave=!0,r()}),f.on("error",n=>{this.emit("error",n),i&&i(n)})}else{let c=new Error(`Cache file ${e} does not exist`);this.emit("error",c),i&&i(c)}}all(){let e={},t=[...this._cache.items];for(let r of t)e[r.key]=r.value;return e}get items(){return[...this._cache.items]}get cacheFilePath(){return o.default.resolve(`${this._cacheDir}/${this._cacheId}`)}get cacheDirPath(){return o.default.resolve(this._cacheDir)}keys(){return[...this._cache.keys]}setKey(e,t,r){this.set(e,t,r)}set(e,t,r){this._cache.set(e,t,r),this._changesSinceLastSave=!0}removeKey(e){this.delete(e)}delete(e){this._cache.delete(e),this._changesSinceLastSave=!0,this.emit("delete",e)}getKey(e){return this.get(e)}get(e){return this._cache.get(e)}clear(){try{this._cache.clear(),this._changesSinceLastSave=!0,this.save(),this.emit("clear")}catch(e){this.emit("error",e)}}save(e=!1){try{if(this._changesSinceLastSave||e){let t=this.cacheFilePath,r=[...this._cache.items],i=this._stringify(r);a.default.existsSync(this._cacheDir)||a.default.mkdirSync(this._cacheDir,{recursive:!0}),a.default.writeFileSync(t,i),this._changesSinceLastSave=!1,this.emit("save")}}catch(t){this.emit("error",t)}}removeCacheFile(){try{if(a.default.existsSync(this.cacheFilePath))return a.default.rmSync(this.cacheFilePath),!0}catch(e){this.emit("error",e)}return!1}destroy(e=!1){try{this._cache.clear(),this.stopAutoPersist(),e?a.default.rmSync(this.cacheDirPath,{recursive:!0,force:!0}):a.default.rmSync(this.cacheFilePath,{recursive:!0,force:!0}),this._changesSinceLastSave=!1,this.emit("destroy")}catch(t){this.emit("error",t)}}startAutoPersist(){this._persistInterval>0&&(this._persistTimer&&(clearInterval(this._persistTimer),this._persistTimer=void 0),this._persistTimer=setInterval(()=>{this.save()},this._persistInterval))}stopAutoPersist(){this._persistTimer&&(clearInterval(this._persistTimer),this._persistTimer=void 0)}},p=class{static create=I;static createFromFile=R;static clearCacheById=x;static clearAll=E};function I(s){let e=new l(s);return e.load(),e}function R(s,e){let t=new l(e);return t.loadFile(s),t}function x(s,e){new l({cacheId:s,cacheDir:e}).destroy()}function E(s){a.default.rmSync(s??".cache",{recursive:!0,force:!0})}0&&(module.exports={FlatCache,FlatCacheEvents,clearAll,clearCacheById,create,createFromFile});
package/dist/index.js CHANGED
@@ -1,431 +1 @@
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
- for (const key of Object.keys(items)) {
154
- this._cache.set(items[key].key, items[key].value, {
155
- expire: items[key].expires
156
- });
157
- }
158
- this._changesSinceLastSave = true;
159
- }
160
- }
161
- loadFileStream(pathToFile, onProgress, onEnd, onError) {
162
- if (fs.existsSync(pathToFile)) {
163
- const stats = fs.statSync(pathToFile);
164
- const total = stats.size;
165
- let loaded = 0;
166
- let streamData = "";
167
- const readStream = fs.createReadStream(pathToFile, { encoding: "utf8" });
168
- readStream.on("data", (chunk) => {
169
- loaded += chunk.length;
170
- streamData += chunk;
171
- onProgress(loaded, total);
172
- });
173
- readStream.on("end", () => {
174
- const items = this._parse(streamData);
175
- for (const key of Object.keys(items)) {
176
- this._cache.set(items[key].key, items[key].value, {
177
- expire: items[key].expires
178
- });
179
- }
180
- this._changesSinceLastSave = true;
181
- onEnd();
182
- });
183
- readStream.on("error", (error) => {
184
- this.emit("error" /* ERROR */, error);
185
- if (onError) {
186
- onError(error);
187
- }
188
- });
189
- } else {
190
- const error = new Error(`Cache file ${pathToFile} does not exist`);
191
- this.emit("error" /* ERROR */, error);
192
- if (onError) {
193
- onError(error);
194
- }
195
- }
196
- }
197
- /**
198
- * Returns the entire persisted object
199
- * @method all
200
- * @returns {*}
201
- */
202
- all() {
203
- const result = {};
204
- const items = [...this._cache.items];
205
- for (const item of items) {
206
- result[item.key] = item.value;
207
- }
208
- return result;
209
- }
210
- /**
211
- * Returns an array with all the items in the cache { key, value, expires }
212
- * @method items
213
- * @returns {Array}
214
- */
215
- // biome-ignore lint/suspicious/noExplicitAny: cache items can store any value
216
- get items() {
217
- return [...this._cache.items];
218
- }
219
- /**
220
- * Returns the path to the file where the cache is persisted
221
- * @method cacheFilePath
222
- * @returns {String}
223
- */
224
- get cacheFilePath() {
225
- return path.resolve(`${this._cacheDir}/${this._cacheId}`);
226
- }
227
- /**
228
- * Returns the path to the cache directory
229
- * @method cacheDirPath
230
- * @returns {String}
231
- */
232
- get cacheDirPath() {
233
- return path.resolve(this._cacheDir);
234
- }
235
- /**
236
- * Returns an array with all the keys in the cache
237
- * @method keys
238
- * @returns {Array}
239
- */
240
- keys() {
241
- return [...this._cache.keys];
242
- }
243
- /**
244
- * (Legacy) set key method. This method will be deprecated in the future
245
- * @method setKey
246
- * @param key {string} the key to set
247
- * @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify
248
- */
249
- // biome-ignore lint/suspicious/noExplicitAny: type format
250
- setKey(key, value, ttl) {
251
- this.set(key, value, ttl);
252
- }
253
- /**
254
- * Sets a key to a given value
255
- * @method set
256
- * @param key {string} the key to set
257
- * @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify
258
- * @param [ttl] {number} the time to live in milliseconds
259
- */
260
- // biome-ignore lint/suspicious/noExplicitAny: type format
261
- set(key, value, ttl) {
262
- this._cache.set(key, value, ttl);
263
- this._changesSinceLastSave = true;
264
- }
265
- /**
266
- * (Legacy) Remove a given key from the cache. This method will be deprecated in the future
267
- * @method removeKey
268
- * @param key {String} the key to remove from the object
269
- */
270
- removeKey(key) {
271
- this.delete(key);
272
- }
273
- /**
274
- * Remove a given key from the cache
275
- * @method delete
276
- * @param key {String} the key to remove from the object
277
- */
278
- delete(key) {
279
- this._cache.delete(key);
280
- this._changesSinceLastSave = true;
281
- this.emit("delete" /* DELETE */, key);
282
- }
283
- /**
284
- * (Legacy) Return the value of the provided key. This method will be deprecated in the future
285
- * @method getKey<T>
286
- * @param key {String} the name of the key to retrieve
287
- * @returns {*} at T the value from the key
288
- */
289
- getKey(key) {
290
- return this.get(key);
291
- }
292
- /**
293
- * Return the value of the provided key
294
- * @method get<T>
295
- * @param key {String} the name of the key to retrieve
296
- * @returns {*} at T the value from the key
297
- */
298
- get(key) {
299
- return this._cache.get(key);
300
- }
301
- /**
302
- * Clear the cache and save the state to disk
303
- * @method clear
304
- */
305
- clear() {
306
- try {
307
- this._cache.clear();
308
- this._changesSinceLastSave = true;
309
- this.save();
310
- this.emit("clear" /* CLEAR */);
311
- } catch (error) {
312
- this.emit("error" /* ERROR */, error);
313
- }
314
- }
315
- /**
316
- * Save the state of the cache identified by the docId to disk
317
- * as a JSON structure
318
- * @method save
319
- */
320
- save(force = false) {
321
- try {
322
- if (this._changesSinceLastSave || force) {
323
- const filePath = this.cacheFilePath;
324
- const items = [...this._cache.items];
325
- const data = this._stringify(items);
326
- if (!fs.existsSync(this._cacheDir)) {
327
- fs.mkdirSync(this._cacheDir, { recursive: true });
328
- }
329
- fs.writeFileSync(filePath, data);
330
- this._changesSinceLastSave = false;
331
- this.emit("save" /* SAVE */);
332
- }
333
- } catch (error) {
334
- this.emit("error" /* ERROR */, error);
335
- }
336
- }
337
- /**
338
- * Remove the file where the cache is persisted
339
- * @method removeCacheFile
340
- * @return {Boolean} true or false if the file was successfully deleted
341
- */
342
- removeCacheFile() {
343
- try {
344
- if (fs.existsSync(this.cacheFilePath)) {
345
- fs.rmSync(this.cacheFilePath);
346
- return true;
347
- }
348
- } catch (error) {
349
- this.emit("error" /* ERROR */, error);
350
- }
351
- return false;
352
- }
353
- /**
354
- * Destroy the cache. This will remove the directory, file, and memory cache
355
- * @method destroy
356
- * @param [includeCacheDir=false] {Boolean} if true, the cache directory will be removed
357
- * @return {undefined}
358
- */
359
- destroy(includeCacheDirectory = false) {
360
- try {
361
- this._cache.clear();
362
- this.stopAutoPersist();
363
- if (includeCacheDirectory) {
364
- fs.rmSync(this.cacheDirPath, { recursive: true, force: true });
365
- } else {
366
- fs.rmSync(this.cacheFilePath, { recursive: true, force: true });
367
- }
368
- this._changesSinceLastSave = false;
369
- this.emit("destroy" /* DESTROY */);
370
- } catch (error) {
371
- this.emit("error" /* ERROR */, error);
372
- }
373
- }
374
- /**
375
- * Start the auto persist interval
376
- * @method startAutoPersist
377
- */
378
- startAutoPersist() {
379
- if (this._persistInterval > 0) {
380
- if (this._persistTimer) {
381
- clearInterval(this._persistTimer);
382
- this._persistTimer = void 0;
383
- }
384
- this._persistTimer = setInterval(() => {
385
- this.save();
386
- }, this._persistInterval);
387
- }
388
- }
389
- /**
390
- * Stop the auto persist interval
391
- * @method stopAutoPersist
392
- */
393
- stopAutoPersist() {
394
- if (this._persistTimer) {
395
- clearInterval(this._persistTimer);
396
- this._persistTimer = void 0;
397
- }
398
- }
399
- };
400
- var FlatCacheDefault = class {
401
- static create = create;
402
- static createFromFile = createFromFile;
403
- static clearCacheById = clearCacheById;
404
- static clearAll = clearAll;
405
- };
406
- function create(options) {
407
- const cache = new FlatCache(options);
408
- cache.load();
409
- return cache;
410
- }
411
- function createFromFile(filePath, options) {
412
- const cache = new FlatCache(options);
413
- cache.loadFile(filePath);
414
- return cache;
415
- }
416
- function clearCacheById(cacheId, cacheDirectory) {
417
- const cache = new FlatCache({ cacheId, cacheDir: cacheDirectory });
418
- cache.destroy();
419
- }
420
- function clearAll(cacheDirectory) {
421
- fs.rmSync(cacheDirectory ?? ".cache", { recursive: true, force: true });
422
- }
423
- export {
424
- FlatCache,
425
- FlatCacheEvents,
426
- clearAll,
427
- clearCacheById,
428
- create,
429
- createFromFile,
430
- FlatCacheDefault as default
431
- };
1
+ import c from"fs";import p from"path";import{CacheableMemory as _}from"cacheable";import{parse as d,stringify as y}from"flatted";import{Hookified as g}from"hookified";var b=(a=>(a.SAVE="save",a.LOAD="load",a.DELETE="delete",a.CLEAR="clear",a.DESTROY="destroy",a.ERROR="error",a.EXPIRED="expired",a))(b||{}),l=class extends g{_cache=new _;_cacheDir=".cache";_cacheId="cache1";_persistInterval=0;_persistTimer;_changesSinceLastSave=!1;_parse=d;_stringify=y;constructor(e){super(),e&&(this._cache=new _({ttl:e.ttl,useClone:e.useClone,lruSize:e.lruSize,checkInterval:e.expirationInterval})),e?.cacheDir&&(this._cacheDir=e.cacheDir),e?.cacheId&&(this._cacheId=e.cacheId),e?.persistInterval&&(this._persistInterval=e.persistInterval,this.startAutoPersist()),e?.deserialize&&(this._parse=e.deserialize),e?.serialize&&(this._stringify=e.serialize)}get cache(){return this._cache}get cacheDir(){return this._cacheDir}set cacheDir(e){this._cacheDir=e}get cacheId(){return this._cacheId}set cacheId(e){this._cacheId=e}get changesSinceLastSave(){return this._changesSinceLastSave}get persistInterval(){return this._persistInterval}set persistInterval(e){this._persistInterval=e}load(e,i){try{let s=p.resolve(`${i??this._cacheDir}/${e??this._cacheId}`);this.loadFile(s),this.emit("load")}catch(s){this.emit("error",s)}}loadFile(e){if(c.existsSync(e)){let i=c.readFileSync(e,"utf8"),s=this._parse(i);if(Array.isArray(s))for(let t of s)t&&typeof t=="object"&&"key"in t&&(t.expires?this._cache.set(t.key,t.value,{expire:t.expires}):t.timestamp?this._cache.set(t.key,t.value,{expire:t.timestamp}):this._cache.set(t.key,t.value));else for(let t of Object.keys(s)){let r=s[t];r&&typeof r=="object"&&"key"in r?this._cache.set(r.key,r.value,{expire:r.expires}):r&&typeof r=="object"&&r.timestamp?this._cache.set(t,r,{expire:r.timestamp}):this._cache.set(t,r)}this._changesSinceLastSave=!0}}loadFileStream(e,i,s,t){if(c.existsSync(e)){let v=c.statSync(e).size,a=0,f="",u=c.createReadStream(e,{encoding:"utf8"});u.on("data",h=>{a+=h.length,f+=h,i(a,v)}),u.on("end",()=>{let h=this._parse(f);for(let o of Object.keys(h))this._cache.set(h[o].key,h[o].value,{expire:h[o].expires});this._changesSinceLastSave=!0,s()}),u.on("error",h=>{this.emit("error",h),t&&t(h)})}else{let r=new Error(`Cache file ${e} does not exist`);this.emit("error",r),t&&t(r)}}all(){let e={},i=[...this._cache.items];for(let s of i)e[s.key]=s.value;return e}get items(){return[...this._cache.items]}get cacheFilePath(){return p.resolve(`${this._cacheDir}/${this._cacheId}`)}get cacheDirPath(){return p.resolve(this._cacheDir)}keys(){return[...this._cache.keys]}setKey(e,i,s){this.set(e,i,s)}set(e,i,s){this._cache.set(e,i,s),this._changesSinceLastSave=!0}removeKey(e){this.delete(e)}delete(e){this._cache.delete(e),this._changesSinceLastSave=!0,this.emit("delete",e)}getKey(e){return this.get(e)}get(e){return this._cache.get(e)}clear(){try{this._cache.clear(),this._changesSinceLastSave=!0,this.save(),this.emit("clear")}catch(e){this.emit("error",e)}}save(e=!1){try{if(this._changesSinceLastSave||e){let i=this.cacheFilePath,s=[...this._cache.items],t=this._stringify(s);c.existsSync(this._cacheDir)||c.mkdirSync(this._cacheDir,{recursive:!0}),c.writeFileSync(i,t),this._changesSinceLastSave=!1,this.emit("save")}}catch(i){this.emit("error",i)}}removeCacheFile(){try{if(c.existsSync(this.cacheFilePath))return c.rmSync(this.cacheFilePath),!0}catch(e){this.emit("error",e)}return!1}destroy(e=!1){try{this._cache.clear(),this.stopAutoPersist(),e?c.rmSync(this.cacheDirPath,{recursive:!0,force:!0}):c.rmSync(this.cacheFilePath,{recursive:!0,force:!0}),this._changesSinceLastSave=!1,this.emit("destroy")}catch(i){this.emit("error",i)}}startAutoPersist(){this._persistInterval>0&&(this._persistTimer&&(clearInterval(this._persistTimer),this._persistTimer=void 0),this._persistTimer=setInterval(()=>{this.save()},this._persistInterval))}stopAutoPersist(){this._persistTimer&&(clearInterval(this._persistTimer),this._persistTimer=void 0)}},m=class{static create=S;static createFromFile=I;static clearCacheById=R;static clearAll=x};function S(n){let e=new l(n);return e.load(),e}function I(n,e){let i=new l(e);return i.loadFile(n),i}function R(n,e){new l({cacheId:n,cacheDir:e}).destroy()}function x(n){c.rmSync(n??".cache",{recursive:!0,force:!0})}export{l as FlatCache,b as FlatCacheEvents,x as clearAll,R as clearCacheById,S as create,I as createFromFile,m as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "flat-cache",
3
- "version": "6.1.17",
3
+ "version": "6.1.18",
4
4
  "description": "A simple key/value storage using files to persist the data",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -64,14 +64,14 @@
64
64
  "dependencies": {
65
65
  "flatted": "^3.3.3",
66
66
  "hookified": "^1.12.0",
67
- "cacheable": "^2.0.3"
67
+ "cacheable": "^2.1.0"
68
68
  },
69
69
  "files": [
70
70
  "dist",
71
71
  "license"
72
72
  ],
73
73
  "scripts": {
74
- "build": "rimraf ./dist && tsup src/index.ts --format cjs,esm --dts --clean",
74
+ "build": "rimraf ./dist && tsup src/index.ts --format cjs,esm --dts --clean --minify",
75
75
  "prepublish": "pnpm build",
76
76
  "lint": "biome check --write --error-on-warnings",
77
77
  "test": "pnpm lint && vitest run --coverage",