@blaze-cache/core 0.2.1-beta → 0.2.3-beta

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/README.md CHANGED
@@ -8,7 +8,8 @@ WebAssembly client-side cache for the browser: SIEVE eviction, per-entry TTLs, t
8
8
  invalidation and optional IndexedDB persistence.
9
9
 
10
10
  The engine behind
11
- [`@blaze-cache/axios`](https://www.npmjs.com/package/@blaze-cache/axios) and
11
+ [`@blaze-cache/axios`](https://www.npmjs.com/package/@blaze-cache/axios),
12
+ [`@blaze-cache/fetch`](https://www.npmjs.com/package/@blaze-cache/fetch) and
12
13
  [`@blaze-cache/react-query`](https://www.npmjs.com/package/@blaze-cache/react-query) —
13
14
  also usable on its own.
14
15
 
@@ -41,6 +42,53 @@ cache.stats(); // { hits, misses, evictions, expirations,
41
42
  `create` instantiates the wasm module once, so everything after it is **synchronous** —
42
43
  `get`/`set` never allocate a `Promise`.
43
44
 
45
+ ## Events
46
+
47
+ Everything the cache does is observable through a typed event system. `on(type, listener)`
48
+ subscribes to one event type, `on(listener)` subscribes to **all** of them (wildcard), both
49
+ return their own unsubscribe function, and `once` / `off` complete the API:
50
+
51
+ ```ts
52
+ // One event type — the payload is typed to exactly that event.
53
+ const offEvict = cache.on('evict', ({ key, value }) => {
54
+ console.log('the cache dropped', key, value);
55
+ });
56
+
57
+ // Wildcard: every event, payload the full union (narrow on `event.type`).
58
+ cache.on((event) => {
59
+ if (event.type === 'hit') console.log('hit', event.key, event.value);
60
+ });
61
+
62
+ cache.once('clear', () => console.log('first clear, only once'));
63
+
64
+ cache.off('evict'); // every `evict` listener
65
+ cache.off(); // every listener, period
66
+ offEvict(); // …or just this one handle (idempotent)
67
+ ```
68
+
69
+ | Event | Emitted when | Payload |
70
+ | --- | --- | --- |
71
+ | `set` | a key was stored (insert or replace) | `key` |
72
+ | `delete` | a key was removed and was present | `key` |
73
+ | `clear` | the cache was emptied | — |
74
+ | `invalidate` | `invalidateTags()` removed entries | `keys` |
75
+ | `prune` | `prune()` removed expired entries | `keys` |
76
+ | `touch` | `touch()` renewed a live entry's deadline | `key` |
77
+ | `evict` | the core dropped an entry to stay within capacity | `key`, `value` |
78
+ | `expire` | the core reclaimed an entry whose TTL elapsed | `key`, `value` |
79
+ | `hit` | `get()` / `getMany()` found a live entry | `key`, `value` |
80
+ | `miss` | a lookup found nothing (absent or expired) | `key` |
81
+
82
+ Eight of those are raised in TypeScript around the call you made; `evict` and `expire`
83
+ happen *inside* the Rust core and are delivered from an opt-in **drop log** — the first
84
+ listener interested in them switches it on through the wasm binding, and with no such
85
+ listener the hot path pays a single predictable branch. Listeners run synchronously in
86
+ registration order (typed first, wildcards last), a throwing listener is logged and
87
+ skipped — never able to undo a mutation — and reads that record nothing (`peek`, `has`,
88
+ `ttl`, `size`, `keys`, `entry`) emit nothing. `dispose()` clears every listener along with
89
+ the wasm memory. The full design notes live in the
90
+ [repository README](https://github.com/blaze-cache/blaze-cache#events).
91
+
44
92
  ## Good to know
45
93
 
46
94
  * **The `.wasm` ships inside this package** — no CDN setup. If your bundler
@@ -65,10 +113,13 @@ cache.stats(); // { hits, misses, evictions, expirations,
65
113
  * **`capacity` is normalised** — below `1` clamps up, above `1_000_000` clamps down, and
66
114
  a non-finite value falls back to the wasm default — so `capacity()` reports a real
67
115
  number back.
116
+ * **Events cost nothing when unused** — with no listeners the bus is a size check per
117
+ operation, and the Rust core's drop log stays off until somebody asks for
118
+ `evict`/`expire` (see [Events](#events)).
68
119
 
69
120
  ## Documentation
70
121
 
71
- Setup, persistence, eviction, tags and the full API are documented in the
122
+ Setup, persistence, eviction, tags, events and the full API are documented in the
72
123
  [repository README](https://github.com/blaze-cache/blaze-cache#readme).
73
124
 
74
125
  ## License
package/dist/cache.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { BlazeCacheLike, CacheEntry, CacheListener, CacheStats, SetOptions, TouchOptions } from './types.js';
1
+ import type { BlazeCacheLike, CacheEntry, CacheEventListener, CacheEventType, CacheListener, CacheStats, SetManyEntry, SetOptions, TouchOptions } from './types.js';
2
2
  import type { WasmInitInput } from './wasm.js';
3
3
  import type { CachePersistence, IndexedDbOptions } from './persistence/types.js';
4
4
  /** Entries held when `capacity` is not given. */
@@ -76,6 +76,51 @@ export interface BlazeCacheOptions {
76
76
  * anyway (your original reference from `set` survives either way). The contract is
77
77
  * ownership transfer, not deep-copy semantics.
78
78
  *
79
+ * ### Events
80
+ *
81
+ * {@link BlazeCache.on} subscribes to one {@link CacheEventType} — `on('set', listener)` —
82
+ * or, without a type, to **every** event; `once` fires a single time, `off` removes
83
+ * listeners without a subscription handle, and every `on`/`once` call returns its own
84
+ * unsubscribe function.
85
+ *
86
+ * Eight event types are raised here in TypeScript, describing the operation you just made.
87
+ * `evict` and `expire` are the exception: capacity sweeps and TTL reclamation happen
88
+ * *inside* the Rust core — mid-`set`, or lazily during a `get` — where no JavaScript
89
+ * exists to observe them. For those the core keeps an opt-in **drop log**. The first
90
+ * listener interested in `evict`/`expire` (a typed one, or any wildcard) switches the log
91
+ * on through the wasm binding, and after every operation that can reclaim memory (`get`,
92
+ * `getMany`, `set`, `setMany`) this class drains it and emits one event per dropped entry:
93
+ * `{ type: 'evict' | 'expire', key, value }`, with `value` coming back as the cache's live
94
+ * reference — exactly what you would have got from `get` one moment earlier. While no such
95
+ * listener exists the log stays off and the hot path pays a single predictable branch at
96
+ * the moment an entry dies — never per read or write.
97
+ *
98
+ * ```ts
99
+ * const offEvict = cache.on('evict', ({ key, value }) => {
100
+ * console.log('the cache dropped', key, value);
101
+ * });
102
+ *
103
+ * const offAll = cache.on((event) => { // wildcard — every event type
104
+ * if (event.type === 'hit') console.log('hit', event.key);
105
+ * });
106
+ *
107
+ * cache.once('clear', () => console.log('first clear, only once'));
108
+ *
109
+ * offEvict(); // unsubscribe one handle
110
+ * cache.off('evict'); // …or drop every `evict` listener
111
+ * cache.off(); // …or every listener, period
112
+ * ```
113
+ *
114
+ * Wildcard listeners receive the full {@link CacheEvent} union, so narrow on
115
+ * `event.type` before reading fields. A listener that throws is isolated: the failure is
116
+ * logged with `console.error`, the mutation it was told about stands, and the remaining
117
+ * listeners still run. Listeners run synchronously, in registration order per type (typed
118
+ * listeners first, wildcards last) — an event is never delivered to a listener that
119
+ * unsubscribed before its turn.
120
+ *
121
+ * Code written against the original `on(listener)` API keeps working: that form *is* the
122
+ * wildcard now, so such listeners additionally see `hit`/`miss`/`evict`/`expire`.
123
+ *
79
124
  * ### Multiple tabs
80
125
  *
81
126
  * Tabs share one IndexedDB namespace but nothing else: each one holds its own WebAssembly
@@ -105,9 +150,19 @@ export declare class BlazeCache<V = any> implements BlazeCacheLike<V> {
105
150
  * Value stored under `key`, or `undefined` when missing or expired. Counts a hit/miss.
106
151
  *
107
152
  * The value comes back as the cache's **live reference** — see *Value ownership* on the
108
- * class before mutating it.
153
+ * class before mutating it. Emits {@link CacheEventMap.hit} / {@link CacheEventMap.miss}
154
+ * when someone listens, and an entry whose stored value *is* `undefined` counts as a
155
+ * miss — from the caller's side there is no way to tell it apart from absence anyway.
109
156
  */
110
157
  get(key: string): V | undefined;
158
+ /**
159
+ * Batch lookup: returns the value for each key, or `undefined` when missing/expired.
160
+ * Crosses the wasm boundary once instead of once per key.
161
+ *
162
+ * Each hit marks the entry visited for SIEVE, exactly like {@link BlazeCache.get} — and
163
+ * emits one `hit`/`miss` event per key.
164
+ */
165
+ getMany(keys: string[]): (V | undefined)[];
111
166
  /**
112
167
  * The same lookup as {@link BlazeCache.get}, minus every side effect: no hit or miss is
113
168
  * recorded, the entry is not marked used for eviction, and nothing is reclaimed.
@@ -127,6 +182,11 @@ export declare class BlazeCache<V = any> implements BlazeCacheLike<V> {
127
182
  ttl(key: string): number | undefined;
128
183
  /** `true` when `key` is present and not expired. Never changes eviction state. */
129
184
  has(key: string): boolean;
185
+ /**
186
+ * Batch existence check: returns `true` for each key that is present and not expired.
187
+ * Crosses the wasm boundary once instead of once per key.
188
+ */
189
+ hasMany(keys: string[]): boolean[];
130
190
  /**
131
191
  * Live entry — value, remaining TTL and tags — without touching statistics. The `value`
132
192
  * field is the cache's live reference — see *Value ownership* on the class.
@@ -163,6 +223,15 @@ export declare class BlazeCache<V = any> implements BlazeCacheLike<V> {
163
223
  * entry, so mutating it afterwards rewrites the cache (see *Value ownership* on the class).
164
224
  */
165
225
  set(key: string, value: V, options?: SetOptions): void;
226
+ /**
227
+ * Batch write: stores every key/value pair in one wasm boundary crossing.
228
+ *
229
+ * Each entry's `ttlMs` and `tags` are applied independently. A negative `ttlMs` means
230
+ * "no expiry". Crosses the boundary once instead of once per entry.
231
+ *
232
+ * Listeners are notified for each entry when change consumers exist.
233
+ */
234
+ setMany(entries: SetManyEntry<V>[]): void;
166
235
  /**
167
236
  * Marks `key` as recently used for eviction and optionally renews its TTL — the stored
168
237
  * value is never changed.
@@ -174,6 +243,11 @@ export declare class BlazeCache<V = any> implements BlazeCacheLike<V> {
174
243
  touch(key: string, options?: TouchOptions): boolean;
175
244
  /** Removes `key`, returning whether it was there. */
176
245
  delete(key: string): boolean;
246
+ /**
247
+ * Batch delete: removes every key, returning `true` for each key that was present.
248
+ * Crosses the wasm boundary once instead of once per key.
249
+ */
250
+ deleteMany(keys: string[]): boolean[];
177
251
  /** Removes every entry carrying any of `tags`, returning the removed keys. */
178
252
  invalidateTags(...tags: string[]): string[];
179
253
  /** Removes every expired entry, returning the removed keys. */
@@ -183,14 +257,60 @@ export declare class BlazeCache<V = any> implements BlazeCacheLike<V> {
183
257
  /** Zeroes the cumulative counters without touching stored entries. */
184
258
  resetStats(): void;
185
259
  /**
186
- * Subscribes to mutations. Returns the unsubscribe function.
260
+ * Subscribes to cache events. Returns the unsubscribe function.
261
+ *
262
+ * Two forms:
263
+ *
264
+ * * `on(type, listener)` — only events of that {@link CacheEventType}; the payload is
265
+ * typed to exactly that event.
266
+ * * `on(listener)` — **wildcard**: every event, payload the full {@link CacheEvent}
267
+ * union (narrow on `event.type` to read per-event fields).
187
268
  *
188
- * Persistence uses this internally, so listeners fire for every change regardless of
189
- * whether storage is enabled. A listener that throws is isolated: the failure is logged
190
- * with `console.error`, the mutation it was told about stands, and the remaining listeners
191
- * are still notified.
269
+ * Registering the same function twice for the same type is a no-op, and the returned
270
+ * unsubscribe function is idempotent. Persistence uses listeners internally, so
271
+ * bookkeeping runs for every change regardless of whether anyone subscribed; a listener
272
+ * that throws is isolated — the failure is logged with `console.error`, the mutation it
273
+ * was told about stands, and the remaining listeners are still notified.
274
+ *
275
+ * Subscribing to `evict`/`expire` (or to anything via the wildcard) switches on the Rust
276
+ * core's drop log — see *Events* on the class. Unsubscribing the last such listener
277
+ * switches it off again.
278
+ *
279
+ * @example
280
+ * ```ts
281
+ * const off = cache.on('set', ({ key }) => console.log('stored', key));
282
+ * const offAll = cache.on((event) => console.log(event.type));
283
+ * off();
284
+ * ```
192
285
  */
286
+ on<K extends CacheEventType>(type: K, listener: CacheEventListener<V, K>): () => void;
287
+ on(listener: CacheEventListener<V>): () => void;
288
+ /** @deprecated The pre-event-system signature — kept so old annotations still compile. */
193
289
  on(listener: CacheListener): () => void;
290
+ /**
291
+ * Like {@link BlazeCache.on}, but the listener fires at most once — it is removed as it
292
+ * runs, so a re-entrant emit from inside it cannot deliver a second time. Returns the
293
+ * unsubscribe function, which simply becomes a no-op after the fire.
294
+ */
295
+ once<K extends CacheEventType>(type: K, listener: CacheEventListener<V, K>): () => void;
296
+ once(listener: CacheEventListener<V>): () => void;
297
+ /** @deprecated The pre-event-system signature — kept so old annotations still compile. */
298
+ once(listener: CacheListener): () => void;
299
+ /**
300
+ * Removes listeners without needing the unsubscribe handle:
301
+ *
302
+ * * `off()` — every listener of every type;
303
+ * * `off(type)` — every listener of that type;
304
+ * * `off(type, listener)` — that one registration;
305
+ * * `off(listener)` — that function from the wildcard **and** every typed set.
306
+ *
307
+ * Calling it with something that is not registered is a no-op. Releasing the last
308
+ * `evict`/`expire`-interested listener also switches the core's drop log off.
309
+ */
310
+ off(): void;
311
+ off(type: CacheEventType): void;
312
+ off(type: CacheEventType, listener: CacheEventListener<V>): void;
313
+ off(listener: CacheEventListener<V> | CacheListener): void;
194
314
  /**
195
315
  * Writes pending changes to storage immediately.
196
316
  *
@@ -1 +1 @@
1
- {"version":3,"file":"cache.d.ts","sourceRoot":"","sources":["../src/cache.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,cAAc,EAEd,UAAU,EACV,aAAa,EACb,UAAU,EACV,UAAU,EACV,YAAY,EACb,MAAM,YAAY,CAAC;AAEpB,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAE/C,OAAO,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAmB,MAAM,wBAAwB,CAAC;AAElG,iDAAiD;AACjD,eAAO,MAAM,gBAAgB,MAAM,CAAC;AACpC,2EAA2E;AAC3E,eAAO,MAAM,sBAAsB,MAAM,CAAC;AAC1C,wDAAwD;AACxD,eAAO,MAAM,mBAAmB,OAAO,CAAC;AAUxC,6DAA6D;AAC7D,MAAM,WAAW,uBAAuB;IACtC,OAAO,EAAE,gBAAgB,CAAC;IAC1B,yFAAyF;IACzF,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,6FAA6F;IAC7F,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,+EAA+E;AAC/E,MAAM,WAAW,2BAA4B,SAAQ,gBAAgB;IACnE,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,qDAAqD;AACrD,MAAM,WAAW,iBAAiB;IAChC;;;;;;;OAOG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;;OAKG;IACH,WAAW,CAAC,EAAE,KAAK,GAAG,uBAAuB,GAAG,2BAA2B,CAAC;IAC5E;;;;;OAKG;IACH,IAAI,CAAC,EAAE,aAAa,CAAC;CACtB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AACH,qBA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dist/cache.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { CacheEventBus } from './events.js';
1
2
  import { initBlazeWasm, WasmCache } from './wasm.js';
2
3
  import { indexedDbPersistence } from './persistence/indexeddb.js';
3
4
  /** Entries held when `capacity` is not given. */
@@ -44,6 +45,51 @@ const NO_TAGS = [];
44
45
  * anyway (your original reference from `set` survives either way). The contract is
45
46
  * ownership transfer, not deep-copy semantics.
46
47
  *
48
+ * ### Events
49
+ *
50
+ * {@link BlazeCache.on} subscribes to one {@link CacheEventType} — `on('set', listener)` —
51
+ * or, without a type, to **every** event; `once` fires a single time, `off` removes
52
+ * listeners without a subscription handle, and every `on`/`once` call returns its own
53
+ * unsubscribe function.
54
+ *
55
+ * Eight event types are raised here in TypeScript, describing the operation you just made.
56
+ * `evict` and `expire` are the exception: capacity sweeps and TTL reclamation happen
57
+ * *inside* the Rust core — mid-`set`, or lazily during a `get` — where no JavaScript
58
+ * exists to observe them. For those the core keeps an opt-in **drop log**. The first
59
+ * listener interested in `evict`/`expire` (a typed one, or any wildcard) switches the log
60
+ * on through the wasm binding, and after every operation that can reclaim memory (`get`,
61
+ * `getMany`, `set`, `setMany`) this class drains it and emits one event per dropped entry:
62
+ * `{ type: 'evict' | 'expire', key, value }`, with `value` coming back as the cache's live
63
+ * reference — exactly what you would have got from `get` one moment earlier. While no such
64
+ * listener exists the log stays off and the hot path pays a single predictable branch at
65
+ * the moment an entry dies — never per read or write.
66
+ *
67
+ * ```ts
68
+ * const offEvict = cache.on('evict', ({ key, value }) => {
69
+ * console.log('the cache dropped', key, value);
70
+ * });
71
+ *
72
+ * const offAll = cache.on((event) => { // wildcard — every event type
73
+ * if (event.type === 'hit') console.log('hit', event.key);
74
+ * });
75
+ *
76
+ * cache.once('clear', () => console.log('first clear, only once'));
77
+ *
78
+ * offEvict(); // unsubscribe one handle
79
+ * cache.off('evict'); // …or drop every `evict` listener
80
+ * cache.off(); // …or every listener, period
81
+ * ```
82
+ *
83
+ * Wildcard listeners receive the full {@link CacheEvent} union, so narrow on
84
+ * `event.type` before reading fields. A listener that throws is isolated: the failure is
85
+ * logged with `console.error`, the mutation it was told about stands, and the remaining
86
+ * listeners still run. Listeners run synchronously, in registration order per type (typed
87
+ * listeners first, wildcards last) — an event is never delivered to a listener that
88
+ * unsubscribed before its turn.
89
+ *
90
+ * Code written against the original `on(listener)` API keeps working: that form *is* the
91
+ * wildcard now, so such listeners additionally see `hit`/`miss`/`evict`/`expire`.
92
+ *
47
93
  * ### Multiple tabs
48
94
  *
49
95
  * Tabs share one IndexedDB namespace but nothing else: each one holds its own WebAssembly
@@ -61,7 +107,12 @@ const NO_TAGS = [];
61
107
  */
62
108
  export class BlazeCache {
63
109
  #wasm;
64
- #listeners = new Set();
110
+ #events = new CacheEventBus(() => this.#syncDropTracking());
111
+ /**
112
+ * Mirrors {@link CacheEventBus.wantsDrops} onto the wasm core: `true` while the Rust
113
+ * side records evictions/expirations for us to drain. `false` costs nothing.
114
+ */
115
+ #dropTracking = false;
65
116
  #unbind = [];
66
117
  #persist = null;
67
118
  #flushDelayMs = DEFAULT_FLUSH_DELAY_MS;
@@ -92,10 +143,53 @@ export class BlazeCache {
92
143
  * Value stored under `key`, or `undefined` when missing or expired. Counts a hit/miss.
93
144
  *
94
145
  * The value comes back as the cache's **live reference** — see *Value ownership* on the
95
- * class before mutating it.
146
+ * class before mutating it. Emits {@link CacheEventMap.hit} / {@link CacheEventMap.miss}
147
+ * when someone listens, and an entry whose stored value *is* `undefined` counts as a
148
+ * miss — from the caller's side there is no way to tell it apart from absence anyway.
96
149
  */
97
150
  get(key) {
98
- return this.#wasm.get(key);
151
+ const value = this.#wasm.get(key);
152
+ // `hears` first: the payload (and the boundary-crossing bookkeeping around it) is only
153
+ // built when a listener of that exact type — or a wildcard — exists.
154
+ if (value === undefined) {
155
+ if (this.#events.hears('miss'))
156
+ this.#events.emit('miss', { type: 'miss', key });
157
+ }
158
+ else if (this.#events.hears('hit')) {
159
+ this.#events.emit('hit', { type: 'hit', key, value });
160
+ }
161
+ // The core may have reclaimed an expired entry during this very lookup.
162
+ if (this.#dropTracking)
163
+ this.#drainDrops();
164
+ return value;
165
+ }
166
+ /**
167
+ * Batch lookup: returns the value for each key, or `undefined` when missing/expired.
168
+ * Crosses the wasm boundary once instead of once per key.
169
+ *
170
+ * Each hit marks the entry visited for SIEVE, exactly like {@link BlazeCache.get} — and
171
+ * emits one `hit`/`miss` event per key.
172
+ */
173
+ getMany(keys) {
174
+ const values = this.#wasm.getMany(keys);
175
+ const wantsHit = this.#events.hears('hit');
176
+ const wantsMiss = this.#events.hears('miss');
177
+ if (wantsHit || wantsMiss) {
178
+ for (let i = 0; i < keys.length; i += 1) {
179
+ const key = keys[i];
180
+ const value = values[i];
181
+ if (value === undefined) {
182
+ if (wantsMiss)
183
+ this.#events.emit('miss', { type: 'miss', key });
184
+ }
185
+ else if (wantsHit) {
186
+ this.#events.emit('hit', { type: 'hit', key, value });
187
+ }
188
+ }
189
+ }
190
+ if (this.#dropTracking)
191
+ this.#drainDrops();
192
+ return values;
99
193
  }
100
194
  /**
101
195
  * The same lookup as {@link BlazeCache.get}, minus every side effect: no hit or miss is
@@ -122,6 +216,17 @@ export class BlazeCache {
122
216
  has(key) {
123
217
  return this.#wasm.has(key);
124
218
  }
219
+ /**
220
+ * Batch existence check: returns `true` for each key that is present and not expired.
221
+ * Crosses the wasm boundary once instead of once per key.
222
+ */
223
+ hasMany(keys) {
224
+ const flags = this.#wasm.hasMany(keys);
225
+ const result = new Array(flags.length);
226
+ for (let i = 0; i < flags.length; i += 1)
227
+ result[i] = flags[i] === 1;
228
+ return result;
229
+ }
125
230
  /**
126
231
  * Live entry — value, remaining TTL and tags — without touching statistics. The `value`
127
232
  * field is the cache's live reference — see *Value ownership* on the class.
@@ -185,6 +290,46 @@ export class BlazeCache {
185
290
  this.#wasm.set(key, value, options?.ttlMs ?? null, (options?.tags ?? NO_TAGS));
186
291
  if (this.#hasChangeConsumers)
187
292
  this.#notify({ type: 'set', key });
293
+ // Capacity pressure is applied inside the wasm call: entries it dropped surface here.
294
+ if (this.#dropTracking)
295
+ this.#drainDrops();
296
+ }
297
+ /**
298
+ * Batch write: stores every key/value pair in one wasm boundary crossing.
299
+ *
300
+ * Each entry's `ttlMs` and `tags` are applied independently. A negative `ttlMs` means
301
+ * "no expiry". Crosses the boundary once instead of once per entry.
302
+ *
303
+ * Listeners are notified for each entry when change consumers exist.
304
+ */
305
+ setMany(entries) {
306
+ const n = entries.length;
307
+ const keys = new Array(n);
308
+ const values = new Array(n);
309
+ const ttlMs = new Float64Array(n);
310
+ const tagsFlat = [];
311
+ const tagOffsets = new Uint32Array(n + 1);
312
+ tagOffsets[0] = 0;
313
+ for (let i = 0; i < n; i += 1) {
314
+ const entry = entries[i];
315
+ keys[i] = entry.key;
316
+ values[i] = entry.value;
317
+ ttlMs[i] = entry.options?.ttlMs ?? -1;
318
+ const tags = entry.options?.tags;
319
+ if (tags) {
320
+ for (const tag of tags)
321
+ tagsFlat.push(tag);
322
+ }
323
+ tagOffsets[i + 1] = tagsFlat.length;
324
+ }
325
+ this.#wasm.setMany(keys, values, ttlMs, tagsFlat, tagOffsets);
326
+ if (this.#hasChangeConsumers) {
327
+ for (let i = 0; i < n; i += 1)
328
+ this.#notify({ type: 'set', key: entries[i].key });
329
+ }
330
+ // One sweep can span the whole batch — drain once, after every write landed.
331
+ if (this.#dropTracking)
332
+ this.#drainDrops();
188
333
  }
189
334
  /**
190
335
  * Marks `key` as recently used for eviction and optionally renews its TTL — the stored
@@ -209,6 +354,23 @@ export class BlazeCache {
209
354
  this.#notify({ type: 'delete', key });
210
355
  return removed;
211
356
  }
357
+ /**
358
+ * Batch delete: removes every key, returning `true` for each key that was present.
359
+ * Crosses the wasm boundary once instead of once per key.
360
+ */
361
+ deleteMany(keys) {
362
+ const removed = this.#wasm.deleteMany(keys);
363
+ const result = new Array(removed.length);
364
+ for (let i = 0; i < removed.length; i += 1)
365
+ result[i] = removed[i] === 1;
366
+ if (this.#hasChangeConsumers) {
367
+ for (let i = 0; i < removed.length; i += 1) {
368
+ if (result[i])
369
+ this.#notify({ type: 'delete', key: keys[i] });
370
+ }
371
+ }
372
+ return result;
373
+ }
212
374
  /** Removes every entry carrying any of `tags`, returning the removed keys. */
213
375
  invalidateTags(...tags) {
214
376
  if (tags.length === 0)
@@ -237,20 +399,25 @@ export class BlazeCache {
237
399
  resetStats() {
238
400
  this.#wasm.resetStats();
239
401
  }
240
- // ------------------------------------------------------------- observers
241
- /**
242
- * Subscribes to mutations. Returns the unsubscribe function.
243
- *
244
- * Persistence uses this internally, so listeners fire for every change regardless of
245
- * whether storage is enabled. A listener that throws is isolated: the failure is logged
246
- * with `console.error`, the mutation it was told about stands, and the remaining listeners
247
- * are still notified.
248
- */
249
- on(listener) {
250
- this.#listeners.add(listener);
251
- return () => {
252
- this.#listeners.delete(listener);
253
- };
402
+ on(typeOrListener, maybeListener) {
403
+ // The bus's change hook keeps `#dropTracking` in step with the subscriber set, so
404
+ // neither registration nor the returned unsubscribe has to remember the wasm call.
405
+ return maybeListener === undefined
406
+ ? this.#events.on(typeOrListener)
407
+ : this.#events.on(typeOrListener, maybeListener);
408
+ }
409
+ once(typeOrListener, maybeListener) {
410
+ return maybeListener === undefined
411
+ ? this.#events.once(typeOrListener)
412
+ : this.#events.once(typeOrListener, maybeListener);
413
+ }
414
+ off(typeOrListener, listener) {
415
+ if (typeOrListener === undefined)
416
+ this.#events.off();
417
+ else if (listener === undefined)
418
+ this.#events.off(typeOrListener);
419
+ else
420
+ this.#events.off(typeOrListener, listener);
254
421
  }
255
422
  /**
256
423
  * Writes pending changes to storage immediately.
@@ -296,7 +463,8 @@ export class BlazeCache {
296
463
  }
297
464
  for (const unbind of this.#unbind.splice(0))
298
465
  unbind();
299
- this.#listeners.clear();
466
+ this.#events.clear(); // the change hook skips the wasm sync (`#disposed` is already true)
467
+ this.#dropTracking = false;
300
468
  try {
301
469
  await this.#persist?.close?.();
302
470
  }
@@ -382,7 +550,8 @@ export class BlazeCache {
382
550
  const remaining = record.ttlMs === null ? null : record.ttlMs - (now - record.storedAt);
383
551
  if (remaining !== null && remaining <= 0)
384
552
  continue;
385
- // Direct wasm call: hydration is not a user write, so it emits no change event.
553
+ // Direct wasm call: hydration is not a user write, so it emits no event — nor any
554
+ // change for persistence (the adapter it came from is already up to date).
386
555
  this.#wasm.set(record.key, record.value, remaining, record.tags);
387
556
  }
388
557
  catch (error) {
@@ -458,9 +627,11 @@ export class BlazeCache {
458
627
  await persist.save(records);
459
628
  }
460
629
  // Reconcile the rows the wasm core dropped on its own. A capacity eviction inside
461
- // `set` and a lapsed TTL never emit a change event — nothing queued a delete for them
462
- // — so without this diff their rows would outlive every flush, be re-hydrated at the
463
- // next startup, and eat quota until a `QuotaExceededError` kills persistence outright.
630
+ // `set` and a lapsed TTL never queue a delete for persistence — the `evict`/`expire`
631
+ // events they emit reach subscribers only, and `prune`/`remove` callers may not have
632
+ // persisted the key either — so without this diff their rows would outlive every
633
+ // flush, be re-hydrated at the next startup, and eat quota until a
634
+ // `QuotaExceededError` kills persistence outright.
464
635
  // Any key storage still holds that the wasm core no longer lists is stale. Skipped
465
636
  // after `clear()` (storage was just emptied) and for adapters without `keys()`.
466
637
  if (!clearAll && typeof persist.keys === 'function') {
@@ -503,7 +674,7 @@ export class BlazeCache {
503
674
  }
504
675
  /**
505
676
  * `true` when a change event would actually reach someone — persistence bookkeeping or at
506
- * least one listener.
677
+ * least one event listener (wildcard or typed).
507
678
  *
508
679
  * Lets the mutation paths skip building a {@link CacheChange} object altogether when
509
680
  * nothing consumes it (memory-only cache, no subscribers). Equivalent to the conditions
@@ -511,7 +682,7 @@ export class BlazeCache {
511
682
  * the `!#disposed` check inside `#notify` cannot change the outcome here.
512
683
  */
513
684
  get #hasChangeConsumers() {
514
- return this.#listeners.size > 0 || this.#persist !== null;
685
+ return this.#events.size > 0 || this.#persist !== null;
515
686
  }
516
687
  #notify(change) {
517
688
  if (this.#persist && !this.#disposed) {
@@ -540,17 +711,47 @@ export class BlazeCache {
540
711
  }
541
712
  this.#scheduleFlush();
542
713
  }
543
- for (const listener of this.#listeners) {
544
- try {
545
- listener(change);
546
- }
547
- catch (error) {
548
- // The mutation already happened and the bookkeeping above already ran — a bad
549
- // subscriber must not abort its siblings or surface out of a successful `set`.
550
- console.error('[blaze-cache] change listener failed — the remaining listeners still run.', error);
551
- }
714
+ // Wildcard and typed listeners alike — the bus isolates a throwing listener from its
715
+ // siblings (see `events.ts`).
716
+ this.#events.emit(change);
717
+ }
718
+ /**
719
+ * Emits `evict`/`expire` for every entry the Rust core reclaimed during the operation
720
+ * that just ran — a capacity sweep inside `set`, or lazy TTL reclamation inside `get`.
721
+ *
722
+ * Callers reach this only while `#dropTracking` is on, and the core only *records* drops
723
+ * while tracking is on, so the frequent result is an empty array: one wasm crossing that
724
+ * emits nothing. The `value` handed to listeners is the dropped entry's live reference.
725
+ */
726
+ #drainDrops() {
727
+ const drops = this.#wasm.drainDrops();
728
+ for (let i = 0; i < drops.length; i += 1) {
729
+ const { key, value, reason } = drops[i];
730
+ if (reason === 'evict')
731
+ this.#events.emit('evict', { type: 'evict', key, value });
732
+ else
733
+ this.#events.emit('expire', { type: 'expire', key, value });
552
734
  }
553
735
  }
736
+ /**
737
+ * Mirrors the subscriber set onto the wasm core: while *any* listener cares about
738
+ * `evict`/`expire` — a typed one or any wildcard — the Rust core's opt-in drop log
739
+ * collects the entries the cache drops by itself; when the last such listener goes away
740
+ * the log is switched off (which also discards anything not yet drained).
741
+ *
742
+ * Driven by the event bus's change hook, so it runs after every `on`/`once`/`off` —
743
+ * including the removal a fired `once` performs — and no call site has to remember it.
744
+ * Skipped after `dispose`: the wasm instance is already gone.
745
+ */
746
+ #syncDropTracking() {
747
+ if (this.#disposed)
748
+ return;
749
+ const wanted = this.#events.wantsDrops;
750
+ if (wanted === this.#dropTracking)
751
+ return;
752
+ this.#dropTracking = wanted;
753
+ this.#wasm.setDropTracking(wanted);
754
+ }
554
755
  }
555
756
  /** Shorthand for {@link BlazeCache.create}. */
556
757
  export function createCache(options) {