rust-node-cache 0.1.1 → 0.2.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/dist/index.d.mts CHANGED
@@ -1,49 +1,63 @@
1
1
  /**
2
- * rust-node-cache — API pública (TypeScript).
2
+ * rust-node-cache — public API (TypeScript).
3
3
  *
4
4
  * "Ultra-fast in-memory cache powered by Rust."
5
5
  *
6
- * Esta camada é um wrapper fino e tipado sobre a classe `Cache` nativa gerada
7
- * pelo Rust/napi-rs. Por que envolver em vez de re-exportar direto?
8
- * - permite **genéricos** ergonômicos: `cache.get<User>("user:1")`;
9
- * - normaliza `undefined`/`null` para sempre devolver `null` num miss;
10
- * - dá um único lugar para JSDoc e para evoluir a API sem quebrar o core Rust.
6
+ * This layer is a thin, typed wrapper over the native `Cache` class generated
7
+ * by Rust/napi-rs. Why wrap it instead of re-exporting it directly?
8
+ * - it allows ergonomic **generics**: `cache.get<User>("user:1")`;
9
+ * - it normalizes `undefined`/`null` so a miss always returns `null`;
10
+ * - it gives one place for the JSDoc and for evolving the API without breaking the Rust core.
11
11
  *
12
- * O custo é uma chamada de função extra por operação — desprezível frente ao
13
- * trabalho real (serialização + acesso ao DashMap) que acontece no Rust.
12
+ * The cost is one extra function call per operation — negligible next to the
13
+ * real work (serialization + DashMap access) done in Rust.
14
14
  */
15
- /** Opções do construtor do cache. */
15
+ /** Eviction strategy when `maxSize` is reached. */
16
+ type EvictionPolicy = "reject" | "lru";
17
+ /** Cache constructor options. */
16
18
  interface CacheOptions {
17
19
  /**
18
- * Limite máximo de chaves. Ao ser atingido, `set` de uma chave **nova**
19
- * retorna `false` (sobrescrever chave existente continua permitido).
20
- * Sem valor => cache ilimitado.
20
+ * Maximum number of keys. What happens when it is reached depends on
21
+ * `evictionPolicy`. No value => unlimited cache.
21
22
  */
22
23
  maxSize?: number;
24
+ /**
25
+ * Policy when `maxSize` is reached on a **new** key:
26
+ * - `"reject"` (default): `set` returns `false` (overwriting still works);
27
+ * - `"lru"`: removes the least recently used entry and goes on.
28
+ */
29
+ evictionPolicy?: EvictionPolicy;
30
+ /**
31
+ * When set (> 0), starts a thread that sweeps expired entries every N
32
+ * seconds (background expiration, on top of the lazy one on access).
33
+ */
34
+ cleanupIntervalSeconds?: number;
23
35
  }
24
- /** Opções por operação de escrita. */
36
+ /** Per-write options. */
25
37
  interface SetOptions {
26
- /** Tempo de vida em segundos. Ausente => a entrada não expira por tempo. */
38
+ /** Time to live in seconds. Absent => the entry does not expire by time. */
27
39
  ttlSeconds?: number;
28
40
  }
29
- /** Estatísticas acumuladas do cache (mais o tamanho atual). */
41
+ /** Accumulated cache statistics (plus the current size). */
30
42
  interface CacheStats {
31
- /** Leituras que encontraram uma entrada válida. */
43
+ /** Reads that found a valid entry. */
32
44
  hits: number;
33
- /** Leituras sem chave válida (ausente ou expirada). */
45
+ /** Reads without a valid key (missing or expired). */
34
46
  misses: number;
35
- /** Total de escritas (`set`). */
47
+ /** Total writes (`set`). */
36
48
  sets: number;
37
- /** Total de remoções explícitas (`delete`). */
49
+ /** Total explicit removals (`delete`). */
38
50
  deletes: number;
39
- /** Total de entradas removidas por expiração. */
51
+ /** Total entries removed by expiration. */
40
52
  expired: number;
41
- /** Número de chaves armazenadas agora. */
53
+ /** Total entries removed by eviction (LRU policy when `maxSize` is reached). */
54
+ evicted: number;
55
+ /** Number of keys stored right now. */
42
56
  size: number;
43
57
  }
44
58
  /**
45
- * Cache em memória ultrarrápido com núcleo em Rust (DashMap + contadores
46
- * atômicos). Thread-safe e com suporte a TTL por entrada.
59
+ * In-memory cache with a Rust core (DashMap + atomic counters). Thread-safe,
60
+ * with an optional TTL per entry.
47
61
  *
48
62
  * @example
49
63
  * ```ts
@@ -55,37 +69,39 @@ interface CacheStats {
55
69
  * ```
56
70
  */
57
71
  declare class Cache {
58
- /** Instância da classe nativa (Rust). */
72
+ /** Instance of the native (Rust) class. */
59
73
  private readonly native;
60
74
  constructor(options?: CacheOptions);
75
+ /** The active eviction policy: `"reject"` or `"lru"`. */
76
+ get evictionPolicy(): EvictionPolicy;
61
77
  /**
62
- * Armazena (ou sobrescreve) um valor. O valor é serializado como JSON no core.
78
+ * Stores (or overwrites) a value. The value is serialized as JSON in the core.
63
79
  *
64
- * @returns `true` em sucesso; `false` se `maxSize` foi atingido e a chave é nova.
80
+ * @returns `true` on success; `false` if `maxSize` was reached and the key is new.
65
81
  */
66
82
  set<T>(key: string, value: T, options?: SetOptions): boolean;
67
83
  /**
68
- * Lê um valor. Aplica expiração preguiçosa: chaves vencidas contam como miss.
84
+ * Reads a value. Applies lazy expiration: expired keys count as a miss.
69
85
  *
70
- * @returns o valor desserializado, ou `null` se ausente/expirado.
86
+ * @returns the deserialized value, or `null` if missing or expired.
71
87
  */
72
88
  get<T = unknown>(key: string): T | null;
73
- /** Remove uma chave. Retorna `true` se ela existia. */
89
+ /** Removes a key. Returns `true` if it existed. */
74
90
  delete(key: string): boolean;
75
- /** Indica se a chave existe e está válida (não expirada). */
91
+ /** Whether the key exists and is still valid (not expired). */
76
92
  exists(key: string): boolean;
77
- /** Esvazia o cache (não zera os contadores históricos de `stats`). */
93
+ /** Empties the cache (does not reset the historical `stats` counters). */
78
94
  clear(): void;
79
- /** Número de chaves armazenadas no momento. */
95
+ /** Number of keys currently stored. */
80
96
  size(): number;
81
97
  /**
82
- * Varre e remove todas as entradas expiradas de uma só vez.
98
+ * Sweeps and removes every expired entry at once.
83
99
  *
84
- * @returns quantas entradas foram removidas.
100
+ * @returns how many entries were removed.
85
101
  */
86
102
  cleanupExpired(): number;
87
- /** Retorna as estatísticas acumuladas + o tamanho atual. */
103
+ /** Returns the accumulated statistics + the current size. */
88
104
  stats(): CacheStats;
89
105
  }
