feat(cli): pretty-print event JSON in the local store

Users actually look at <data-dir>/events-store/ files (cat / jq / git
diff), so the CLI now writes them with the InliningTagArrayPrettyPrinter
that quartz already had configured but never invoked. Each event is
indented with 2 spaces, but every tag array stays on a single line —
nice trade-off between human-readable and not-too-tall:

    {
      "id": "...",
      "pubkey": "...",
      "created_at": 1700000000,
      "kind": 1,
      "tags": [
        ["t","nostr"],
        ["e","abc...a"],
        ["alt","quick brown fox"]
      ],
      "content": "hi there",
      "sig": "..."
    }

Stored bytes are not the canonical NIP-01 form — but verification
re-canonicalises via EventHasher anyway, so format is purely a UX
choice. Compact stays the default for any caller that doesn't opt
in (Android keeps SQLite, generic FsEventStore embedders keep
compact).

- JacksonMapper.toJsonPretty(event): new entry point that uses
  writerWithDefaultPrettyPrinter() with the existing inlining printer.
- FsEventStore now takes an `eventToJson: (Event) -> String` callback,
  default = Event::toJson (compact). Used in insert.
- Context wires in JacksonMapper::toJsonPretty.

2 new tests in FsEventToJsonTest pin both formats (compact stays
single-line; pretty round-trips). 117 fs tests green.
This commit is contained in:
Claude
2026-04-25 03:56:39 +00:00
parent 37a4f89178
commit 99be0b2d16
4 changed files with 157 additions and 2 deletions
@@ -141,6 +141,29 @@ class JacksonMapper {
fun toJson(event: Event): String = EventManualSerializer.toJson(event.id, event.pubKey, event.createdAt, event.kind, event.tags, event.content, event.sig)
/**
* Pretty-printed event JSON for human inspection. Uses the
* [InliningTagArrayPrettyPrinter] already configured on the
* mapper so each tag array stays on its own line (no nested
* line-per-element noise) and the seven event fields get their
* own indented lines. Re-canonicalisation is the caller's
* problem — this output is not canonical NIP-01.
*/
fun toJsonPretty(event: Event): String =
mapper
.writerWithDefaultPrettyPrinter()
.writeValueAsString(
EventManualSerializer.assemble(
event.id,
event.pubKey,
event.createdAt,
event.kind,
event.tags,
event.content,
event.sig,
),
)
fun toJson(event: ArrayNode): String = mapper.writeValueAsString(event)
fun toJson(event: ObjectNode?): String = mapper.writeValueAsString(event)
@@ -67,6 +67,14 @@ open class FsEventStore(
* `SQLiteEventStore`'s relay arg semantics.
*/
private val relay: NormalizedRelayUrl? = null,
/**
* How to render an event to JSON before writing the canonical file.
* Default is the compact NIP-01 form ([Event.toJson]); CLIs that
* surface store files to humans pass a pretty-printer instead. The
* stored bytes are not re-used for signature checks anyway —
* verification re-canonicalises — so format is purely a UX choice.
*/
private val eventToJson: (Event) -> String = Event::toJson,
) : IEventStore {
private val layout = FsLayout(root)
private val hasher: TagNameValueHasher
@@ -126,7 +134,7 @@ open class FsEventStore(
Files.createDirectories(canonical.parent)
val tmp = Files.createTempFile(layout.staging, event.id, FsLayout.JSON_EXT)
try {
Files.writeString(tmp, event.toJson())
Files.writeString(tmp, eventToJson(event))
try {
Files.move(tmp, canonical, StandardCopyOption.ATOMIC_MOVE)
} catch (_: FileAlreadyExistsException) {
@@ -0,0 +1,116 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.quartz.nip01Core.store.fs
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.jackson.JacksonMapper
import com.vitorpamplona.quartz.nip01Core.relay.filters.Filter
import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync
import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent
import com.vitorpamplona.quartz.utils.Secp256k1Instance
import java.nio.file.Files
import java.nio.file.Path
import kotlin.io.path.exists
import kotlin.io.path.readText
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class FsEventToJsonTest {
private val signer = NostrSignerSync()
private lateinit var root: Path
@BeforeTest
fun setup() {
Secp256k1Instance
root = Files.createTempDirectory("fs-fmt-")
}
@AfterTest
fun tearDown() {
if (root.exists()) {
Files.walk(root).use { it.sorted(Comparator.reverseOrder()).forEach { p -> Files.deleteIfExists(p) } }
}
}
@Test
fun `default formatter writes compact JSON one line`() {
val store = FsEventStore(root)
try {
val n =
signer.sign<TextNoteEvent>(
TextNoteEvent.build("hello", createdAt = 100),
)
store.insert(n)
val canonical =
root
.resolve("events")
.resolve(n.id.substring(0, 2))
.resolve(n.id.substring(2, 4))
.resolve("${n.id}.json")
val raw = canonical.readText()
assertEquals(raw.trim(), raw, "compact form has no trailing whitespace")
assertTrue(!raw.contains('\n'), "compact form is single-line")
} finally {
store.close()
}
}
@Test
fun `pretty formatter writes multi-line indented JSON and round-trips`() {
val store =
FsEventStore(
root,
eventToJson = JacksonMapper::toJsonPretty,
)
try {
val n =
signer.sign<TextNoteEvent>(
TextNoteEvent.build("hello", createdAt = 100),
)
store.insert(n)
val canonical =
root
.resolve("events")
.resolve(n.id.substring(0, 2))
.resolve(n.id.substring(2, 4))
.resolve("${n.id}.json")
val raw = canonical.readText()
assertTrue(raw.contains('\n'), "pretty form is multi-line")
assertTrue(raw.contains("\"id\""), "field labels survive pretty print")
// Round-trip: parsing pretty output back must produce the same event.
val reparsed = Event.fromJson(raw)
assertEquals(n.id, reparsed.id)
assertEquals(n.content, reparsed.content)
assertEquals(n.sig, reparsed.sig)
// And the store can read it back through its own API.
val got = store.query<TextNoteEvent>(Filter(ids = listOf(n.id)))
assertEquals(1, got.size)
assertEquals(n.id, got[0].id)
} finally {
store.close()
}
}
}