@greenborn/greenborn-memory-cache 0.0.0-stage → 1.0.1
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/LICENSE +21 -0
- package/README.md +85 -2
- package/dist/index.cjs +217 -0
- package/dist/index.cjs.map +7 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +190 -0
- package/dist/index.js.map +7 -0
- package/package.json +58 -4
- package/src/MemoryCache.js +216 -0
- package/src/index.js +4 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 2012lucho
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,86 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @greenborn/greenborn-memory-cache
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Caché en memoria para el lado del servidor en Node.js. TTL por entrada, eventos y limpieza periódica automática. Sin dependencias de runtime (usa `node:events`).
|
|
4
|
+
|
|
5
|
+
## Instalación
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @greenborn/greenborn-memory-cache
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Uso
|
|
12
|
+
|
|
13
|
+
### ESModules
|
|
14
|
+
|
|
15
|
+
```js
|
|
16
|
+
import MemoryCache from '@greenborn/greenborn-memory-cache';
|
|
17
|
+
|
|
18
|
+
const cache = new MemoryCache({ ttlMs: 60_000 });
|
|
19
|
+
cache.set('usuario', { id: 1, nombre: 'Lucho' });
|
|
20
|
+
const usuario = cache.get('usuario'); // { id: 1, nombre: 'Lucho' }
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
### CommonJS
|
|
24
|
+
|
|
25
|
+
```js
|
|
26
|
+
const MemoryCache = require('@greenborn/greenborn-memory-cache');
|
|
27
|
+
|
|
28
|
+
const cache = new MemoryCache();
|
|
29
|
+
cache.set('clave', 'valor');
|
|
30
|
+
console.log(cache.get('clave')); // 'valor'
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## API
|
|
34
|
+
|
|
35
|
+
### `new MemoryCache(options?)`
|
|
36
|
+
|
|
37
|
+
| Opción | Tipo | Default | Descripción |
|
|
38
|
+
|--------|------|---------|-------------|
|
|
39
|
+
| `ttlMs` | `number` | `0` | TTL por defecto en ms. `0` = no expira. |
|
|
40
|
+
| `cleanupIntervalMs` | `number` | `60000` | Intervalo de limpieza periódica en ms. `0` = desactivada. |
|
|
41
|
+
| `maxSize` | `number` | `0` | Máximo de entradas. `0` = ilimitado. Al llenarse expulsa la menos usada (LRU). |
|
|
42
|
+
|
|
43
|
+
### Métodos
|
|
44
|
+
|
|
45
|
+
| Método | Descripción |
|
|
46
|
+
|--------|-------------|
|
|
47
|
+
| `set(key, value, ttlMs?)` | Guarda/actualiza una entrada. `ttlMs` anula el por defecto. Devuelve `this`. |
|
|
48
|
+
| `get(key)` | Lee una entrada. Devuelve `undefined` si no existe o expiró (purga perezosa). |
|
|
49
|
+
| `has(key)` | `true` si la clave existe y no expiró. |
|
|
50
|
+
| `delete(key)` | Elimina una entrada. Devuelve `true` si existía. |
|
|
51
|
+
| `clear()` | Vacía la caché. Devuelve la cantidad de entradas eliminadas. |
|
|
52
|
+
| `cleanup()` | Elimina todas las expiradas manualmente. Devuelve el número eliminado. |
|
|
53
|
+
| `keys()` | Array de claves de entradas vivas. |
|
|
54
|
+
| `destroy()` | Detiene la limpieza periódica y libera listeners. |
|
|
55
|
+
|
|
56
|
+
### Propiedades
|
|
57
|
+
|
|
58
|
+
- `size` — cantidad de entradas vivas (getter).
|
|
59
|
+
|
|
60
|
+
### Eventos
|
|
61
|
+
|
|
62
|
+
La instancia es un `EventEmitter`:
|
|
63
|
+
|
|
64
|
+
| Evento | Payload | Descripción |
|
|
65
|
+
|--------|---------|-------------|
|
|
66
|
+
| `'set'` | `{ key, value, ttlMs, exists }` | Se registra/actualiza una entrada. |
|
|
67
|
+
| `'get'` | `{ key }` | Se lee una entrada existente y viva. |
|
|
68
|
+
| `'delete'` | `{ key }` | Se elimina una entrada. |
|
|
69
|
+
| `'clear'` | `{ count }` | Se vacía la caché. |
|
|
70
|
+
| `'expired'` | `{ key }` | Una entrada expiró (purga perezosa o limpieza periódica). |
|
|
71
|
+
| `'evicted'` | `{ key }` | Una entrada fue expulsada por `maxSize` (LRU). |
|
|
72
|
+
|
|
73
|
+
```js
|
|
74
|
+
cache.on('expired', ({ key }) => console.log(`Expirada: ${key}`));
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Scripts
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
npm run build # genera dist/ (ESM + CJS + .d.ts)
|
|
81
|
+
npm test # ejecuta la suite con node:test
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## Licencia
|
|
85
|
+
|
|
86
|
+
MIT
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __export = (target, all) => {
|
|
6
|
+
for (var name in all)
|
|
7
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
8
|
+
};
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
18
|
+
|
|
19
|
+
// src/index.js
|
|
20
|
+
var src_exports = {};
|
|
21
|
+
__export(src_exports, {
|
|
22
|
+
MemoryCache: () => MemoryCache,
|
|
23
|
+
default: () => src_default
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(src_exports);
|
|
26
|
+
|
|
27
|
+
// src/MemoryCache.js
|
|
28
|
+
var import_node_events = require("node:events");
|
|
29
|
+
var import_node_perf_hooks = require("node:perf_hooks");
|
|
30
|
+
var DEFAULT_CLEANUP_INTERVAL_MS = 6e4;
|
|
31
|
+
var MemoryCache = class extends import_node_events.EventEmitter {
|
|
32
|
+
/**
|
|
33
|
+
* @param {object} [options]
|
|
34
|
+
* @param {number} [options.ttlMs=0] TTL por defecto en milisegundos (0 = no expira).
|
|
35
|
+
* @param {number} [options.cleanupIntervalMs=60000] Intervalo de limpieza periódica en ms (0 = desactivada).
|
|
36
|
+
* @param {number} [options.maxSize=0] Tamaño máximo de entradas (0 = ilimitado). Al llenarse evita la entrada menos recientemente usada.
|
|
37
|
+
*/
|
|
38
|
+
constructor({ ttlMs = 0, cleanupIntervalMs = DEFAULT_CLEANUP_INTERVAL_MS, maxSize = 0 } = {}) {
|
|
39
|
+
super();
|
|
40
|
+
this.ttlMs = ttlMs;
|
|
41
|
+
this.maxSize = maxSize;
|
|
42
|
+
this._store = /* @__PURE__ */ new Map();
|
|
43
|
+
this._timer = null;
|
|
44
|
+
if (cleanupIntervalMs > 0) {
|
|
45
|
+
this._timer = setInterval(() => this.cleanup(), cleanupIntervalMs);
|
|
46
|
+
if (typeof this._timer.unref === "function") {
|
|
47
|
+
this._timer.unref();
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Devuelve el TTL en milisegundos de una entrada, usando el override por
|
|
53
|
+
* entrada si se indicó, o el TTL por defecto de la caché.
|
|
54
|
+
* @private
|
|
55
|
+
*/
|
|
56
|
+
_resolveTtl(ttlMs) {
|
|
57
|
+
return ttlMs === void 0 ? this.ttlMs : ttlMs;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Registra o reemplaza una entrada.
|
|
61
|
+
* @param {string} key
|
|
62
|
+
* @param {unknown} value
|
|
63
|
+
* @param {number} [ttlMs] TTL específico en ms (anula el por defecto).
|
|
64
|
+
* @returns {this}
|
|
65
|
+
*/
|
|
66
|
+
set(key, value, ttlMs) {
|
|
67
|
+
if (key === void 0 || key === null) {
|
|
68
|
+
throw new TypeError("MemoryCache#set: la clave no puede ser null/undefined");
|
|
69
|
+
}
|
|
70
|
+
const resolvedTtl = this._resolveTtl(ttlMs);
|
|
71
|
+
const expiresAt = resolvedTtl > 0 ? Date.now() + resolvedTtl : Infinity;
|
|
72
|
+
const record = { value, expiresAt, lastAccess: import_node_perf_hooks.performance.now() };
|
|
73
|
+
const exists = this._store.has(key);
|
|
74
|
+
this._store.set(key, record);
|
|
75
|
+
this._evictIfNeeded();
|
|
76
|
+
this.emit("set", { key, value, ttlMs: resolvedTtl, exists });
|
|
77
|
+
return this;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Lee una entrada. Si está expirada la elimina (perezoso) y emite 'expired'.
|
|
81
|
+
* @param {string} key
|
|
82
|
+
* @returns {unknown | undefined}
|
|
83
|
+
*/
|
|
84
|
+
get(key) {
|
|
85
|
+
const record = this._store.get(key);
|
|
86
|
+
if (!record) return void 0;
|
|
87
|
+
if (this._isExpired(record)) {
|
|
88
|
+
this._delete(key);
|
|
89
|
+
this.emit("expired", { key });
|
|
90
|
+
return void 0;
|
|
91
|
+
}
|
|
92
|
+
record.lastAccess = import_node_perf_hooks.performance.now();
|
|
93
|
+
this.emit("get", { key });
|
|
94
|
+
return record.value;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Indica si la clave existe y no está expirada.
|
|
98
|
+
* @param {string} key
|
|
99
|
+
* @returns {boolean}
|
|
100
|
+
*/
|
|
101
|
+
has(key) {
|
|
102
|
+
const record = this._store.get(key);
|
|
103
|
+
if (!record) return false;
|
|
104
|
+
if (this._isExpired(record)) {
|
|
105
|
+
this._delete(key);
|
|
106
|
+
this.emit("expired", { key });
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Elimina una entrada. Emite 'delete' solo si existía.
|
|
113
|
+
* @param {string} key
|
|
114
|
+
* @returns {boolean} true si existía y fue eliminada.
|
|
115
|
+
*/
|
|
116
|
+
delete(key) {
|
|
117
|
+
const existed = this._store.has(key);
|
|
118
|
+
if (existed) {
|
|
119
|
+
this._delete(key);
|
|
120
|
+
this.emit("delete", { key });
|
|
121
|
+
}
|
|
122
|
+
return existed;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Vacía la caché por completo. Emite 'clear' solo si había entradas.
|
|
126
|
+
* @returns {number} cantidad de entradas eliminadas.
|
|
127
|
+
*/
|
|
128
|
+
clear() {
|
|
129
|
+
const count = this._store.size;
|
|
130
|
+
if (count > 0) {
|
|
131
|
+
this._store.clear();
|
|
132
|
+
this.emit("clear", { count });
|
|
133
|
+
}
|
|
134
|
+
return count;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Elimina todas las entradas expiradas. Emite 'expired' por cada una.
|
|
138
|
+
* @returns {number} cantidad de entradas expiradas eliminadas.
|
|
139
|
+
*/
|
|
140
|
+
cleanup() {
|
|
141
|
+
const now = Date.now();
|
|
142
|
+
let removed = 0;
|
|
143
|
+
for (const [key, record] of this._store) {
|
|
144
|
+
if (record.expiresAt <= now) {
|
|
145
|
+
this._store.delete(key);
|
|
146
|
+
removed += 1;
|
|
147
|
+
this.emit("expired", { key });
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return removed;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Cantidad de entradas vivas (sin contar expiradas pendientes de purga).
|
|
154
|
+
* @returns {number}
|
|
155
|
+
*/
|
|
156
|
+
get size() {
|
|
157
|
+
return this._store.size;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Lista de claves de entradas vivas.
|
|
161
|
+
* @returns {string[]}
|
|
162
|
+
*/
|
|
163
|
+
keys() {
|
|
164
|
+
return Array.from(this._store.keys());
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Detiene la limpieza periódica y libera el temporizador.
|
|
168
|
+
*/
|
|
169
|
+
destroy() {
|
|
170
|
+
if (this._timer) {
|
|
171
|
+
clearInterval(this._timer);
|
|
172
|
+
this._timer = null;
|
|
173
|
+
}
|
|
174
|
+
this.removeAllListeners();
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* @private
|
|
178
|
+
*/
|
|
179
|
+
_delete(key) {
|
|
180
|
+
this._store.delete(key);
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* @private
|
|
184
|
+
*/
|
|
185
|
+
_isExpired(record) {
|
|
186
|
+
return record.expiresAt <= Date.now();
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Si hay maxSize y la caché lo supera, expulsa la entrada menos
|
|
190
|
+
* recientemente usada. Emite 'evicted'.
|
|
191
|
+
* @private
|
|
192
|
+
*/
|
|
193
|
+
_evictIfNeeded() {
|
|
194
|
+
if (this.maxSize <= 0 || this._store.size <= this.maxSize) return;
|
|
195
|
+
let lruKey = null;
|
|
196
|
+
let lruAccess = Infinity;
|
|
197
|
+
for (const [key, record] of this._store) {
|
|
198
|
+
if (record.lastAccess < lruAccess) {
|
|
199
|
+
lruAccess = record.lastAccess;
|
|
200
|
+
lruKey = key;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
if (lruKey !== null) {
|
|
204
|
+
this._delete(lruKey);
|
|
205
|
+
this.emit("evicted", { key: lruKey });
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
// src/index.js
|
|
211
|
+
var src_default = MemoryCache;
|
|
212
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
213
|
+
0 && (module.exports = {
|
|
214
|
+
MemoryCache
|
|
215
|
+
});
|
|
216
|
+
module.exports = module.exports.default;
|
|
217
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/index.js", "../src/MemoryCache.js"],
|
|
4
|
+
"sourcesContent": ["import { MemoryCache } from './MemoryCache.js';\n\nexport { MemoryCache };\nexport default MemoryCache;\n", "import { EventEmitter } from 'node:events';\nimport { performance } from 'node:perf_hooks';\n\nconst DEFAULT_CLEANUP_INTERVAL_MS = 60_000;\n\n/**\n * Cach\u00E9 en memoria para el lado del servidor.\n *\n * - TTL por entrada (0 = sin expiraci\u00F3n).\n * - Expiraci\u00F3n perezosa al leer (get/has) + limpieza peri\u00F3dica autom\u00E1tica.\n * - Emite eventos: 'set', 'get', 'delete', 'clear', 'expired', 'evicted'.\n *\n * @extends EventEmitter\n */\nexport class MemoryCache extends EventEmitter {\n /**\n * @param {object} [options]\n * @param {number} [options.ttlMs=0] TTL por defecto en milisegundos (0 = no expira).\n * @param {number} [options.cleanupIntervalMs=60000] Intervalo de limpieza peri\u00F3dica en ms (0 = desactivada).\n * @param {number} [options.maxSize=0] Tama\u00F1o m\u00E1ximo de entradas (0 = ilimitado). Al llenarse evita la entrada menos recientemente usada.\n */\n constructor({ ttlMs = 0, cleanupIntervalMs = DEFAULT_CLEANUP_INTERVAL_MS, maxSize = 0 } = {}) {\n super();\n this.ttlMs = ttlMs;\n this.maxSize = maxSize;\n /** @type {Map<string, { value: unknown, expiresAt: number, lastAccess: number }>} */\n this._store = new Map();\n this._timer = null;\n\n if (cleanupIntervalMs > 0) {\n this._timer = setInterval(() => this.cleanup(), cleanupIntervalMs);\n if (typeof this._timer.unref === 'function') {\n this._timer.unref();\n }\n }\n }\n\n /**\n * Devuelve el TTL en milisegundos de una entrada, usando el override por\n * entrada si se indic\u00F3, o el TTL por defecto de la cach\u00E9.\n * @private\n */\n _resolveTtl(ttlMs) {\n return ttlMs === undefined ? this.ttlMs : ttlMs;\n }\n\n /**\n * Registra o reemplaza una entrada.\n * @param {string} key\n * @param {unknown} value\n * @param {number} [ttlMs] TTL espec\u00EDfico en ms (anula el por defecto).\n * @returns {this}\n */\n set(key, value, ttlMs) {\n if (key === undefined || key === null) {\n throw new TypeError('MemoryCache#set: la clave no puede ser null/undefined');\n }\n const resolvedTtl = this._resolveTtl(ttlMs);\n const expiresAt = resolvedTtl > 0 ? Date.now() + resolvedTtl : Infinity;\n const record = { value, expiresAt, lastAccess: performance.now() };\n\n const exists = this._store.has(key);\n this._store.set(key, record);\n this._evictIfNeeded();\n this.emit('set', { key, value, ttlMs: resolvedTtl, exists });\n return this;\n }\n\n /**\n * Lee una entrada. Si est\u00E1 expirada la elimina (perezoso) y emite 'expired'.\n * @param {string} key\n * @returns {unknown | undefined}\n */\n get(key) {\n const record = this._store.get(key);\n if (!record) return undefined;\n\n if (this._isExpired(record)) {\n this._delete(key);\n this.emit('expired', { key });\n return undefined;\n }\n\n record.lastAccess = performance.now();\n this.emit('get', { key });\n return record.value;\n }\n\n /**\n * Indica si la clave existe y no est\u00E1 expirada.\n * @param {string} key\n * @returns {boolean}\n */\n has(key) {\n const record = this._store.get(key);\n if (!record) return false;\n\n if (this._isExpired(record)) {\n this._delete(key);\n this.emit('expired', { key });\n return false;\n }\n\n return true;\n }\n\n /**\n * Elimina una entrada. Emite 'delete' solo si exist\u00EDa.\n * @param {string} key\n * @returns {boolean} true si exist\u00EDa y fue eliminada.\n */\n delete(key) {\n const existed = this._store.has(key);\n if (existed) {\n this._delete(key);\n this.emit('delete', { key });\n }\n return existed;\n }\n\n /**\n * Vac\u00EDa la cach\u00E9 por completo. Emite 'clear' solo si hab\u00EDa entradas.\n * @returns {number} cantidad de entradas eliminadas.\n */\n clear() {\n const count = this._store.size;\n if (count > 0) {\n this._store.clear();\n this.emit('clear', { count });\n }\n return count;\n }\n\n /**\n * Elimina todas las entradas expiradas. Emite 'expired' por cada una.\n * @returns {number} cantidad de entradas expiradas eliminadas.\n */\n cleanup() {\n const now = Date.now();\n let removed = 0;\n for (const [key, record] of this._store) {\n if (record.expiresAt <= now) {\n this._store.delete(key);\n removed += 1;\n this.emit('expired', { key });\n }\n }\n return removed;\n }\n\n /**\n * Cantidad de entradas vivas (sin contar expiradas pendientes de purga).\n * @returns {number}\n */\n get size() {\n return this._store.size;\n }\n\n /**\n * Lista de claves de entradas vivas.\n * @returns {string[]}\n */\n keys() {\n return Array.from(this._store.keys());\n }\n\n /**\n * Detiene la limpieza peri\u00F3dica y libera el temporizador.\n */\n destroy() {\n if (this._timer) {\n clearInterval(this._timer);\n this._timer = null;\n }\n this.removeAllListeners();\n }\n\n /**\n * @private\n */\n _delete(key) {\n this._store.delete(key);\n }\n\n /**\n * @private\n */\n _isExpired(record) {\n return record.expiresAt <= Date.now();\n }\n\n /**\n * Si hay maxSize y la cach\u00E9 lo supera, expulsa la entrada menos\n * recientemente usada. Emite 'evicted'.\n * @private\n */\n _evictIfNeeded() {\n if (this.maxSize <= 0 || this._store.size <= this.maxSize) return;\n\n let lruKey = null;\n let lruAccess = Infinity;\n for (const [key, record] of this._store) {\n if (record.lastAccess < lruAccess) {\n lruAccess = record.lastAccess;\n lruKey = key;\n }\n }\n\n if (lruKey !== null) {\n this._delete(lruKey);\n this.emit('evicted', { key: lruKey });\n }\n }\n}\n\nexport default MemoryCache;\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,yBAA6B;AAC7B,6BAA4B;AAE5B,IAAM,8BAA8B;AAW7B,IAAM,cAAN,cAA0B,gCAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO5C,YAAY,EAAE,QAAQ,GAAG,oBAAoB,6BAA6B,UAAU,EAAE,IAAI,CAAC,GAAG;AAC5F,UAAM;AACN,SAAK,QAAQ;AACb,SAAK,UAAU;AAEf,SAAK,SAAS,oBAAI,IAAI;AACtB,SAAK,SAAS;AAEd,QAAI,oBAAoB,GAAG;AACzB,WAAK,SAAS,YAAY,MAAM,KAAK,QAAQ,GAAG,iBAAiB;AACjE,UAAI,OAAO,KAAK,OAAO,UAAU,YAAY;AAC3C,aAAK,OAAO,MAAM;AAAA,MACpB;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,YAAY,OAAO;AACjB,WAAO,UAAU,SAAY,KAAK,QAAQ;AAAA,EAC5C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,IAAI,KAAK,OAAO,OAAO;AACrB,QAAI,QAAQ,UAA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AAI,OAAO,aAAa,WAAW;AACjC,oBAAY,OAAO;AACnB,iBAAS;AAAA,MACX;AAAA,IACF;AAEA,QAAI,WAAW,MAAM;AACnB,WAAK,QAAQ,MAAM;AACnB,WAAK,KAAK,WAAW,EAAE,KAAK,OAAO,CAAC;AAAA,IACtC;AAAA,EACF;AACF;;;ADlNA,IAAO,cAAQ;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export interface MemoryCacheOptions {
|
|
2
|
+
ttlMs?: number;
|
|
3
|
+
cleanupIntervalMs?: number;
|
|
4
|
+
maxSize?: number;
|
|
5
|
+
}
|
|
6
|
+
export interface SetEvent { key: string; value: unknown; ttlMs: number; exists: boolean; }
|
|
7
|
+
export interface KeyEvent { key: string; }
|
|
8
|
+
export interface ClearEvent { count: number; }
|
|
9
|
+
export class MemoryCache {
|
|
10
|
+
constructor(options?: MemoryCacheOptions);
|
|
11
|
+
ttlMs: number;
|
|
12
|
+
maxSize: number;
|
|
13
|
+
readonly size: number;
|
|
14
|
+
set(key: string, value: unknown, ttlMs?: number): this;
|
|
15
|
+
get<T = unknown>(key: string): T | undefined;
|
|
16
|
+
has(key: string): boolean;
|
|
17
|
+
delete(key: string): boolean;
|
|
18
|
+
clear(): number;
|
|
19
|
+
cleanup(): number;
|
|
20
|
+
keys(): string[];
|
|
21
|
+
destroy(): void;
|
|
22
|
+
on(event: "set", listener: (e: SetEvent) => void): this;
|
|
23
|
+
on(event: "get" | "delete" | "expired" | "evicted", listener: (e: KeyEvent) => void): this;
|
|
24
|
+
on(event: "clear", listener: (e: ClearEvent) => void): this;
|
|
25
|
+
}
|
|
26
|
+
export default MemoryCache;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
// src/MemoryCache.js
|
|
2
|
+
import { EventEmitter } from "node:events";
|
|
3
|
+
import { performance } from "node:perf_hooks";
|
|
4
|
+
var DEFAULT_CLEANUP_INTERVAL_MS = 6e4;
|
|
5
|
+
var MemoryCache = class extends EventEmitter {
|
|
6
|
+
/**
|
|
7
|
+
* @param {object} [options]
|
|
8
|
+
* @param {number} [options.ttlMs=0] TTL por defecto en milisegundos (0 = no expira).
|
|
9
|
+
* @param {number} [options.cleanupIntervalMs=60000] Intervalo de limpieza periódica en ms (0 = desactivada).
|
|
10
|
+
* @param {number} [options.maxSize=0] Tamaño máximo de entradas (0 = ilimitado). Al llenarse evita la entrada menos recientemente usada.
|
|
11
|
+
*/
|
|
12
|
+
constructor({ ttlMs = 0, cleanupIntervalMs = DEFAULT_CLEANUP_INTERVAL_MS, maxSize = 0 } = {}) {
|
|
13
|
+
super();
|
|
14
|
+
this.ttlMs = ttlMs;
|
|
15
|
+
this.maxSize = maxSize;
|
|
16
|
+
this._store = /* @__PURE__ */ new Map();
|
|
17
|
+
this._timer = null;
|
|
18
|
+
if (cleanupIntervalMs > 0) {
|
|
19
|
+
this._timer = setInterval(() => this.cleanup(), cleanupIntervalMs);
|
|
20
|
+
if (typeof this._timer.unref === "function") {
|
|
21
|
+
this._timer.unref();
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Devuelve el TTL en milisegundos de una entrada, usando el override por
|
|
27
|
+
* entrada si se indicó, o el TTL por defecto de la caché.
|
|
28
|
+
* @private
|
|
29
|
+
*/
|
|
30
|
+
_resolveTtl(ttlMs) {
|
|
31
|
+
return ttlMs === void 0 ? this.ttlMs : ttlMs;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Registra o reemplaza una entrada.
|
|
35
|
+
* @param {string} key
|
|
36
|
+
* @param {unknown} value
|
|
37
|
+
* @param {number} [ttlMs] TTL específico en ms (anula el por defecto).
|
|
38
|
+
* @returns {this}
|
|
39
|
+
*/
|
|
40
|
+
set(key, value, ttlMs) {
|
|
41
|
+
if (key === void 0 || key === null) {
|
|
42
|
+
throw new TypeError("MemoryCache#set: la clave no puede ser null/undefined");
|
|
43
|
+
}
|
|
44
|
+
const resolvedTtl = this._resolveTtl(ttlMs);
|
|
45
|
+
const expiresAt = resolvedTtl > 0 ? Date.now() + resolvedTtl : Infinity;
|
|
46
|
+
const record = { value, expiresAt, lastAccess: performance.now() };
|
|
47
|
+
const exists = this._store.has(key);
|
|
48
|
+
this._store.set(key, record);
|
|
49
|
+
this._evictIfNeeded();
|
|
50
|
+
this.emit("set", { key, value, ttlMs: resolvedTtl, exists });
|
|
51
|
+
return this;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Lee una entrada. Si está expirada la elimina (perezoso) y emite 'expired'.
|
|
55
|
+
* @param {string} key
|
|
56
|
+
* @returns {unknown | undefined}
|
|
57
|
+
*/
|
|
58
|
+
get(key) {
|
|
59
|
+
const record = this._store.get(key);
|
|
60
|
+
if (!record) return void 0;
|
|
61
|
+
if (this._isExpired(record)) {
|
|
62
|
+
this._delete(key);
|
|
63
|
+
this.emit("expired", { key });
|
|
64
|
+
return void 0;
|
|
65
|
+
}
|
|
66
|
+
record.lastAccess = performance.now();
|
|
67
|
+
this.emit("get", { key });
|
|
68
|
+
return record.value;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Indica si la clave existe y no está expirada.
|
|
72
|
+
* @param {string} key
|
|
73
|
+
* @returns {boolean}
|
|
74
|
+
*/
|
|
75
|
+
has(key) {
|
|
76
|
+
const record = this._store.get(key);
|
|
77
|
+
if (!record) return false;
|
|
78
|
+
if (this._isExpired(record)) {
|
|
79
|
+
this._delete(key);
|
|
80
|
+
this.emit("expired", { key });
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
return true;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Elimina una entrada. Emite 'delete' solo si existía.
|
|
87
|
+
* @param {string} key
|
|
88
|
+
* @returns {boolean} true si existía y fue eliminada.
|
|
89
|
+
*/
|
|
90
|
+
delete(key) {
|
|
91
|
+
const existed = this._store.has(key);
|
|
92
|
+
if (existed) {
|
|
93
|
+
this._delete(key);
|
|
94
|
+
this.emit("delete", { key });
|
|
95
|
+
}
|
|
96
|
+
return existed;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Vacía la caché por completo. Emite 'clear' solo si había entradas.
|
|
100
|
+
* @returns {number} cantidad de entradas eliminadas.
|
|
101
|
+
*/
|
|
102
|
+
clear() {
|
|
103
|
+
const count = this._store.size;
|
|
104
|
+
if (count > 0) {
|
|
105
|
+
this._store.clear();
|
|
106
|
+
this.emit("clear", { count });
|
|
107
|
+
}
|
|
108
|
+
return count;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Elimina todas las entradas expiradas. Emite 'expired' por cada una.
|
|
112
|
+
* @returns {number} cantidad de entradas expiradas eliminadas.
|
|
113
|
+
*/
|
|
114
|
+
cleanup() {
|
|
115
|
+
const now = Date.now();
|
|
116
|
+
let removed = 0;
|
|
117
|
+
for (const [key, record] of this._store) {
|
|
118
|
+
if (record.expiresAt <= now) {
|
|
119
|
+
this._store.delete(key);
|
|
120
|
+
removed += 1;
|
|
121
|
+
this.emit("expired", { key });
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return removed;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Cantidad de entradas vivas (sin contar expiradas pendientes de purga).
|
|
128
|
+
* @returns {number}
|
|
129
|
+
*/
|
|
130
|
+
get size() {
|
|
131
|
+
return this._store.size;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Lista de claves de entradas vivas.
|
|
135
|
+
* @returns {string[]}
|
|
136
|
+
*/
|
|
137
|
+
keys() {
|
|
138
|
+
return Array.from(this._store.keys());
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Detiene la limpieza periódica y libera el temporizador.
|
|
142
|
+
*/
|
|
143
|
+
destroy() {
|
|
144
|
+
if (this._timer) {
|
|
145
|
+
clearInterval(this._timer);
|
|
146
|
+
this._timer = null;
|
|
147
|
+
}
|
|
148
|
+
this.removeAllListeners();
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* @private
|
|
152
|
+
*/
|
|
153
|
+
_delete(key) {
|
|
154
|
+
this._store.delete(key);
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* @private
|
|
158
|
+
*/
|
|
159
|
+
_isExpired(record) {
|
|
160
|
+
return record.expiresAt <= Date.now();
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Si hay maxSize y la caché lo supera, expulsa la entrada menos
|
|
164
|
+
* recientemente usada. Emite 'evicted'.
|
|
165
|
+
* @private
|
|
166
|
+
*/
|
|
167
|
+
_evictIfNeeded() {
|
|
168
|
+
if (this.maxSize <= 0 || this._store.size <= this.maxSize) return;
|
|
169
|
+
let lruKey = null;
|
|
170
|
+
let lruAccess = Infinity;
|
|
171
|
+
for (const [key, record] of this._store) {
|
|
172
|
+
if (record.lastAccess < lruAccess) {
|
|
173
|
+
lruAccess = record.lastAccess;
|
|
174
|
+
lruKey = key;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (lruKey !== null) {
|
|
178
|
+
this._delete(lruKey);
|
|
179
|
+
this.emit("evicted", { key: lruKey });
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
// src/index.js
|
|
185
|
+
var src_default = MemoryCache;
|
|
186
|
+
export {
|
|
187
|
+
MemoryCache,
|
|
188
|
+
src_default as default
|
|
189
|
+
};
|
|
190
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/MemoryCache.js", "../src/index.js"],
|
|
4
|
+
"sourcesContent": ["import { EventEmitter } from 'node:events';\nimport { performance } from 'node:perf_hooks';\n\nconst DEFAULT_CLEANUP_INTERVAL_MS = 60_000;\n\n/**\n * Cach\u00E9 en memoria para el lado del servidor.\n *\n * - TTL por entrada (0 = sin expiraci\u00F3n).\n * - Expiraci\u00F3n perezosa al leer (get/has) + limpieza peri\u00F3dica autom\u00E1tica.\n * - Emite eventos: 'set', 'get', 'delete', 'clear', 'expired', 'evicted'.\n *\n * @extends EventEmitter\n */\nexport class MemoryCache extends EventEmitter {\n /**\n * @param {object} [options]\n * @param {number} [options.ttlMs=0] TTL por defecto en milisegundos (0 = no expira).\n * @param {number} [options.cleanupIntervalMs=60000] Intervalo de limpieza peri\u00F3dica en ms (0 = desactivada).\n * @param {number} [options.maxSize=0] Tama\u00F1o m\u00E1ximo de entradas (0 = ilimitado). Al llenarse evita la entrada menos recientemente usada.\n */\n constructor({ ttlMs = 0, cleanupIntervalMs = DEFAULT_CLEANUP_INTERVAL_MS, maxSize = 0 } = {}) {\n super();\n this.ttlMs = ttlMs;\n this.maxSize = maxSize;\n /** @type {Map<string, { value: unknown, expiresAt: number, lastAccess: number }>} */\n this._store = new Map();\n this._timer = null;\n\n if (cleanupIntervalMs > 0) {\n this._timer = setInterval(() => this.cleanup(), cleanupIntervalMs);\n if (typeof this._timer.unref === 'function') {\n this._timer.unref();\n }\n }\n }\n\n /**\n * Devuelve el TTL en milisegundos de una entrada, usando el override por\n * entrada si se indic\u00F3, o el TTL por defecto de la cach\u00E9.\n * @private\n */\n _resolveTtl(ttlMs) {\n return ttlMs === undefined ? this.ttlMs : ttlMs;\n }\n\n /**\n * Registra o reemplaza una entrada.\n * @param {string} key\n * @param {unknown} value\n * @param {number} [ttlMs] TTL espec\u00EDfico en ms (anula el por defecto).\n * @returns {this}\n */\n set(key, value, ttlMs) {\n if (key === undefined || key === null) {\n throw new TypeError('MemoryCache#set: la clave no puede ser null/undefined');\n }\n const resolvedTtl = this._resolveTtl(ttlMs);\n const expiresAt = resolvedTtl > 0 ? Date.now() + resolvedTtl : Infinity;\n const record = { value, expiresAt, lastAccess: performance.now() };\n\n const exists = this._store.has(key);\n this._store.set(key, record);\n this._evictIfNeeded();\n this.emit('set', { key, value, ttlMs: resolvedTtl, exists });\n return this;\n }\n\n /**\n * Lee una entrada. Si est\u00E1 expirada la elimina (perezoso) y emite 'expired'.\n * @param {string} key\n * @returns {unknown | undefined}\n */\n get(key) {\n const record = this._store.get(key);\n if (!record) return undefined;\n\n if (this._isExpired(record)) {\n this._delete(key);\n this.emit('expired', { key });\n return undefined;\n }\n\n record.lastAccess = performance.now();\n this.emit('get', { key });\n return record.value;\n }\n\n /**\n * Indica si la clave existe y no est\u00E1 expirada.\n * @param {string} key\n * @returns {boolean}\n */\n has(key) {\n const record = this._store.get(key);\n if (!record) return false;\n\n if (this._isExpired(record)) {\n this._delete(key);\n this.emit('expired', { key });\n return false;\n }\n\n return true;\n }\n\n /**\n * Elimina una entrada. Emite 'delete' solo si exist\u00EDa.\n * @param {string} key\n * @returns {boolean} true si exist\u00EDa y fue eliminada.\n */\n delete(key) {\n const existed = this._store.has(key);\n if (existed) {\n this._delete(key);\n this.emit('delete', { key });\n }\n return existed;\n }\n\n /**\n * Vac\u00EDa la cach\u00E9 por completo. Emite 'clear' solo si hab\u00EDa entradas.\n * @returns {number} cantidad de entradas eliminadas.\n */\n clear() {\n const count = this._store.size;\n if (count > 0) {\n this._store.clear();\n this.emit('clear', { count });\n }\n return count;\n }\n\n /**\n * Elimina todas las entradas expiradas. Emite 'expired' por cada una.\n * @returns {number} cantidad de entradas expiradas eliminadas.\n */\n cleanup() {\n const now = Date.now();\n let removed = 0;\n for (const [key, record] of this._store) {\n if (record.expiresAt <= now) {\n this._store.delete(key);\n removed += 1;\n this.emit('expired', { key });\n }\n }\n return removed;\n }\n\n /**\n * Cantidad de entradas vivas (sin contar expiradas pendientes de purga).\n * @returns {number}\n */\n get size() {\n return this._store.size;\n }\n\n /**\n * Lista de claves de entradas vivas.\n * @returns {string[]}\n */\n keys() {\n return Array.from(this._store.keys());\n }\n\n /**\n * Detiene la limpieza peri\u00F3dica y libera el temporizador.\n */\n destroy() {\n if (this._timer) {\n clearInterval(this._timer);\n this._timer = null;\n }\n this.removeAllListeners();\n }\n\n /**\n * @private\n */\n _delete(key) {\n this._store.delete(key);\n }\n\n /**\n * @private\n */\n _isExpired(record) {\n return record.expiresAt <= Date.now();\n }\n\n /**\n * Si hay maxSize y la cach\u00E9 lo supera, expulsa la entrada menos\n * recientemente usada. Emite 'evicted'.\n * @private\n */\n _evictIfNeeded() {\n if (this.maxSize <= 0 || this._store.size <= this.maxSize) return;\n\n let lruKey = null;\n let lruAccess = Infinity;\n for (const [key, record] of this._store) {\n if (record.lastAccess < lruAccess) {\n lruAccess = record.lastAccess;\n lruKey = key;\n }\n }\n\n if (lruKey !== null) {\n this._delete(lruKey);\n this.emit('evicted', { key: lruKey });\n }\n }\n}\n\nexport default MemoryCache;\n", "import { MemoryCache } from './MemoryCache.js';\n\nexport { MemoryCache };\nexport default MemoryCache;\n"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,oBAAoB;AAC7B,SAAS,mBAAmB;AAE5B,IAAM,8BAA8B;AAW7B,IAAM,cAAN,cAA0B,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO5C,YAAY,EAAE,QAAQ,GAAG,oBAAoB,6BAA6B,UAAU,EAAE,IAAI,CAAC,GAAG;AAC5F,UAAM;AACN,SAAK,QAAQ;AACb,SAAK,UAAU;AAEf,SAAK,SAAS,oBAAI,IAAI;AACtB,SAAK,SAAS;AAEd,QAAI,oBAAoB,GAAG;AACzB,WAAK,SAAS,YAAY,MAAM,KAAK,QAAQ,GAAG,iBAAiB;AACjE,UAAI,OAAO,KAAK,OAAO,UAAU,YAAY;AAC3C,aAAK,OAAO,MAAM;AAAA,MACpB;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,YAAY,OAAO;AACjB,WAAO,UAAU,SAAY,KAAK,QAAQ;AAAA,EAC5C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,IAAI,KAAK,OAAO,O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AAK,KAAK,QAAQ;AACvC,UAAI,OAAO,aAAa,WAAW;AACjC,oBAAY,OAAO;AACnB,iBAAS;AAAA,MACX;AAAA,IACF;AAEA,QAAI,WAAW,MAAM;AACnB,WAAK,QAAQ,MAAM;AACnB,WAAK,KAAK,WAAW,EAAE,KAAK,OAAO,CAAC;AAAA,IACtC;AAAA,EACF;AACF;;;AClNA,IAAO,cAAQ;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@greenborn/greenborn-memory-cache",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "Caché en memoria del lado del servidor para Node.js: TTL por entrada, eventos y limpieza periódica automática. Sin dependencias de runtime (usa node:events).",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"files": [
|
|
7
|
+
"dist",
|
|
8
|
+
"src"
|
|
9
|
+
],
|
|
10
|
+
"main": "./dist/index.cjs",
|
|
11
|
+
"module": "./dist/index.js",
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"import": {
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"default": "./dist/index.js"
|
|
18
|
+
},
|
|
19
|
+
"require": {
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"default": "./dist/index.cjs"
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"scripts": {
|
|
26
|
+
"build": "node build.mjs",
|
|
27
|
+
"test": "node --test",
|
|
28
|
+
"prepublishOnly": "npm run build",
|
|
29
|
+
"prepack": "npm run build"
|
|
30
|
+
},
|
|
31
|
+
"keywords": [
|
|
32
|
+
"cache",
|
|
33
|
+
"memory",
|
|
34
|
+
"memory-cache",
|
|
35
|
+
"ttl",
|
|
36
|
+
"server",
|
|
37
|
+
"nodejs",
|
|
38
|
+
"caching",
|
|
39
|
+
"lru"
|
|
40
|
+
],
|
|
41
|
+
"license": "MIT",
|
|
42
|
+
"author": {
|
|
43
|
+
"name": "2012lucho",
|
|
44
|
+
"email": "lucho.2012.tandil@gmail.com"
|
|
45
|
+
},
|
|
46
|
+
"homepage": "https://github.com/Greenborn/opencode_dev/tree/main/greenborn-memory-cache",
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
},
|
|
50
|
+
"repository": {
|
|
51
|
+
"type": "git",
|
|
52
|
+
"url": "git+https://github.com/Greenborn/opencode_dev.git"
|
|
53
|
+
},
|
|
54
|
+
"engines": {
|
|
55
|
+
"node": ">=18"
|
|
56
|
+
},
|
|
57
|
+
"devDependencies": {
|
|
58
|
+
"esbuild": "^0.21.0"
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
import { performance } from 'node:perf_hooks';
|
|
3
|
+
|
|
4
|
+
const DEFAULT_CLEANUP_INTERVAL_MS = 60_000;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Caché en memoria para el lado del servidor.
|
|
8
|
+
*
|
|
9
|
+
* - TTL por entrada (0 = sin expiración).
|
|
10
|
+
* - Expiración perezosa al leer (get/has) + limpieza periódica automática.
|
|
11
|
+
* - Emite eventos: 'set', 'get', 'delete', 'clear', 'expired', 'evicted'.
|
|
12
|
+
*
|
|
13
|
+
* @extends EventEmitter
|
|
14
|
+
*/
|
|
15
|
+
export class MemoryCache extends EventEmitter {
|
|
16
|
+
/**
|
|
17
|
+
* @param {object} [options]
|
|
18
|
+
* @param {number} [options.ttlMs=0] TTL por defecto en milisegundos (0 = no expira).
|
|
19
|
+
* @param {number} [options.cleanupIntervalMs=60000] Intervalo de limpieza periódica en ms (0 = desactivada).
|
|
20
|
+
* @param {number} [options.maxSize=0] Tamaño máximo de entradas (0 = ilimitado). Al llenarse evita la entrada menos recientemente usada.
|
|
21
|
+
*/
|
|
22
|
+
constructor({ ttlMs = 0, cleanupIntervalMs = DEFAULT_CLEANUP_INTERVAL_MS, maxSize = 0 } = {}) {
|
|
23
|
+
super();
|
|
24
|
+
this.ttlMs = ttlMs;
|
|
25
|
+
this.maxSize = maxSize;
|
|
26
|
+
/** @type {Map<string, { value: unknown, expiresAt: number, lastAccess: number }>} */
|
|
27
|
+
this._store = new Map();
|
|
28
|
+
this._timer = null;
|
|
29
|
+
|
|
30
|
+
if (cleanupIntervalMs > 0) {
|
|
31
|
+
this._timer = setInterval(() => this.cleanup(), cleanupIntervalMs);
|
|
32
|
+
if (typeof this._timer.unref === 'function') {
|
|
33
|
+
this._timer.unref();
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Devuelve el TTL en milisegundos de una entrada, usando el override por
|
|
40
|
+
* entrada si se indicó, o el TTL por defecto de la caché.
|
|
41
|
+
* @private
|
|
42
|
+
*/
|
|
43
|
+
_resolveTtl(ttlMs) {
|
|
44
|
+
return ttlMs === undefined ? this.ttlMs : ttlMs;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Registra o reemplaza una entrada.
|
|
49
|
+
* @param {string} key
|
|
50
|
+
* @param {unknown} value
|
|
51
|
+
* @param {number} [ttlMs] TTL específico en ms (anula el por defecto).
|
|
52
|
+
* @returns {this}
|
|
53
|
+
*/
|
|
54
|
+
set(key, value, ttlMs) {
|
|
55
|
+
if (key === undefined || key === null) {
|
|
56
|
+
throw new TypeError('MemoryCache#set: la clave no puede ser null/undefined');
|
|
57
|
+
}
|
|
58
|
+
const resolvedTtl = this._resolveTtl(ttlMs);
|
|
59
|
+
const expiresAt = resolvedTtl > 0 ? Date.now() + resolvedTtl : Infinity;
|
|
60
|
+
const record = { value, expiresAt, lastAccess: performance.now() };
|
|
61
|
+
|
|
62
|
+
const exists = this._store.has(key);
|
|
63
|
+
this._store.set(key, record);
|
|
64
|
+
this._evictIfNeeded();
|
|
65
|
+
this.emit('set', { key, value, ttlMs: resolvedTtl, exists });
|
|
66
|
+
return this;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Lee una entrada. Si está expirada la elimina (perezoso) y emite 'expired'.
|
|
71
|
+
* @param {string} key
|
|
72
|
+
* @returns {unknown | undefined}
|
|
73
|
+
*/
|
|
74
|
+
get(key) {
|
|
75
|
+
const record = this._store.get(key);
|
|
76
|
+
if (!record) return undefined;
|
|
77
|
+
|
|
78
|
+
if (this._isExpired(record)) {
|
|
79
|
+
this._delete(key);
|
|
80
|
+
this.emit('expired', { key });
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
record.lastAccess = performance.now();
|
|
85
|
+
this.emit('get', { key });
|
|
86
|
+
return record.value;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Indica si la clave existe y no está expirada.
|
|
91
|
+
* @param {string} key
|
|
92
|
+
* @returns {boolean}
|
|
93
|
+
*/
|
|
94
|
+
has(key) {
|
|
95
|
+
const record = this._store.get(key);
|
|
96
|
+
if (!record) return false;
|
|
97
|
+
|
|
98
|
+
if (this._isExpired(record)) {
|
|
99
|
+
this._delete(key);
|
|
100
|
+
this.emit('expired', { key });
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return true;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Elimina una entrada. Emite 'delete' solo si existía.
|
|
109
|
+
* @param {string} key
|
|
110
|
+
* @returns {boolean} true si existía y fue eliminada.
|
|
111
|
+
*/
|
|
112
|
+
delete(key) {
|
|
113
|
+
const existed = this._store.has(key);
|
|
114
|
+
if (existed) {
|
|
115
|
+
this._delete(key);
|
|
116
|
+
this.emit('delete', { key });
|
|
117
|
+
}
|
|
118
|
+
return existed;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Vacía la caché por completo. Emite 'clear' solo si había entradas.
|
|
123
|
+
* @returns {number} cantidad de entradas eliminadas.
|
|
124
|
+
*/
|
|
125
|
+
clear() {
|
|
126
|
+
const count = this._store.size;
|
|
127
|
+
if (count > 0) {
|
|
128
|
+
this._store.clear();
|
|
129
|
+
this.emit('clear', { count });
|
|
130
|
+
}
|
|
131
|
+
return count;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Elimina todas las entradas expiradas. Emite 'expired' por cada una.
|
|
136
|
+
* @returns {number} cantidad de entradas expiradas eliminadas.
|
|
137
|
+
*/
|
|
138
|
+
cleanup() {
|
|
139
|
+
const now = Date.now();
|
|
140
|
+
let removed = 0;
|
|
141
|
+
for (const [key, record] of this._store) {
|
|
142
|
+
if (record.expiresAt <= now) {
|
|
143
|
+
this._store.delete(key);
|
|
144
|
+
removed += 1;
|
|
145
|
+
this.emit('expired', { key });
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return removed;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Cantidad de entradas vivas (sin contar expiradas pendientes de purga).
|
|
153
|
+
* @returns {number}
|
|
154
|
+
*/
|
|
155
|
+
get size() {
|
|
156
|
+
return this._store.size;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Lista de claves de entradas vivas.
|
|
161
|
+
* @returns {string[]}
|
|
162
|
+
*/
|
|
163
|
+
keys() {
|
|
164
|
+
return Array.from(this._store.keys());
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Detiene la limpieza periódica y libera el temporizador.
|
|
169
|
+
*/
|
|
170
|
+
destroy() {
|
|
171
|
+
if (this._timer) {
|
|
172
|
+
clearInterval(this._timer);
|
|
173
|
+
this._timer = null;
|
|
174
|
+
}
|
|
175
|
+
this.removeAllListeners();
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* @private
|
|
180
|
+
*/
|
|
181
|
+
_delete(key) {
|
|
182
|
+
this._store.delete(key);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* @private
|
|
187
|
+
*/
|
|
188
|
+
_isExpired(record) {
|
|
189
|
+
return record.expiresAt <= Date.now();
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Si hay maxSize y la caché lo supera, expulsa la entrada menos
|
|
194
|
+
* recientemente usada. Emite 'evicted'.
|
|
195
|
+
* @private
|
|
196
|
+
*/
|
|
197
|
+
_evictIfNeeded() {
|
|
198
|
+
if (this.maxSize <= 0 || this._store.size <= this.maxSize) return;
|
|
199
|
+
|
|
200
|
+
let lruKey = null;
|
|
201
|
+
let lruAccess = Infinity;
|
|
202
|
+
for (const [key, record] of this._store) {
|
|
203
|
+
if (record.lastAccess < lruAccess) {
|
|
204
|
+
lruAccess = record.lastAccess;
|
|
205
|
+
lruKey = key;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
if (lruKey !== null) {
|
|
210
|
+
this._delete(lruKey);
|
|
211
|
+
this.emit('evicted', { key: lruKey });
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export default MemoryCache;
|
package/src/index.js
ADDED