Sign In

flat-cache

Package Overview
Dependencies
Maintainers
1
Versions
53
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

flat-cache - npm Package Compare versions

Comparing version
6.1.17
to
6.1.18
+1
-471
dist/index.cjs

@@ -1,471 +0,1 @@

"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
FlatCache: () => FlatCache,
FlatCacheEvents: () => FlatCacheEvents,
clearAll: () => clearAll,
clearCacheById: () => clearCacheById,
create: () => create,
createFromFile: () => createFromFile,
default: () => FlatCacheDefault
});
module.exports = __toCommonJS(index_exports);
var import_node_fs = __toESM(require("fs"), 1);
var import_node_path = __toESM(require("path"), 1);
var import_cacheable = require("cacheable");
var import_flatted = require("flatted");
var import_hookified = require("hookified");
var FlatCacheEvents = /* @__PURE__ */ ((FlatCacheEvents2) => {
FlatCacheEvents2["SAVE"] = "save";
FlatCacheEvents2["LOAD"] = "load";
FlatCacheEvents2["DELETE"] = "delete";
FlatCacheEvents2["CLEAR"] = "clear";
FlatCacheEvents2["DESTROY"] = "destroy";
FlatCacheEvents2["ERROR"] = "error";
FlatCacheEvents2["EXPIRED"] = "expired";
return FlatCacheEvents2;
})(FlatCacheEvents || {});
var FlatCache = class extends import_hookified.Hookified {
_cache = new import_cacheable.CacheableMemory();
_cacheDir = ".cache";
_cacheId = "cache1";
_persistInterval = 0;
_persistTimer;
_changesSinceLastSave = false;
_parse = import_flatted.parse;
_stringify = import_flatted.stringify;
constructor(options) {
super();
if (options) {
this._cache = new import_cacheable.CacheableMemory({
ttl: options.ttl,
useClone: options.useClone,
lruSize: options.lruSize,
checkInterval: options.expirationInterval
});
}
if (options?.cacheDir) {
this._cacheDir = options.cacheDir;
}
if (options?.cacheId) {
this._cacheId = options.cacheId;
}
if (options?.persistInterval) {
this._persistInterval = options.persistInterval;
this.startAutoPersist();
}
if (options?.deserialize) {
this._parse = options.deserialize;
}
if (options?.serialize) {
this._stringify = options.serialize;
}
}
/**
* The cache object
* @property cache
* @type {CacheableMemory}
*/
get cache() {
return this._cache;
}
/**
* The cache directory
* @property cacheDir
* @type {String}
* @default '.cache'
*/
get cacheDir() {
return this._cacheDir;
}
/**
* Set the cache directory
* @property cacheDir
* @type {String}
* @default '.cache'
*/
set cacheDir(value) {
this._cacheDir = value;
}
/**
* The cache id
* @property cacheId
* @type {String}
* @default 'cache1'
*/
get cacheId() {
return this._cacheId;
}
/**
* Set the cache id
* @property cacheId
* @type {String}
* @default 'cache1'
*/
set cacheId(value) {
this._cacheId = value;
}
/**
* The flag to indicate if there are changes since the last save
* @property changesSinceLastSave
* @type {Boolean}
* @default false
*/
get changesSinceLastSave() {
return this._changesSinceLastSave;
}
/**
* The interval to persist the cache to disk. 0 means no timed persistence
* @property persistInterval
* @type {Number}
* @default 0
*/
get persistInterval() {
return this._persistInterval;
}
/**
* Set the interval to persist the cache to disk. 0 means no timed persistence
* @property persistInterval
* @type {Number}
* @default 0
*/
set persistInterval(value) {
this._persistInterval = value;
}
/**
* Load a cache identified by the given Id. If the element does not exists, then initialize an empty
* cache storage. If specified `cacheDir` will be used as the directory to persist the data to. If omitted
* then the cache module directory `.cacheDir` will be used instead
*
* @method load
* @param cacheId {String} the id of the cache, would also be used as the name of the file cache
* @param cacheDir {String} directory for the cache entry
*/
load(cacheId, cacheDir) {
try {
const filePath = import_node_path.default.resolve(
`${cacheDir ?? this._cacheDir}/${cacheId ?? this._cacheId}`
);
this.loadFile(filePath);
this.emit("load" /* LOAD */);
} catch (error) {
this.emit("error" /* ERROR */, error);
}
}
/**
* Load the cache from the provided file
* @method loadFile
* @param {String} pathToFile the path to the file containing the info for the cache
*/
loadFile(pathToFile) {
if (import_node_fs.default.existsSync(pathToFile)) {
const data = import_node_fs.default.readFileSync(pathToFile, "utf8");
const items = this._parse(data);
for (const key of Object.keys(items)) {
this._cache.set(items[key].key, items[key].value, {
expire: items[key].expires
});
}
this._changesSinceLastSave = true;
}
}
loadFileStream(pathToFile, onProgress, onEnd, onError) {
if (import_node_fs.default.existsSync(pathToFile)) {
const stats = import_node_fs.default.statSync(pathToFile);
const total = stats.size;
let loaded = 0;
let streamData = "";
const readStream = import_node_fs.default.createReadStream(pathToFile, { encoding: "utf8" });
readStream.on("data", (chunk) => {
loaded += chunk.length;
streamData += chunk;
onProgress(loaded, total);
});
readStream.on("end", () => {
const items = this._parse(streamData);
for (const key of Object.keys(items)) {
this._cache.set(items[key].key, items[key].value, {
expire: items[key].expires
});
}
this._changesSinceLastSave = true;
onEnd();
});
readStream.on("error", (error) => {
this.emit("error" /* ERROR */, error);
if (onError) {
onError(error);
}
});
} else {
const error = new Error(`Cache file ${pathToFile} does not exist`);
this.emit("error" /* ERROR */, error);
if (onError) {
onError(error);
}
}
}
/**
* Returns the entire persisted object
* @method all
* @returns {*}
*/
all() {
const result = {};
const items = [...this._cache.items];
for (const item of items) {
result[item.key] = item.value;
}
return result;
}
/**
* Returns an array with all the items in the cache { key, value, expires }
* @method items
* @returns {Array}
*/
// biome-ignore lint/suspicious/noExplicitAny: cache items can store any value
get items() {
return [...this._cache.items];
}
/**
* Returns the path to the file where the cache is persisted
* @method cacheFilePath
* @returns {String}
*/
get cacheFilePath() {
return import_node_path.default.resolve(`${this._cacheDir}/${this._cacheId}`);
}
/**
* Returns the path to the cache directory
* @method cacheDirPath
* @returns {String}
*/
get cacheDirPath() {
return import_node_path.default.resolve(this._cacheDir);
}
/**
* Returns an array with all the keys in the cache
* @method keys
* @returns {Array}
*/
keys() {
return [...this._cache.keys];
}
/**
* (Legacy) set key method. This method will be deprecated in the future
* @method setKey
* @param key {string} the key to set
* @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify
*/
// biome-ignore lint/suspicious/noExplicitAny: type format
setKey(key, value, ttl) {
this.set(key, value, ttl);
}
/**
* Sets a key to a given value
* @method set
* @param key {string} the key to set
* @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify
* @param [ttl] {number} the time to live in milliseconds
*/
// biome-ignore lint/suspicious/noExplicitAny: type format
set(key, value, ttl) {
this._cache.set(key, value, ttl);
this._changesSinceLastSave = true;
}
/**
* (Legacy) Remove a given key from the cache. This method will be deprecated in the future
* @method removeKey
* @param key {String} the key to remove from the object
*/
removeKey(key) {
this.delete(key);
}
/**
* Remove a given key from the cache
* @method delete
* @param key {String} the key to remove from the object
*/
delete(key) {
this._cache.delete(key);
this._changesSinceLastSave = true;
this.emit("delete" /* DELETE */, key);
}
/**
* (Legacy) Return the value of the provided key. This method will be deprecated in the future
* @method getKey<T>
* @param key {String} the name of the key to retrieve
* @returns {*} at T the value from the key
*/
getKey(key) {
return this.get(key);
}
/**
* Return the value of the provided key
* @method get<T>
* @param key {String} the name of the key to retrieve
* @returns {*} at T the value from the key
*/
get(key) {
return this._cache.get(key);
}
/**
* Clear the cache and save the state to disk
* @method clear
*/
clear() {
try {
this._cache.clear();
this._changesSinceLastSave = true;
this.save();
this.emit("clear" /* CLEAR */);
} catch (error) {
this.emit("error" /* ERROR */, error);
}
}
/**
* Save the state of the cache identified by the docId to disk
* as a JSON structure
* @method save
*/
save(force = false) {
try {
if (this._changesSinceLastSave || force) {
const filePath = this.cacheFilePath;
const items = [...this._cache.items];
const data = this._stringify(items);
if (!import_node_fs.default.existsSync(this._cacheDir)) {
import_node_fs.default.mkdirSync(this._cacheDir, { recursive: true });
}
import_node_fs.default.writeFileSync(filePath, data);
this._changesSinceLastSave = false;
this.emit("save" /* SAVE */);
}
} catch (error) {
this.emit("error" /* ERROR */, error);
}
}
/**
* Remove the file where the cache is persisted
* @method removeCacheFile
* @return {Boolean} true or false if the file was successfully deleted
*/
removeCacheFile() {
try {
if (import_node_fs.default.existsSync(this.cacheFilePath)) {
import_node_fs.default.rmSync(this.cacheFilePath);
return true;
}
} catch (error) {
this.emit("error" /* ERROR */, error);
}
return false;
}
/**
* Destroy the cache. This will remove the directory, file, and memory cache
* @method destroy
* @param [includeCacheDir=false] {Boolean} if true, the cache directory will be removed
* @return {undefined}
*/
destroy(includeCacheDirectory = false) {
try {
this._cache.clear();
this.stopAutoPersist();
if (includeCacheDirectory) {
import_node_fs.default.rmSync(this.cacheDirPath, { recursive: true, force: true });
} else {
import_node_fs.default.rmSync(this.cacheFilePath, { recursive: true, force: true });
}
this._changesSinceLastSave = false;
this.emit("destroy" /* DESTROY */);
} catch (error) {
this.emit("error" /* ERROR */, error);
}
}
/**
* Start the auto persist interval
* @method startAutoPersist
*/
startAutoPersist() {
if (this._persistInterval > 0) {
if (this._persistTimer) {
clearInterval(this._persistTimer);
this._persistTimer = void 0;
}
this._persistTimer = setInterval(() => {
this.save();
}, this._persistInterval);
}
}
/**
* Stop the auto persist interval
* @method stopAutoPersist
*/
stopAutoPersist() {
if (this._persistTimer) {
clearInterval(this._persistTimer);
this._persistTimer = void 0;
}
}
};
var FlatCacheDefault = class {
static create = create;
static createFromFile = createFromFile;
static clearCacheById = clearCacheById;
static clearAll = clearAll;
};
function create(options) {
const cache = new FlatCache(options);
cache.load();
return cache;
}
function createFromFile(filePath, options) {
const cache = new FlatCache(options);
cache.loadFile(filePath);
return cache;
}
function clearCacheById(cacheId, cacheDirectory) {
const cache = new FlatCache({ cacheId, cacheDir: cacheDirectory });
cache.destroy();
}
function clearAll(cacheDirectory) {
import_node_fs.default.rmSync(cacheDirectory ?? ".cache", { recursive: true, force: true });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
FlatCache,
FlatCacheEvents,
clearAll,
clearCacheById,
create,
createFromFile
});
"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});