90
106
 
91
- export { Cache, type CacheOptions, type CacheStats, type SetOptions };
107
+ export { Cache, type CacheOptions, type CacheStats, type EvictionPolicy, type SetOptions };
package/dist/index.d.ts CHANGED
@@ -1,49 +1,63 @@
1
1
  /**
2
- * rust-node-cache — API pública (TypeScript).
2
+ * rust-node-cache — public API (TypeScript).
3
3
  *
4
4
  * "Ultra-fast in-memory cache powered by Rust."
5
5
  *
6
- * Esta camada é um wrapper fino e tipado sobre a classe `Cache` nativa gerada
7
- * pelo Rust/napi-rs. Por que envolver em vez de re-exportar direto?
8
- * - permite **genéricos** ergonômicos: `cache.get<User>("user:1")`;
9
- * - normaliza `undefined`/`null` para sempre devolver `null` num miss;
10
- * - dá um único lugar para JSDoc e para evoluir a API sem quebrar o core Rust.
6
+ * This layer is a thin, typed wrapper over the native `Cache` class generated
7
+ * by Rust/napi-rs. Why wrap it instead of re-exporting it directly?
8
+ * - it allows ergonomic **generics**: `cache.get<User>("user:1")`;
9
+ * - it normalizes `undefined`/`null` so a miss always returns `null`;
10
+ * - it gives one place for the JSDoc and for evolving the API without breaking the Rust core.
11
11
  *
12
- * O custo é uma chamada de função extra por operação — desprezível frente ao
13
- * trabalho real (serialização + acesso ao DashMap) que acontece no Rust.
12
+ * The cost is one extra function call per operation — negligible next to the
13
+ * real work (serialization + DashMap access) done in Rust.
14
14
  */
15
- /** Opções do construtor do cache. */
15
+ /** Eviction strategy when `maxSize` is reached. */
16
+ type EvictionPolicy = "reject" | "lru";
17
+ /** Cache constructor options. */
16
18
  interface CacheOptions {
17
19
  /**
18
- * Limite máximo de chaves. Ao ser atingido, `set` de uma chave **nova**
19
- * retorna `false` (sobrescrever chave existente continua permitido).
20
- * Sem valor => cache ilimitado.
20
+ * Maximum number of keys. What happens when it is reached depends on
21
+ * `evictionPolicy`. No value => unlimited cache.
21
22
  */
22
23
  maxSize?: number;
24
+ /**
25
+ * Policy when `maxSize` is reached on a **new** key:
26
+ * - `"reject"` (default): `set` returns `false` (overwriting still works);
27
+ * - `"lru"`: removes the least recently used entry and goes on.
28
+ */
29
+ evictionPolicy?: EvictionPolicy;
30
+ /**
31
+ * When set (> 0), starts a thread that sweeps expired entries every N
32
+ * seconds (background expiration, on top of the lazy one on access).
33
+ */
34
+ cleanupIntervalSeconds?: number;
23
35
  }
24
- /** Opções por operação de escrita. */
36
+ /** Per-write options. */
25
37
  interface SetOptions {
26
- /** Tempo de vida em segundos. Ausente => a entrada não expira por tempo. */
38
+ /** Time to live in seconds. Absent => the entry does not expire by time. */
27
39
  ttlSeconds?: number;
28
40
  }
29
- /** Estatísticas acumuladas do cache (mais o tamanho atual). */
41
+ /** Accumulated cache statistics (plus the current size). */
30
42
  interface CacheStats {
31
- /** Leituras que encontraram uma entrada válida. */
43
+ /** Reads that found a valid entry. */
32
44
  hits: number;
33
- /** Leituras sem chave válida (ausente ou expirada). */
45
+ /** Reads without a valid key (missing or expired). */
34
46
  misses: number;
35
- /** Total de escritas (`set`). */
47
+ /** Total writes (`set`). */
36
48
  sets: number;
37
- /** Total de remoções explícitas (`delete`). */
49
+ /** Total explicit removals (`delete`). */
38
50
  deletes: number;
39
- /** Total de entradas removidas por expiração. */
51
+ /** Total entries removed by expiration. */
40
52
  expired: number;
41
- /** Número de chaves armazenadas agora. */
53
+ /** Total entries removed by eviction (LRU policy when `maxSize` is reached). */
54
+ evicted: number;
55
+ /** Number of keys stored right now. */
42
56
  size: number;
43
57
  }
44
58
  /**
45
- * Cache em memória ultrarrápido com núcleo em Rust (DashMap + contadores
46
- * atômicos). Thread-safe e com suporte a TTL por entrada.
59
+ * In-memory cache with a Rust core (DashMap + atomic counters). Thread-safe,
60
+ * with an optional TTL per entry.
47
61
  *
48
62
  * @example
49
63
  * ```ts
@@ -55,37 +69,39 @@ interface CacheStats {
55
69
  * ```
56
70
  */
