OverviewFilesCommitsIssuesDocsReleasesPeers

pear-git-v3 / lib / services / repo-event-log-messages.js

56 lines · javascript ref:
/**
 * Wire codec for the repo-event-log Hypercore entries.
 *
 * Single entry type, compact-encoded:
 *
 *   { op: uint8,              // 0=created, 1=updated, 2=deleted (reserved)
 *     name: string,           // repo name (short ASCII)
 *     head: string,           // HEAD commit hex, '' if empty
 *     ts: uint,               // unix ms
 *     issueBootstrapKey: buffer(32) | null }
 *
 * The trailing `issueBootstrapKey` uses a 1-byte presence prefix (0|1)
 * followed by the raw 32-byte key when present — same pattern as
 * hyper-overlay/lib/messages.js uses for nullable buffer fields.
 */

import c from 'compact-encoding'

export const entry = {
  preencode (state, m) {
    c.uint8.preencode(state, m.op | 0)
    c.string.preencode(state, m.name || '')
    c.string.preencode(state, m.head || '')
    c.uint.preencode(state, m.ts || 0)
    c.uint8.preencode(state, m.issueBootstrapKey ? 1 : 0)
    if (m.issueBootstrapKey) state.end += 32
  },
  encode (state, m) {
    c.uint8.encode(state, m.op | 0)
    c.string.encode(state, m.name || '')
    c.string.encode(state, m.head || '')
    c.uint.encode(state, m.ts || 0)
    c.uint8.encode(state, m.issueBootstrapKey ? 1 : 0)
    if (m.issueBootstrapKey) {
      const buf = typeof m.issueBootstrapKey === 'string'
        ? Buffer.from(m.issueBootstrapKey, 'hex')
        : m.issueBootstrapKey
      buf.copy(state.buffer, state.start, 0, 32)
      state.start += 32
    }
  },
  decode (state) {
    const op = c.uint8.decode(state)
    const name = c.string.decode(state)
    const head = c.string.decode(state)
    const ts = c.uint.decode(state)
    const hasKey = c.uint8.decode(state)
    let issueBootstrapKey = null
    if (hasKey) {
      issueBootstrapKey = Buffer.from(state.buffer.subarray(state.start, state.start + 32))
      state.start += 32
    }
    return { op, name, head, ts, issueBootstrapKey }
  }
}