@@ -1,431 +0,1 @@

// src/index.ts
import fs from "fs";
import path from "path";
import { CacheableMemory } from "cacheable";
import { parse, stringify } from "flatted";
import { Hookified } from "hookified";
var FlatCacheEvents = /* @__PURE__ */ ((FlatCacheEvents2) => {
FlatCacheEvents2["SAVE"] = "save";
FlatCacheEvents2["LOAD"] = "load";
FlatCacheEvents2["DELETE"] = "delete";
FlatCacheEvents2["CLEAR"] = "clear";
FlatCacheEvents2["DESTROY"] = "destroy";
FlatCacheEvents2["ERROR"] = "error";
FlatCacheEvents2["EXPIRED"] = "expired";
return FlatCacheEvents2;
})(FlatCacheEvents || {});
var FlatCache = class extends Hookified {
_cache = new CacheableMemory();
_cacheDir = ".cache";
_cacheId = "cache1";
_persistInterval = 0;
_persistTimer;
_changesSinceLastSave = false;
_parse = parse;
_stringify = stringify;
constructor(options) {
super();
if (options) {
this._cache = new CacheableMemory({
ttl: options.ttl,
useClone: options.useClone,
lruSize: options.lruSize,
checkInterval: options.expirationInterval
});
}
if (options?.cacheDir) {
this._cacheDir = options.cacheDir;
}
if (options?.cacheId) {
this._cacheId = options.cacheId;
}
if (options?.persistInterval) {
this._persistInterval = options.persistInterval;
this.startAutoPersist();
}
if (options?.deserialize) {
this._parse = options.deserialize;
}
if (options?.serialize) {
this._stringify = options.serialize;
}
}
/**
* The cache object
* @property cache
* @type {CacheableMemory}
*/
get cache() {
return this._cache;
}
/**
* The cache directory
* @property cacheDir
* @type {String}
* @default '.cache'
*/
get cacheDir() {
return this._cacheDir;
}
/**
* Set the cache directory
* @property cacheDir
* @type {String}
* @default '.cache'
*/
set cacheDir(value) {
this._cacheDir = value;
}
/**
* The cache id
* @property cacheId
* @type {String}
* @default 'cache1'
*/
get cacheId() {
return this._cacheId;
}
/**
* Set the cache id
* @property cacheId
* @type {String}
* @default 'cache1'
*/
set cacheId(value) {
this._cacheId = value;
}
/**
* The flag to indicate if there are changes since the last save
* @property changesSinceLastSave
* @type {Boolean}
* @default false
*/
get changesSinceLastSave() {
return this._changesSinceLastSave;
}
/**
* The interval to persist the cache to disk. 0 means no timed persistence
* @property persistInterval
* @type {Number}
* @default 0
*/
get persistInterval() {
return this._persistInterval;
}
/**
* Set the interval to persist the cache to disk. 0 means no timed persistence
* @property persistInterval
* @type {Number}
* @default 0
*/
set persistInterval(value) {
this._persistInterval = value;
}
/**
* Load a cache identified by the given Id. If the element does not exists, then initialize an empty
* cache storage. If specified `cacheDir` will be used as the directory to persist the data to. If omitted
* then the cache module directory `.cacheDir` will be used instead
*
* @method load
* @param cacheId {String} the id of the cache, would also be used as the name of the file cache
* @param cacheDir {String} directory for the cache entry
*/
load(cacheId, cacheDir) {
try {
const filePath = path.resolve(
`${cacheDir ?? this._cacheDir}/${cacheId ?? this._cacheId}`
);
this.loadFile(filePath);
this.emit("load" /* LOAD */);
} catch (error) {
this.emit("error" /* ERROR */, error);
}
}
/**
* Load the cache from the provided file
* @method loadFile
* @param {String} pathToFile the path to the file containing the info for the cache
*/
loadFile(pathToFile) {
if (fs.existsSync(pathToFile)) {
const data = fs.readFileSync(pathToFile, "utf8");
const items = this._parse(data);
for (const key of Object.keys(items)) {
this._cache.set(items[key].key, items[key].value, {
expire: items[key].expires
});
}
this._changesSinceLastSave = true;
}
}
loadFileStream(pathToFile, onProgress, onEnd, onError) {
if (fs.existsSync(pathToFile)) {
const stats = fs.statSync(pathToFile);
const total = stats.size;
let loaded = 0;
let streamData = "";
const readStream = fs.createReadStream(pathToFile, { encoding: "utf8" });
readStream.on("data", (chunk) => {
loaded += chunk.length;
streamData += chunk;
onProgress(loaded, total);
});
readStream.on("end", () => {
const items = this._parse(streamData);
for (const key of Object.keys(items)) {
this._cache.set(items[key].key, items[key].value, {
expire: items[key].expires
});
}
this._changesSinceLastSave = true;
onEnd();
});
readStream.on("error", (error) => {
this.emit("error" /* ERROR */, error);
if (onError) {
onError(error);
}
});
} else {
const error = new Error(`Cache file ${pathToFile} does not exist`);
this.emit("error" /* ERROR */, error);
if (onError) {
onError(error);
}
}
}
/**
* Returns the entire persisted object
* @method all
* @returns {*}
*/
all() {
const result = {};
const items = [...this._cache.items];
for (const item of items) {
result[item.key] = item.value;
}
return result;
}
/**
* Returns an array with all the items in the cache { key, value, expires }
* @method items
* @returns {Array}
*/
// biome-ignore lint/suspicious/noExplicitAny: cache items can store any value
get items() {
return [...this._cache.items];
}
/**
* Returns the path to the file where the cache is persisted
* @method cacheFilePath
* @returns {String}
*/
get cacheFilePath() {
return path.resolve(`${this._cacheDir}/${this._cacheId}`);
}
/**
* Returns the path to the cache directory
* @method cacheDirPath
* @returns {String}
*/
get cacheDirPath() {
return path.resolve(this._cacheDir);
}
/**
* Returns an array with all the keys in the cache
* @method keys
* @returns {Array}
*/
keys() {
return [...this._cache.keys];
}
/**
* (Legacy) set key method. This method will be deprecated in the future
* @method setKey
* @param key {string} the key to set
* @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify
*/
// biome-ignore lint/suspicious/noExplicitAny: type format
setKey(key, value, ttl) {
this.set(key, value, ttl);
}
/**
* Sets a key to a given value
* @method set
* @param key {string} the key to set
* @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify
* @param [ttl] {number} the time to live in milliseconds
*/
// biome-ignore lint/suspicious/noExplicitAny: type format
set(key, value, ttl) {
this._cache.set(key, value, ttl);
this._changesSinceLastSave = true;
}
/**
* (Legacy) Remove a given key from the cache. This method will be deprecated in the future
* @method removeKey
* @param key {String} the key to remove from the object
*/
removeKey(key) {
this.delete(key);
}
/**
* Remove a given key from the cache
* @method delete
* @param key {String} the key to remove from the object
*/
delete(key) {
this._cache.delete(key);
this._changesSinceLastSave = true;
this.emit("delete" /* DELETE */, key);
}
/**
* (Legacy) Return the value of the provided key. This method will be deprecated in the future
* @method getKey<T>
* @param key {String} the name of the key to retrieve
* @returns {*} at T the value from the key
*/
getKey(key) {
return this.get(key);
}
/**
* Return the value of the provided key
* @method get<T>
* @param key {String} the name of the key to retrieve
* @returns {*} at T the value from the key
*/
get(key) {
return this._cache.get(key);
}
/**
* Clear the cache and save the state to disk
* @method clear
*/
clear() {
try {
this._cache.clear();
this._changesSinceLastSave = true;
this.save();
this.emit("clear" /* CLEAR */);
} catch (error) {
this.emit("error" /* ERROR */, error);
}
}
/**
* Save the state of the cache identified by the docId to disk
* as a JSON structure
* @method save
*/
save(force = false) {
try {
if (this._changesSinceLastSave || force) {
const filePath = this.cacheFilePath;
const items = [...this._cache.items];
const data = this._stringify(items);
if (!fs.existsSync(this._cacheDir)) {
fs.mkdirSync(this._cacheDir, { recursive: true });
}
fs.writeFileSync(filePath, data);
this._changesSinceLastSave = false;
this.emit("save" /* SAVE */);
}
} catch (error) {
this.emit("error" /* ERROR */, error);
}
}
/**
* Remove the file where the cache is persisted
* @method removeCacheFile
* @return {Boolean} true or false if the file was successfully deleted
*/
removeCacheFile() {
try {
if (fs.existsSync(this.cacheFilePath)) {
fs.rmSync(this.cacheFilePath);
return true;
}
} catch (error) {
this.emit("error" /* ERROR */, error);
}
return false;
}
/**
* Destroy the cache. This will remove the directory, file, and memory cache
* @method destroy
* @param [includeCacheDir=false] {Boolean} if true, the cache directory will be removed
* @return {undefined}
*/
destroy(includeCacheDirectory = false) {
try {
this._cache.clear();
this.stopAutoPersist();
if (includeCacheDirectory) {
fs.rmSync(this.cacheDirPath, { recursive: true, force: true });
} else {
fs.rmSync(this.cacheFilePath, { recursive: true, force: true });
}
this._changesSinceLastSave = false;
this.emit("destroy" /* DESTROY */);
} catch (error) {
this.emit("error" /* ERROR */, error);
}
}
/**
* Start the auto persist interval
* @method startAutoPersist
*/
startAutoPersist() {
if (this._persistInterval > 0) {
if (this._persistTimer) {
clearInterval(this._persistTimer);
this._persistTimer = void 0;
}
this._persistTimer = setInterval(() => {
this.save();
}, this._persistInterval);
}
}
/**
* Stop the auto persist interval
* @method stopAutoPersist
*/
stopAutoPersist() {
if (this._persistTimer) {
clearInterval(this._persistTimer);
this._persistTimer = void 0;
}
}
};
var FlatCacheDefault = class {
static create = create;
static createFromFile = createFromFile;
static clearCacheById = clearCacheById;
static clearAll = clearAll;
};
function create(options) {
const cache = new FlatCache(options);
cache.load();
return cache;
}
function createFromFile(filePath, options) {
const cache = new FlatCache(options);
cache.loadFile(filePath);
return cache;
}
function clearCacheById(cacheId, cacheDirectory) {
const cache = new FlatCache({ cacheId, cacheDir: cacheDirectory });
cache.destroy();
}
function clearAll(cacheDirectory) {
fs.rmSync(cacheDirectory ?? ".cache", { recursive: true, force: true });
}
export {
FlatCache,
FlatCacheEvents,
clearAll,
clearCacheById,
create,
createFromFile,
FlatCacheDefault as default
};
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};
+3
-3
{
"name": "flat-cache",
"version": "6.1.17",
"version": "6.1.18",
"description": "A simple key/value storage using files to persist the data",

@@ -67,3 +67,3 @@ "type": "module",

"hookified": "^1.12.0",
"cacheable": "^2.0.3"
"cacheable": "^2.1.0"
},

@@ -75,3 +75,3 @@ "files": [

"scripts": {
"build": "rimraf ./dist && tsup src/index.ts --format cjs,esm --dts --clean",
"build": "rimraf ./dist && tsup src/index.ts --format cjs,esm --dts --clean --minify",
"prepublish": "pnpm build",

@@ -78,0 +78,0 @@ "lint": "biome check --write --error-on-warnings",