57
71
  declare class Cache {
58
- /** Instância da classe nativa (Rust). */
72
+ /** Instance of the native (Rust) class. */
59
73
  private readonly native;
60
74
  constructor(options?: CacheOptions);
75
+ /** The active eviction policy: `"reject"` or `"lru"`. */
76
+ get evictionPolicy(): EvictionPolicy;
61
77
  /**
62
- * Armazena (ou sobrescreve) um valor. O valor é serializado como JSON no core.
78
+ * Stores (or overwrites) a value. The value is serialized as JSON in the core.
63
79
  *
64
- * @returns `true` em sucesso; `false` se `maxSize` foi atingido e a chave é nova.
80
+ * @returns `true` on success; `false` if `maxSize` was reached and the key is new.
65
81
  */
66
82
  set<T>(key: string, value: T, options?: SetOptions): boolean;
67
83
  /**
68
- * Lê um valor. Aplica expiração preguiçosa: chaves vencidas contam como miss.
84
+ * Reads a value. Applies lazy expiration: expired keys count as a miss.
69
85
  *
70
- * @returns o valor desserializado, ou `null` se ausente/expirado.
86
+ * @returns the deserialized value, or `null` if missing or expired.
71
87
  */
72
88
  get<T = unknown>(key: string): T | null;
73
- /** Remove uma chave. Retorna `true` se ela existia. */
89
+ /** Removes a key. Returns `true` if it existed. */
74
90
  delete(key: string): boolean;
75
- /** Indica se a chave existe e está válida (não expirada). */
91
+ /** Whether the key exists and is still valid (not expired). */
76
92
  exists(key: string): boolean;
77
- /** Esvazia o cache (não zera os contadores históricos de `stats`). */
93
+ /** Empties the cache (does not reset the historical `stats` counters). */
78
94
  clear(): void;
79
- /** Número de chaves armazenadas no momento. */
95
+ /** Number of keys currently stored. */
80
96
  size(): number;
81
97
  /**
82
- * Varre e remove todas as entradas expiradas de uma só vez.
98
+ * Sweeps and removes every expired entry at once.
83
99
  *
84
- * @returns quantas entradas foram removidas.
100
+ * @returns how many entries were removed.
85
101
  */
86
102
  cleanupExpired(): number;
87
- /** Retorna as estatísticas acumuladas + o tamanho atual. */
103
+ /** Returns the accumulated statistics + the current size. */
88
104
  stats(): CacheStats;
89
105
  }
90
106
 
91
- export { Cache, type CacheOptions, type CacheStats, type SetOptions };
107
+ export { Cache, type CacheOptions, type CacheStats, type EvictionPolicy, type SetOptions };
package/dist/index.js CHANGED
@@ -36,50 +36,59 @@ module.exports = __toCommonJS(index_exports);
36
36
  var native = __toESM(require("../binding.js"));
