From 6e14fcea6bf08187c817a3404cf82b9093a41146 Mon Sep 17 00:00:00 2001 From: Gregor MacLennan Date: Wed, 15 Jul 2026 23:01:21 +0100 Subject: [PATCH] emit clear when a range of blocks is cleared from local storage append and truncate emit session events, but core.clear() emits nothing, so there is no way to observe blocks being removed from local storage (e.g. to re-announce state derived from the local bitfield) without wrapping core.clear. Emit a clear event with the cleared range after the state has been flushed, mirroring the truncate event. --- README.md | 4 ++++ lib/session-state.js | 4 ++++ test/clear.js | 13 +++++++++++++ 3 files changed, 21 insertions(+) diff --git a/README.md b/README.md index f39f10632..46ce36d97 100644 --- a/README.md +++ b/README.md @@ -755,6 +755,10 @@ Emitted when the core has been appended to (i.e. has a new length / byteLength), Emitted when the core has been truncated, either locally or remotely. +#### `core.on('clear', start, end)` + +Emitted when a range of blocks has been cleared from local storage with `core.clear()`. + #### `core.on('peer-add')` Emitted when a new connection has been established with a peer. diff --git a/lib/session-state.js b/lib/session-state.js index f97263bfc..caad77f09 100644 --- a/lib/session-state.js +++ b/lib/session-state.js @@ -605,6 +605,10 @@ class SessionState { this.core.replicator.onhave(start, length, true) if (this.core.hintsChanged) await this.core.flushHints() + + for (let i = this.sessions.length - 1; i >= 0; i--) { + this.sessions[i].emit('clear', start, end) + } } } finally { this._unlock() diff --git a/test/clear.js b/test/clear.js index b715219b7..84b272170 100644 --- a/test/clear.js +++ b/test/clear.js @@ -22,6 +22,19 @@ test('clear', async function (t) { await a.close() }) +test('clear emits a clear event with the cleared range', async function (t) { + const a = await create(t) + await a.append(['a', 'b', 'c']) + + const cleared = new Promise((resolve) => a.once('clear', (start, end) => resolve({ start, end }))) + + await a.clear(1, 3) + + t.alike(await cleared, { start: 1, end: 3 }, 'clear event fired with the cleared range') + + await a.close() +}) + test('clear + replication', async function (t) { const a = await create(t) const b = await create(t, a.key)