37
37
  var Cache2 = class {
38
38
  constructor(options = {}) {
39
- this.native = options.maxSize !== void 0 ? new native.Cache({ maxSize: options.maxSize }) : new native.Cache();
39
+ const hasOptions = options.maxSize !== void 0 || options.evictionPolicy !== void 0 || options.cleanupIntervalSeconds !== void 0;
40
+ this.native = hasOptions ? new native.Cache({
41
+ maxSize: options.maxSize,
42
+ evictionPolicy: options.evictionPolicy,
43
+ cleanupIntervalSeconds: options.cleanupIntervalSeconds
44
+ }) : new native.Cache();
45
+ }
46
+ /** The active eviction policy: `"reject"` or `"lru"`. */
47
+ get evictionPolicy() {
48
+ return this.native.evictionPolicy;
40
49
  }
41
50
  /**
42
- * Armazena (ou sobrescreve) um valor. O valor é serializado como JSON no core.
51
+ * Stores (or overwrites) a value. The value is serialized as JSON in the core.
43
52
  *
44
- * @returns `true` em sucesso; `false` se `maxSize` foi atingido e a chave é nova.
53
+ * @returns `true` on success; `false` if `maxSize` was reached and the key is new.
45
54
  */
46
55
  set(key, value, options) {
47
56
  return this.native.set(key, value, options);
48
57
  }
49
58
  /**
50
- * Lê um valor. Aplica expiração preguiçosa: chaves vencidas contam como miss.
59
+ * Reads a value. Applies lazy expiration: expired keys count as a miss.
51
60
  *
52
- * @returns o valor desserializado, ou `null` se ausente/expirado.
61
+ * @returns the deserialized value, or `null` if missing or expired.
53
62
  */
54
63
  get(key) {
55
64
  const value = this.native.get(key);
56
65
  return value === null || value === void 0 ? null : value;
57
66
  }
58
- /** Remove uma chave. Retorna `true` se ela existia. */
67
+ /** Removes a key. Returns `true` if it existed. */
59
68
  delete(key) {
60
69
  return this.native.delete(key);
61
70
  }
62
- /** Indica se a chave existe e está válida (não expirada). */
71
+ /** Whether the key exists and is still valid (not expired). */
63
72
  exists(key) {
64
73
  return this.native.exists(key);
65
74
  }
66
- /** Esvazia o cache (não zera os contadores históricos de `stats`). */
75
+ /** Empties the cache (does not reset the historical `stats` counters). */
67
76
  clear() {
68
77
  this.native.clear();
69
78
  }
70
- /** Número de chaves armazenadas no momento. */
79
+ /** Number of keys currently stored. */
71
80
  size() {
72
81
  return this.native.size();
73
82
  }
74
83
  /**
75
- * Varre e remove todas as entradas expiradas de uma só vez.
84
+ * Sweeps and removes every expired entry at once.
76
85
  *
77
- * @returns quantas entradas foram removidas.
86
+ * @returns how many entries were removed.
78
87
  */
79
88
  cleanupExpired() {
80
89
  return this.native.cleanupExpired();
81
90
  }
82
- /** Retorna as estatísticas acumuladas + o tamanho atual. */
91
+ /** Returns the accumulated statistics + the current size. */
83
92
  stats() {
84
93
  return this.native.stats();
85
94
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../js/index.ts"],"sourcesContent":["/**\n * rust-node-cache — API pública (TypeScript).\n *\n * \"Ultra-fast in-memory cache powered by Rust.\"\n *\n * Esta camada é um wrapper fino e tipado sobre a classe `Cache` nativa gerada\n * pelo Rust/napi-rs. Por que envolver em vez de re-exportar direto?\n * - permite **genéricos** ergonômicos: `cache.get<User>(\"user:1\")`;\n * - normaliza `undefined`/`null` para sempre devolver `null` num miss;\n * - dá um único lugar para JSDoc e para evoluir a API sem quebrar o core Rust.\n *\n * O custo é uma chamada de função extra por operação — desprezível frente ao\n * trabalho real (serialização + acesso ao DashMap) que acontece no Rust.\n */\n\n// Namespace import: funciona igual em CommonJS e ESM ao consumir o addon nativo\n// (que é um módulo CJS gerado pelo napi-rs).\nimport * as native from \"../binding.js\";\n\n/** Opções do construtor do cache. */\nexport interface CacheOptions {\n /**\n * Limite máximo de chaves. Ao ser atingido, `set` de uma chave **nova**\n * retorna `false` (sobrescrever chave existente continua permitido).\n * Sem valor => cache ilimitado.\n */\n maxSize?: number;\n}\n\n/** Opções por operação de escrita. */\nexport interface SetOptions {\n /** Tempo de vida em segundos. Ausente => a entrada não expira por tempo. */\n ttlSeconds?: number;\n}\n\n/** Estatísticas acumuladas do cache (mais o tamanho atual). */\nexport interface CacheStats {\n /** Leituras que encontraram uma entrada válida. */\n hits: number;\n /** Leituras sem chave válida (ausente ou expirada). */\n misses: number;\n /** Total de escritas (`set`). */\n sets: number;\n /** Total de remoções explícitas (`delete`). */\n deletes: number;\n /** Total de entradas removidas por expiração. */\n expired: number;\n /** Número de chaves armazenadas agora. */\n size: number;\n}\n\n/**\n * Cache em memória ultrarrápido com núcleo em Rust (DashMap + contadores\n * atômicos). Thread-safe e com suporte a TTL por entrada.\n *\n * @example\n * ```ts\n * import { Cache } from \"rust-node-cache\";\n *\n * const cache = new Cache();\n * cache.set(\"user:1\", { id: 1, name: \"Roberto\" });\n * cache.get<{ id: number; name: string }>(\"user:1\"); // { id: 1, name: \"Roberto\" }\n * ```\n */\nexport class Cache {\n /** Instância da classe nativa (Rust). */\n private readonly native: native.Cache;\n\n constructor(options: CacheOptions = {}) {\n // Só repassamos o objeto de opções ao Rust quando há algo relevante.\n this.native =\n options.maxSize !== undefined\n ? new native.Cache({ maxSize: options.maxSize })\n : new native.Cache();\n }\n\n /**\n * Armazena (ou sobrescreve) um valor. O valor é serializado como JSON no core.\n *\n * @returns `true` em sucesso; `false` se `maxSize` foi atingido e a chave é nova.\n */\n set<T>(key: string, value: T, options?: SetOptions): boolean {\n return this.native.set(key, value as unknown as object, options);\n }\n\n /**\n * Lê um valor. Aplica expiração preguiçosa: chaves vencidas contam como miss.\n *\n * @returns o valor desserializado, ou `null` se ausente/expirado.\n */\n get<T = unknown>(key: string): T | null {\n const value = this.native.get(key);\n return value === null || value === undefined ? null : (value as T);\n }\n\n /** Remove uma chave. Retorna `true` se ela existia. */\n delete(key: string): boolean {\n return this.native.delete(key);\n }\n\n /** Indica se a chave existe e está válida (não expirada). */\n exists(key: string): boolean {\n return this.native.exists(key);\n }\n\n /** Esvazia o cache (não zera os contadores históricos de `stats`). */\n clear(): void {\n this.native.clear();\n }\n\n /** Número de chaves armazenadas no momento. */\n size(): number {\n return this.native.size();\n }\n\n /**\n * Varre e remove todas as entradas expiradas de uma só vez.\n *\n * @returns quantas entradas foram removidas.\n */\n cleanupExpired(): number {\n return this.native.cleanupExpired();\n }\n\n /** Retorna as estatísticas acumuladas + o tamanho atual. */\n stats(): CacheStats {\n return this.native.stats();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA,eAAAA;AAAA;AAAA;AAiBA,aAAwB;AA+CjB,IAAMA,SAAN,MAAY;AAAA,EAIjB,YAAY,UAAwB,CAAC,GAAG;AAEtC,SAAK,SACH,QAAQ,YAAY,SAChB,IAAW,aAAM,EAAE,SAAS,QAAQ,QAAQ,CAAC,IAC7C,IAAW,aAAM;AAAA,EACzB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAO,KAAa,OAAU,SAA+B;AAC3D,WAAO,KAAK,OAAO,IAAI,KAAK,OAA4B,OAAO;AAAA,EACjE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAiB,KAAuB;AACtC,UAAM,QAAQ,KAAK,OAAO,IAAI,GAAG;AACjC,WAAO,UAAU,QAAQ,UAAU,SAAY,OAAQ;AAAA,EACzD;AAAA;AAAA,EAGA,OAAO,KAAsB;AAC3B,WAAO,KAAK,OAAO,OAAO,GAAG;AAAA,EAC/B;AAAA;AAAA,EAGA,OAAO,KAAsB;AAC3B,WAAO,KAAK,OAAO,OAAO,GAAG;AAAA,EAC/B;AAAA;AAAA,EAGA,QAAc;AACZ,SAAK,OAAO,MAAM;AAAA,EACpB;AAAA;AAAA,EAGA,OAAe;AACb,WAAO,KAAK,OAAO,KAAK;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,iBAAyB;AACvB,WAAO,KAAK,OAAO,eAAe;AAAA,EACpC;AAAA;AAAA,EAGA,QAAoB;AAClB,WAAO,KAAK,OAAO,MAAM;AAAA,EAC3B;AACF;","names":["Cache"]}
1
+ {"version":3,"sources":["../js/index.ts"],"sourcesContent":["/**\n * rust-node-cache — public API (TypeScript).\n *\n * \"Ultra-fast in-memory cache powered by Rust.\"\n *\n * This layer is a thin, typed wrapper over the native `Cache` class generated\n * by Rust/napi-rs. Why wrap it instead of re-exporting it directly?\n * - it allows ergonomic **generics**: `cache.get<User>(\"user:1\")`;\n * - it normalizes `undefined`/`null` so a miss always returns `null`;\n * - it gives one place for the JSDoc and for evolving the API without breaking the Rust core.\n *\n * The cost is one extra function call per operation — negligible next to the\n * real work (serialization + DashMap access) done in Rust.\n */\n\n// Namespace import: works the same in CommonJS and ESM when consuming the native\n// addon (a CJS module generated by napi-rs).\nimport * as native from \"../binding.js\";\n\n/** Eviction strategy when `maxSize` is reached. */\nexport type EvictionPolicy = \"reject\" | \"lru\";\n\n/** Cache constructor options. */\nexport interface CacheOptions {\n /**\n * Maximum number of keys. What happens when it is reached depends on\n * `evictionPolicy`. No value => unlimited cache.\n */\n maxSize?: number;\n /**\n * Policy when `maxSize` is reached on a **new** key:\n * - `\"reject\"` (default): `set` returns `false` (overwriting still works);\n * - `\"lru\"`: removes the least recently used entry and goes on.\n */\n evictionPolicy?: EvictionPolicy;\n /**\n * When set (> 0), starts a thread that sweeps expired entries every N\n * seconds (background expiration, on top of the lazy one on access).\n */\n cleanupIntervalSeconds?: number;\n}\n\n/** Per-write options. */\nexport interface SetOptions {\n /** Time to live in seconds. Absent => the entry does not expire by time. */\n ttlSeconds?: number;\n}\n\n/** Accumulated cache statistics (plus the current size). */\nexport interface CacheStats {\n /** Reads that found a valid entry. */\n hits: number;\n /** Reads without a valid key (missing or expired). */\n misses: number;\n /** Total writes (`set`). */\n sets: number;\n /** Total explicit removals (`delete`). */\n deletes: number;\n /** Total entries removed by expiration. */\n expired: number;\n /** Total entries removed by eviction (LRU policy when `maxSize` is reached). */\n evicted: number;\n /** Number of keys stored right now. */\n size: number;\n}\n\n/**\n * In-memory cache with a Rust core (DashMap + atomic counters). Thread-safe,\n * with an optional TTL per entry.\n *\n * @example\n * ```ts\n * import { Cache } from \"rust-node-cache\";\n *\n * const cache = new Cache();\n * cache.set(\"user:1\", { id: 1, name: \"Roberto\" });\n * cache.get<{ id: number; name: string }>(\"user:1\"); // { id: 1, name: \"Roberto\" }\n * ```\n */\nexport class Cache {\n /** Instance of the native (Rust) class. */\n private readonly native: native.Cache;\n\n constructor(options: CacheOptions = {}) {\n // An options object is passed to Rust only when it carries something.\n const hasOptions =\n options.maxSize !== undefined ||\n options.evictionPolicy !== undefined ||\n options.cleanupIntervalSeconds !== undefined;\n this.native = hasOptions\n ? new native.Cache({\n maxSize: options.maxSize,\n evictionPolicy: options.evictionPolicy,\n cleanupIntervalSeconds: options.cleanupIntervalSeconds,\n })\n : new native.Cache();\n }\n\n /** The active eviction policy: `\"reject\"` or `\"lru\"`. */\n get evictionPolicy(): EvictionPolicy {\n return this.native.evictionPolicy as EvictionPolicy;\n }\n\n /**\n * Stores (or overwrites) a value. The value is serialized as JSON in the core.\n *\n * @returns `true` on success; `false` if `maxSize` was reached and the key is new.\n */\n set<T>(key: string, value: T, options?: SetOptions): boolean {\n return this.native.set(key, value as unknown as object, options);\n }\n\n /**\n * Reads a value. Applies lazy expiration: expired keys count as a miss.\n *\n * @returns the deserialized value, or `null` if missing or expired.\n */\n get<T = unknown>(key: string): T | null {\n const value = this.native.get(key);\n return value === null || value === undefined ? null : (value as T);\n }\n\n /** Removes a key. Returns `true` if it existed. */\n delete(key: string): boolean {\n return this.native.delete(key);\n }\n\n /** Whether the key exists and is still valid (not expired). */\n exists(key: string): boolean {\n return this.native.exists(key);\n }\n\n /** Empties the cache (does not reset the historical `stats` counters). */\n clear(): void {\n this.native.clear();\n }\n\n /** Number of keys currently stored. */\n size(): number {\n return this.native.size();\n }\n\n /**\n * Sweeps and removes every expired entry at once.\n *\n * @returns how many entries were removed.\n */\n cleanupExpired(): number {\n return this.native.cleanupExpired();\n }\n\n /** Returns the accumulated statistics + the current size. */\n stats(): CacheStats {\n return this.native.stats();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA,eAAAA;AAAA;AAAA;AAiBA,aAAwB;AA8DjB,IAAMA,SAAN,MAAY;AAAA,EAIjB,YAAY,UAAwB,CAAC,GAAG;AAEtC,UAAM,aACJ,QAAQ,YAAY,UACpB,QAAQ,mBAAmB,UAC3B,QAAQ,2BAA2B;AACrC,SAAK,SAAS,aACV,IAAW,aAAM;AAAA,MACf,SAAS,QAAQ;AAAA,MACjB,gBAAgB,QAAQ;AAAA,MACxB,wBAAwB,QAAQ;AAAA,IAClC,CAAC,IACD,IAAW,aAAM;AAAA,EACvB;AAAA;AAAA,EAGA,IAAI,iBAAiC;AACnC,WAAO,KAAK,OAAO;AAAA,EACrB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAO,KAAa,OAAU,SAA+B;AAC3D,WAAO,KAAK,OAAO,IAAI,KAAK,OAA4B,OAAO;AAAA,EACjE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAiB,KAAuB;AACtC,UAAM,QAAQ,KAAK,OAAO,IAAI,GAAG;AACjC,WAAO,UAAU,QAAQ,UAAU,SAAY,OAAQ;AAAA,EACzD;AAAA;AAAA,EAGA,OAAO,KAAsB;AAC3B,WAAO,KAAK,OAAO,OAAO,GAAG;AAAA,EAC/B;AAAA;AAAA,EAGA,OAAO,KAAsB;AAC3B,WAAO,KAAK,OAAO,OAAO,GAAG;AAAA,EAC/B;AAAA;AAAA,EAGA,QAAc;AACZ,SAAK,OAAO,MAAM;AAAA,EACpB;AAAA;AAAA,EAGA,OAAe;AACb,WAAO,KAAK,OAAO,KAAK;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,iBAAyB;AACvB,WAAO,KAAK,OAAO,eAAe;AAAA,EACpC;AAAA;AAAA,EAGA,QAAoB;AAClB,WAAO,KAAK,OAAO,MAAM;AAAA,EAC3B;AACF;","names":["Cache"]}
package/dist/index.mjs CHANGED
@@ -2,50 +2,59 @@
2
2
  import * as native from "../binding.js";
3
3
  var Cache2 = class {
4
4
  constructor(options = {}) {
5
- this.native = options.maxSize !== void 0 ? new native.Cache({ maxSize: options.maxSize }) : new native.Cache();
5
+ const hasOptions = options.maxSize !== void 0 || options.evictionPolicy !== void 0 || options.cleanupIntervalSeconds !== void 0;
6
+ this.native = hasOptions ? new native.Cache({
7
+ maxSize: options.maxSize,
8
+ evictionPolicy: options.evictionPolicy,
9
+ cleanupIntervalSeconds: options.cleanupIntervalSeconds
10
+ }) : new native.Cache();
11
+ }
12
+ /** The active eviction policy: `"reject"` or `"lru"`. */
13
+ get evictionPolicy() {
14
+ return this.native.evictionPolicy;
6
15
  }
7
16
  /**
8
- * Armazena (ou sobrescreve) um valor. O valor é serializado como JSON no core.
17
+ * Stores (or overwrites) a value. The value is serialized as JSON in the core.
9
18
  *
10
- * @returns `true` em sucesso; `false` se `maxSize` foi atingido e a chave é nova.
19
+ * @returns `true` on success; `false` if `maxSize` was reached and the key is new.
11
20
  */
12
21
  set(key, value, options) {
13
22
  return this.native.set(key, value, options);
14
23
  }
15
24
  /**
16
- * Lê um valor. Aplica expiração preguiçosa: chaves vencidas contam como miss.
25
+ * Reads a value. Applies lazy expiration: expired keys count as a miss.
17
26
  *
18
- * @returns o valor desserializado, ou `null` se ausente/expirado.
27
+ * @returns the deserialized value, or `null` if missing or expired.
19
28
  */
20
29
  get(key) {
21
30
  const value = this.native.get(key);
22
31
  return value === null || value === void 0 ? null : value;
23
32
  }
24
- /** Remove uma chave. Retorna `true` se ela existia. */
33
+ /** Removes a key. Returns `true` if it existed. */
25
34
  delete(key) {
26
35
  return this.native.delete(key);
27
36
  }
28
- /** Indica se a chave existe e está válida (não expirada). */
37
+ /** Whether the key exists and is still valid (not expired). */
29
38
  exists(key) {
30
39
  return this.native.exists(key);
31
40
  }
32
- /** Esvazia o cache (não zera os contadores históricos de `stats`). */
41
+ /** Empties the cache (does not reset the historical `stats` counters). */
33
42
  clear() {
34
43
  this.native.clear();
35
44
  }
36
- /** Número de chaves armazenadas no momento. */
45
+ /** Number of keys currently stored. */
37
46
  size() {
38
47
  return this.native.size();
39
48
  }
40
49
  /**
41
- * Varre e remove todas as entradas expiradas de uma só vez.
50
+ * Sweeps and removes every expired entry at once.
42
51
  *
43
- * @returns quantas entradas foram removidas.
52
+ * @returns how many entries were removed.
44
53
  */
45
54
  cleanupExpired() {
46
55
  return this.native.cleanupExpired();
47
56
  }
48
- /** Retorna as estatísticas acumuladas + o tamanho atual. */
57
+ /** Returns the accumulated statistics + the current size. */
49
58
  stats() {
50
59
  return this.native.stats();
51
60
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../js/index.ts"],"sourcesContent":["/**\n * rust-node-cache — API pública (TypeScript).\n *\n * \"Ultra-fast in-memory cache powered by Rust.\"\n *\n * Esta camada é um wrapper fino e tipado sobre a classe `Cache` nativa gerada\n * pelo Rust/napi-rs. Por que envolver em vez de re-exportar direto?\n * - permite **genéricos** ergonômicos: `cache.get<User>(\"user:1\")`;\n * - normaliza `undefined`/`null` para sempre devolver `null` num miss;\n * - dá um único lugar para JSDoc e para evoluir a API sem quebrar o core Rust.\n *\n * O custo é uma chamada de função extra por operação — desprezível frente ao\n * trabalho real (serialização + acesso ao DashMap) que acontece no Rust.\n */\n\n// Namespace import: funciona igual em CommonJS e ESM ao consumir o addon nativo\n// (que é um módulo CJS gerado pelo napi-rs).\nimport * as native from \"../binding.js\";\n\n/** Opções do construtor do cache. */\nexport interface CacheOptions {\n /**\n * Limite máximo de chaves. Ao ser atingido, `set` de uma chave **nova**\n * retorna `false` (sobrescrever chave existente continua permitido).\n * Sem valor => cache ilimitado.\n */\n maxSize?: number;\n}\n\n/** Opções por operação de escrita. */\nexport interface SetOptions {\n /** Tempo de vida em segundos. Ausente => a entrada não expira por tempo. */\n ttlSeconds?: number;\n}\n\n/** Estatísticas acumuladas do cache (mais o tamanho atual). */\nexport interface CacheStats {\n /** Leituras que encontraram uma entrada válida. */\n hits: number;\n /** Leituras sem chave válida (ausente ou expirada). */\n misses: number;\n /** Total de escritas (`set`). */\n sets: number;\n /** Total de remoções explícitas (`delete`). */\n deletes: number;\n /** Total de entradas removidas por expiração. */\n expired: number;\n /** Número de chaves armazenadas agora. */\n size: number;\n}\n\n/**\n * Cache em memória ultrarrápido com núcleo em Rust (DashMap + contadores\n * atômicos). Thread-safe e com suporte a TTL por entrada.\n *\n * @example\n * ```ts\n * import { Cache } from \"rust-node-cache\";\n *\n * const cache = new Cache();\n * cache.set(\"user:1\", { id: 1, name: \"Roberto\" });\n * cache.get<{ id: number; name: string }>(\"user:1\"); // { id: 1, name: \"Roberto\" }\n * ```\n */\nexport class Cache {\n /** Instância da classe nativa (Rust). */\n private readonly native: native.Cache;\n\n constructor(options: CacheOptions = {}) {\n // Só repassamos o objeto de opções ao Rust quando há algo relevante.\n this.native =\n options.maxSize !== undefined\n ? new native.Cache({ maxSize: options.maxSize })\n : new native.Cache();\n }\n\n /**\n * Armazena (ou sobrescreve) um valor. O valor é serializado como JSON no core.\n *\n * @returns `true` em sucesso; `false` se `maxSize` foi atingido e a chave é nova.\n */\n set<T>(key: string, value: T, options?: SetOptions): boolean {\n return this.native.set(key, value as unknown as object, options);\n }\n\n /**\n * Lê um valor. Aplica expiração preguiçosa: chaves vencidas contam como miss.\n *\n * @returns o valor desserializado, ou `null` se ausente/expirado.\n */\n get<T = unknown>(key: string): T | null {\n const value = this.native.get(key);\n return value === null || value === undefined ? null : (value as T);\n }\n\n /** Remove uma chave. Retorna `true` se ela existia. */\n delete(key: string): boolean {\n return this.native.delete(key);\n }\n\n /** Indica se a chave existe e está válida (não expirada). */\n exists(key: string): boolean {\n return this.native.exists(key);\n }\n\n /** Esvazia o cache (não zera os contadores históricos de `stats`). */\n clear(): void {\n this.native.clear();\n }\n\n /** Número de chaves armazenadas no momento. */\n size(): number {\n return this.native.size();\n }\n\n /**\n * Varre e remove todas as entradas expiradas de uma só vez.\n *\n * @returns quantas entradas foram removidas.\n */\n cleanupExpired(): number {\n return this.native.cleanupExpired();\n }\n\n /** Retorna as estatísticas acumuladas + o tamanho atual. */\n stats(): CacheStats {\n return this.native.stats();\n }\n}\n"],"mappings":";AAiBA,YAAY,YAAY;AA+CjB,IAAMA,SAAN,MAAY;AAAA,EAIjB,YAAY,UAAwB,CAAC,GAAG;AAEtC,SAAK,SACH,QAAQ,YAAY,SAChB,IAAW,aAAM,EAAE,SAAS,QAAQ,QAAQ,CAAC,IAC7C,IAAW,aAAM;AAAA,EACzB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAO,KAAa,OAAU,SAA+B;AAC3D,WAAO,KAAK,OAAO,IAAI,KAAK,OAA4B,OAAO;AAAA,EACjE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAiB,KAAuB;AACtC,UAAM,QAAQ,KAAK,OAAO,IAAI,GAAG;AACjC,WAAO,UAAU,QAAQ,UAAU,SAAY,OAAQ;AAAA,EACzD;AAAA;AAAA,EAGA,OAAO,KAAsB;AAC3B,WAAO,KAAK,OAAO,OAAO,GAAG;AAAA,EAC/B;AAAA;AAAA,EAGA,OAAO,KAAsB;AAC3B,WAAO,KAAK,OAAO,OAAO,GAAG;AAAA,EAC/B;AAAA;AAAA,EAGA,QAAc;AACZ,SAAK,OAAO,MAAM;AAAA,EACpB;AAAA;AAAA,EAGA,OAAe;AACb,WAAO,KAAK,OAAO,KAAK;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,iBAAyB;AACvB,WAAO,KAAK,OAAO,eAAe;AAAA,EACpC;AAAA;AAAA,EAGA,QAAoB;AAClB,WAAO,KAAK,OAAO,MAAM;AAAA,EAC3B;AACF;","names":["Cache"]}
1
+ {"version":3,"sources":["../js/index.ts"],"sourcesContent":["/**\n * rust-node-cache — public API (TypeScript).\n *\n * \"Ultra-fast in-memory cache powered by Rust.\"\n *\n * This layer is a thin, typed wrapper over the native `Cache` class generated\n * by Rust/napi-rs. Why wrap it instead of re-exporting it directly?\n * - it allows ergonomic **generics**: `cache.get<User>(\"user:1\")`;\n * - it normalizes `undefined`/`null` so a miss always returns `null`;\n * - it gives one place for the JSDoc and for evolving the API without breaking the Rust core.\n *\n * The cost is one extra function call per operation — negligible next to the\n * real work (serialization + DashMap access) done in Rust.\n */\n\n// Namespace import: works the same in CommonJS and ESM when consuming the native\n// addon (a CJS module generated by napi-rs).\nimport * as native from \"../binding.js\";\n\n/** Eviction strategy when `maxSize` is reached. */\nexport type EvictionPolicy = \"reject\" | \"lru\";\n\n/** Cache constructor options. */\nexport interface CacheOptions {\n /**\n * Maximum number of keys. What happens when it is reached depends on\n * `evictionPolicy`. No value => unlimited cache.\n */\n maxSize?: number;\n /**\n * Policy when `maxSize` is reached on a **new** key:\n * - `\"reject\"` (default): `set` returns `false` (overwriting still works);\n * - `\"lru\"`: removes the least recently used entry and goes on.\n */\n evictionPolicy?: EvictionPolicy;\n /**\n * When set (> 0), starts a thread that sweeps expired entries every N\n * seconds (background expiration, on top of the lazy one on access).\n */\n cleanupIntervalSeconds?: number;\n}\n\n/** Per-write options. */\nexport interface SetOptions {\n /** Time to live in seconds. Absent => the entry does not expire by time. */\n ttlSeconds?: number;\n}\n\n/** Accumulated cache statistics (plus the current size). */\nexport interface CacheStats {\n /** Reads that found a valid entry. */\n hits: number;\n /** Reads without a valid key (missing or expired). */\n misses: number;\n /** Total writes (`set`). */\n sets: number;\n /** Total explicit removals (`delete`). */\n deletes: number;\n /** Total entries removed by expiration. */\n expired: number;\n /** Total entries removed by eviction (LRU policy when `maxSize` is reached). */\n evicted: number;\n /** Number of keys stored right now. */\n size: number;\n}\n\n/**\n * In-memory cache with a Rust core (DashMap + atomic counters). Thread-safe,\n * with an optional TTL per entry.\n *\n * @example\n * ```ts\n * import { Cache } from \"rust-node-cache\";\n *\n * const cache = new Cache();\n * cache.set(\"user:1\", { id: 1, name: \"Roberto\" });\n * cache.get<{ id: number; name: string }>(\"user:1\"); // { id: 1, name: \"Roberto\" }\n * ```\n */\nexport class Cache {\n /** Instance of the native (Rust) class. */\n private readonly native: native.Cache;\n\n constructor(options: CacheOptions = {}) {\n // An options object is passed to Rust only when it carries something.\n const hasOptions =\n options.maxSize !== undefined ||\n options.evictionPolicy !== undefined ||\n options.cleanupIntervalSeconds !== undefined;\n this.native = hasOptions\n ? new native.Cache({\n maxSize: options.maxSize,\n evictionPolicy: options.evictionPolicy,\n cleanupIntervalSeconds: options.cleanupIntervalSeconds,\n })\n : new native.Cache();\n }\n\n /** The active eviction policy: `\"reject\"` or `\"lru\"`. */\n get evictionPolicy(): EvictionPolicy {\n return this.native.evictionPolicy as EvictionPolicy;\n }\n\n /**\n * Stores (or overwrites) a value. The value is serialized as JSON in the core.\n *\n * @returns `true` on success; `false` if `maxSize` was reached and the key is new.\n */\n set<T>(key: string, value: T, options?: SetOptions): boolean {\n return this.native.set(key, value as unknown as object, options);\n }\n\n /**\n * Reads a value. Applies lazy expiration: expired keys count as a miss.\n *\n * @returns the deserialized value, or `null` if missing or expired.\n */\n get<T = unknown>(key: string): T | null {\n const value = this.native.get(key);\n return value === null || value === undefined ? null : (value as T);\n }\n\n /** Removes a key. Returns `true` if it existed. */\n delete(key: string): boolean {\n return this.native.delete(key);\n }\n\n /** Whether the key exists and is still valid (not expired). */\n exists(key: string): boolean {\n return this.native.exists(key);\n }\n\n /** Empties the cache (does not reset the historical `stats` counters). */\n clear(): void {\n this.native.clear();\n }\n\n /** Number of keys currently stored. */\n size(): number {\n return this.native.size();\n }\n\n /**\n * Sweeps and removes every expired entry at once.\n *\n * @returns how many entries were removed.\n */\n cleanupExpired(): number {\n return this.native.cleanupExpired();\n }\n\n /** Returns the accumulated statistics + the current size. */\n stats(): CacheStats {\n return this.native.stats();\n }\n}\n"],"mappings":";AAiBA,YAAY,YAAY;AA8DjB,IAAMA,SAAN,MAAY;AAAA,EAIjB,YAAY,UAAwB,CAAC,GAAG;AAEtC,UAAM,aACJ,QAAQ,YAAY,UACpB,QAAQ,mBAAmB,UAC3B,QAAQ,2BAA2B;AACrC,SAAK,SAAS,aACV,IAAW,aAAM;AAAA,MACf,SAAS,QAAQ;AAAA,MACjB,gBAAgB,QAAQ;AAAA,MACxB,wBAAwB,QAAQ;AAAA,IAClC,CAAC,IACD,IAAW,aAAM;AAAA,EACvB;AAAA;AAAA,EAGA,IAAI,iBAAiC;AACnC,WAAO,KAAK,OAAO;AAAA,EACrB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAO,KAAa,OAAU,SAA+B;AAC3D,WAAO,KAAK,OAAO,IAAI,KAAK,OAA4B,OAAO;AAAA,EACjE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAiB,KAAuB;AACtC,UAAM,QAAQ,KAAK,OAAO,IAAI,GAAG;AACjC,WAAO,UAAU,QAAQ,UAAU,SAAY,OAAQ;AAAA,EACzD;AAAA;AAAA,EAGA,OAAO,KAAsB;AAC3B,WAAO,KAAK,OAAO,OAAO,GAAG;AAAA,EAC/B;AAAA;AAAA,EAGA,OAAO,KAAsB;AAC3B,WAAO,KAAK,OAAO,OAAO,GAAG;AAAA,EAC/B;AAAA;AAAA,EAGA,QAAc;AACZ,SAAK,OAAO,MAAM;AAAA,EACpB;AAAA;AAAA,EAGA,OAAe;AACb,WAAO,KAAK,OAAO,KAAK;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,iBAAyB;AACvB,WAAO,KAAK,OAAO,eAAe;AAAA,EACpC;AAAA;AAAA,EAGA,QAAoB;AAClB,WAAO,KAAK,OAAO,MAAM;AAAA,EAC3B;AACF;","names":["Cache"]}
package/dist/nestjs.d.mts CHANGED
@@ -3,36 +3,36 @@ import { Observable } from 'rxjs';
3
3
  import { Cache } from './index.mjs';
4
4
 
5
5
  /**
6
- * Integração com NestJS: interceptor de cache de respostas.
6
+ * NestJS integration: a response caching interceptor.
7
7
  *
8
- * Uso:
8
+ * Usage:
9
9
  * import { Cache } from "rust-node-cache";
10
10
  * import { CacheInterceptor } from "rust-node-cache/nestjs";
11
11
  *
12
12
  * const cache = new Cache();
13
13
  * app.useGlobalInterceptors(new CacheInterceptor({ cache, ttlSeconds: 60 }));
14
14
  *
15
- * Usamos `import type` para `@nestjs/common`, ou seja, NÃO há import em runtime
16
- * do Nest aqui — o pacote não força o Nest como dependência. A única dependência
17
- * de runtime são os operadores `of`/`tap` do RxJS (presentes em qualquer app Nest).
15
+ * `@nestjs/common` is imported with `import type`, so there is NO runtime import
16
+ * of Nest here — the package does not force Nest as a dependency. The only runtime
17
+ * dependencies are RxJS's `of`/`tap` operators (present in any Nest app).
18
18
  */
19
19
 
20
20
  interface CacheInterceptorOptions {
21
- /** Instância de cache a usar. */
21
+ /** Cache instance to use. */
22
22
  cache: Cache;
23
- /** TTL aplicado às respostas guardadas (em segundos). */
23
+ /** TTL applied to stored responses (in seconds). */
24
24
  ttlSeconds?: number;
25
- /** Métodos HTTP elegíveis para cache. Padrão: `["GET"]`. */
25
+ /** HTTP methods eligible for caching. Default: `["GET"]`. */
26
26
  methods?: string[];
27
- /** Gera a chave de cache a partir da requisição. Padrão: `METHOD:url`. */
27
+ /** Builds the cache key from the request. Default: `METHOD:url`. */
28
28
  keyGenerator?: (req: {
29
29
  method: string;
30
30
  url: string;
31
31
  }) => string;
32
32
  }
33
33
  /**
34
- * Interceptor NestJS que cacheia o valor retornado pelos handlers. Num HIT,
35
- * devolve o valor do cache sem executar o handler.
34
+ * NestJS interceptor that caches the value returned by handlers. On a HIT, it
35
+ * returns the cached value without running the handler.
36
36
  */
37
37
  declare class CacheInterceptor implements NestInterceptor {
38
38
  private readonly cache;