// One Durable Object per repository. It holds every Git object, the branches, the commit records // and the votes in its own SQLite database, so a push, a vote and a removal never race each other. import { DurableObject } from 'cloudflare:workers'; import { ZERO, FLUSH, te, td, pkt, concat, readPkts, sideband, objectId, parseTree, writeTree, parseCommit, personName, readPack, packHeader, packObjHeader, deflate, inflate, TYPE_NUM, NUM_TYPE, type ObjType, type RawObj, type TreeEntry, } from './git/core'; import { Sha1 } from './git/sha1'; import { checkBlob } from './checks'; const PART = 1_000_000; // bytes per stored row (SQLite rows cap at 2 MB) export const VOTES_TO_DECIDE = 3; const BRANCH_RE = /^(?!\/|.*\/\/|.*\.\.|.*\.lock$|.*[\s~^:?*[\\\x00-\x1f\x7f]|.*@\{|\.|.*\/\.)[A-Za-z0-9._\/-]{1,100}(? 0; } zOf(sha: string): { type: number; size: number; z: Uint8Array } | null { const r = this.sql.exec('SELECT type, size, parts, z FROM objects WHERE sha = ?', sha).toArray()[0]; if (!r) return null; let z: Uint8Array; if ((r.parts as number) === 0) z = new Uint8Array(r.z as ArrayBuffer); else z = concat(this.sql.exec('SELECT z FROM object_parts WHERE sha = ? ORDER BY idx', sha).toArray().map((p) => new Uint8Array(p.z as ArrayBuffer))); return { type: r.type as number, size: r.size as number, z }; } get(sha: string, overlay?: Map): RawObj | null { const o = overlay?.get(sha); if (o) return o; const z = this.zOf(sha); if (!z) return null; return { type: NUM_TYPE[z.type], data: inflate(z.z), sha }; } put(o: RawObj) { if (this.has(o.sha)) return; const z = deflate(o.data); if (z.length <= PART) { this.sql.exec('INSERT INTO objects (sha, type, size, parts, z) VALUES (?, ?, ?, 0, ?)', o.sha, TYPE_NUM[o.type], o.data.length, z); return; } const n = Math.ceil(z.length / PART); for (let i = 0; i < n; i++) this.sql.exec('INSERT INTO object_parts (sha, idx, z) VALUES (?, ?, ?)', o.sha, i, z.subarray(i * PART, (i + 1) * PART)); this.sql.exec('INSERT INTO objects (sha, type, size, parts, z) VALUES (?, ?, ?, ?, NULL)', o.sha, TYPE_NUM[o.type], o.data.length, n); } make(type: ObjType, data: Uint8Array): string { const sha = objectId(type, data); this.put({ type, data, sha }); return sha; } refs(): Map { return new Map(this.sql.exec('SELECT name, sha FROM refs ORDER BY name').toArray().map((r) => [r.name as string, r.sha as string])); } setRef(branch: string, sha: string) { this.sql.exec('INSERT INTO refs (name, sha) VALUES (?, ?) ON CONFLICT (name) DO UPDATE SET sha = excluded.sha', 'refs/heads/' + branch, sha); this.sql.exec('UPDATE branches SET last_sha = ? WHERE name = ?', sha, branch); } commit(sha: string, overlay?: Map) { const o = this.get(sha, overlay); if (!o || o.type !== 'commit') throw new Error('missing commit ' + sha); return parseCommit(o.data); } tree(sha: string, overlay?: Map): TreeEntry[] { const o = this.get(sha, overlay); if (!o || o.type !== 'tree') throw new Error('missing tree ' + sha); return parseTree(o.data); } /** Every commit reachable from the given tips. */ reachable(tips: string[], overlay?: Map, stop?: Set, limit = 100000): Set { const seen = new Set(); const q = tips.filter((t) => t && t !== ZERO); while (q.length && seen.size < limit) { const s = q.pop()!; if (seen.has(s) || stop?.has(s)) continue; seen.add(s); for (const p of this.commit(s, overlay).parents) if (!seen.has(p)) q.push(p); } return seen; } /** path -> {mode, sha} for every file under a tree (submodules kept as entries). */ flatten(treeSha: string | null, overlay?: Map, prefix = '', out = new Map()) { if (!treeSha) return out; for (const e of this.tree(treeSha, overlay)) { if (e.mode === '40000') this.flatten(e.sha, overlay, prefix + e.name + '/', out); else out.set(prefix + e.name, { mode: e.mode, sha: e.sha }); } return out; } buildTree(flat: Map): string { type Dir = { files: TreeEntry[]; dirs: Map }; const root: Dir = { files: [], dirs: new Map() }; for (const [path, v] of flat) { const parts = path.split('/'); let d = root; for (const p of parts.slice(0, -1)) { if (!d.dirs.has(p)) d.dirs.set(p, { files: [], dirs: new Map() }); d = d.dirs.get(p)!; } d.files.push({ mode: v.mode, name: parts[parts.length - 1], sha: v.sha }); } const write = (d: Dir): string => this.make('tree', writeTree([...d.files, ...[...d.dirs].map(([name, sub]) => ({ mode: '40000', name, sha: write(sub) }))])); return write(root); } changes(sha: string, overlay?: Map) { const c = this.commit(sha, overlay); const after = this.flatten(c.tree, overlay); const before = c.parents[0] ? this.flatten(this.commit(c.parents[0], overlay).tree, overlay) : new Map(); const out: { path: string; status: 'added' | 'changed' | 'deleted'; before?: { mode: string; sha: string }; after?: { mode: string; sha: string } }[] = []; for (const [p, v] of after) { const b = before.get(p); if (!b) out.push({ path: p, status: 'added', after: v }); else if (b.sha !== v.sha || b.mode !== v.mode) out.push({ path: p, status: 'changed', before: b, after: v }); } for (const [p, v] of before) if (!after.has(p)) out.push({ path: p, status: 'deleted', before: v }); return { commit: c, files: out.sort((a, b) => (a.path < b.path ? -1 : 1)) }; } // ---------------- Git smart HTTP ---------------- async fetch(req: Request): Promise { const url = new URL(req.url); const rn = req.headers.get('x-repo'); if (rn && !this.meta('name')) this.setMeta('name', rn); try { if (url.pathname === '/info/refs') return this.advertise(url.searchParams.get('service') || ''); if (url.pathname === '/git-upload-pack') return this.uploadPack(new Uint8Array(await req.arrayBuffer())); if (url.pathname === '/git-receive-pack') { const pusher = JSON.parse(req.headers.get('x-pusher') || 'null') as Pusher | null; if (!pusher) return new Response('sign in to push', { status: 401 }); return this.receivePack(new Uint8Array(await req.arrayBuffer()), pusher); } } catch (e) { return new Response('error: ' + (e as Error).message, { status: 500 }); } return new Response('not found', { status: 404 }); } advertise(service: string): Response { if (service !== 'git-upload-pack' && service !== 'git-receive-pack') return new Response('dumb HTTP is not supported; use git 1.7 or newer', { status: 403 }); const refs = this.refs(); const def = this.defaultBranch(); const caps = service === 'git-upload-pack' ? `side-band-64k no-progress symref=HEAD:refs/heads/${def} agent=branchwell/1` : 'report-status side-band-64k quiet ofs-delta agent=branchwell/1'; const lines: Uint8Array[] = [pkt(`# service=${service}\n`), FLUSH]; const list: [string, string][] = []; const head = refs.get('refs/heads/' + def); if (head && service === 'git-upload-pack') list.push(['HEAD', head]); for (const [n, s] of refs) list.push([n, s]); if (!list.length) lines.push(pkt(`${ZERO} capabilities^{}\0${caps}\n`)); list.forEach(([n, s], i) => lines.push(pkt(i === 0 ? `${s} ${n}\0${caps}\n` : `${s} ${n}\n`))); lines.push(FLUSH); return new Response(concat(lines), { headers: { 'content-type': `application/x-${service}-advertisement`, 'cache-control': 'no-cache' } }); } uploadPack(body: Uint8Array): Response { const { lines } = readPkts(body); const wants: string[] = []; const haves: string[] = []; let done = false; let caps = ''; for (const l of lines) { if (!l) continue; const s = td.decode(l).replace(/\n$/, ''); if (s.startsWith('want ')) { wants.push(s.slice(5, 45)); if (!caps) caps = s.slice(46); } else if (s.startsWith('have ')) haves.push(s.slice(5, 45)); else if (s === 'done') done = true; } const common = haves.filter((h) => this.has(h)); const ack = pkt(common.length ? `ACK ${common[0]}\n` : 'NAK\n'); const type = 'application/x-git-upload-pack-result'; if (!done && !wants.length) return new Response(ack, { headers: { 'content-type': type } }); if (!done) return new Response(ack, { headers: { 'content-type': type } }); for (const w of wants) if (!this.has(w)) return new Response(concat([pkt(`ERR upload-pack: not our ref ${w}\n`)]), { headers: { 'content-type': type } }); // Objects the client already has. const have = new Set(); const commitsHave = this.reachable(common); const addTree = (t: string, set: Set) => { if (set.has(t)) return; set.add(t); for (const e of this.tree(t)) { if (e.mode === '40000') addTree(e.sha, set); else if (e.mode !== '160000') set.add(e.sha); } }; for (const c of commitsHave) { have.add(c); addTree(this.commit(c).tree, have); } // Objects to send, in commit, tree, blob order. const send: string[] = []; const seen = new Set(); const q = [...wants]; while (q.length) { const s = q.pop()!; if (seen.has(s) || have.has(s)) continue; seen.add(s); const z = this.sql.exec('SELECT type FROM objects WHERE sha = ?', s).toArray()[0]; if (!z) continue; send.push(s); if (z.type === 1) { const c = this.commit(s); q.push(...c.parents); this.collectTree(c.tree, have, seen, send); } else if (z.type === 4) { const t = td.decode(this.get(s)!.data).match(/^object ([0-9a-f]{40})/m); if (t) q.push(t[1]); } } const band = /\bside-band-64k\b/.test(caps); const { readable, writable } = new TransformStream(); const w = writable.getWriter(); const self = this; (async () => { const out = async (d: Uint8Array) => { if (band) { for (const p of sideband(1, d)) await w.write(p); } else await w.write(d); }; try { await w.write(ack); const sha = new Sha1(); const emit = async (d: Uint8Array) => { sha.update(d); await out(d); }; await emit(packHeader(send.length)); let batch: Uint8Array[] = []; let n = 0; for (const s of send) { const z = self.zOf(s)!; batch.push(packObjHeader(z.type, z.size), z.z); n += z.z.length; if (n > 256 * 1024) { await emit(concat(batch)); batch = []; n = 0; } } if (batch.length) await emit(concat(batch)); await out(sha.digest()); if (band) await w.write(FLUSH); await w.close(); } catch (e) { await w.abort(e); } })(); return new Response(readable, { headers: { 'content-type': type, 'cache-control': 'no-cache' } }); } collectTree(t: string, have: Set, seen: Set, send: string[]) { if (seen.has(t) || have.has(t)) return; seen.add(t); send.push(t); for (const e of this.tree(t)) { if (e.mode === '40000') this.collectTree(e.sha, have, seen, send); else if (e.mode !== '160000' && !seen.has(e.sha) && !have.has(e.sha)) { seen.add(e.sha); send.push(e.sha); } } } async receivePack(body: Uint8Array, pusher: Pusher): Promise { const { lines, end } = readPkts(body, 0, true); const cmds: { old: string; neu: string; ref: string }[] = []; let caps = ''; for (const l of lines) { if (!l) break; let s = td.decode(l).replace(/\n$/, ''); const nul = s.indexOf('\0'); if (nul >= 0) { caps = s.slice(nul + 1); s = s.slice(0, nul); } const [old, neu, ref] = s.split(' '); cmds.push({ old, neu, ref }); } const band = /\bside-band-64k\b/.test(caps); const progress: string[] = []; const results = new Map(); // ref -> '' (ok) or reason let unpack = 'ok'; const overlay = new Map(); try { if (end < body.length && cmds.some((c) => c.neu !== ZERO)) { const objs = await readPack(body.subarray(end), async (sha) => this.get(sha)); for (const o of objs) overlay.set(o.sha, o); } } catch (e) { unpack = (e as Error).message; } const refsNow = this.refs(); const known = unpack === 'ok' ? this.reachable([...refsNow.values()]) : new Set(); const newCommits = new Map(); // ref -> new commit shas (oldest first) if (unpack === 'ok') for (const c of cmds) { const branch = c.ref.replace(/^refs\/heads\//, ''); if (!c.ref.startsWith('refs/heads/') || !BRANCH_RE.test(branch)) { results.set(c.ref, 'only branches (refs/heads/...) with plain names can be pushed'); continue; } if (c.neu === ZERO) { results.set(c.ref, 'branches are removed by votes, not by push'); continue; } const cur = refsNow.get(c.ref) || ZERO; if (cur !== c.old) { results.set(c.ref, 'fetch first: the branch moved. Run git pull, then push again'); continue; } const removed = this.sql.exec("SELECT 1 FROM branches WHERE name = ? AND status = 'removed'", branch).toArray().length; if (removed && cur === ZERO) { results.set(c.ref, 'this branch name was voted out. Push under a new name'); continue; } let mine: Set; try { mine = this.reachable([c.neu], overlay, known); } catch (e) { results.set(c.ref, 'missing objects: ' + (e as Error).message); continue; } if (cur !== ZERO && !mine.has(cur) && !this.reachable([c.neu], overlay).has(cur)) { results.set(c.ref, 'not a fast-forward. Run git pull, then push again (history is never rewritten here)'); continue; } if (mine.size > 2000) { results.set(c.ref, 'too many new commits in one push (limit 2000)'); continue; } // Checks ("tests"): every changed file in every new commit. const problems: string[] = []; const checked = new Set(); for (const sha of mine) { for (const f of this.changes(sha, overlay).files) { if (!f.after || f.after.mode === '160000' || checked.has(f.after.sha + f.path)) continue; checked.add(f.after.sha + f.path); const blob = this.get(f.after.sha, overlay); const why = blob ? checkBlob(f.path, blob.data) : 'missing file data'; if (why) problems.push(`${f.path}: ${why}`); if (problems.length >= 5) break; } if (problems.length >= 5) break; } if (problems.length) { results.set(c.ref, 'checks failed: ' + problems.join('; ')); continue; } const order = [...mine].map((s) => ({ s, t: this.commit(s, overlay).time })).sort((a, b) => a.t - b.t).map((x) => x.s); newCommits.set(c.ref, order); results.set(c.ref, ''); } const okRefs = cmds.filter((c) => results.get(c.ref) === ''); if (okRefs.length) { for (const o of overlay.values()) this.put(o); const now = Date.now(); for (const c of okRefs) { const branch = c.ref.replace(/^refs\/heads\//, ''); const first = !this.refs().size; if (first) this.setMeta('default_branch', branch); const isDefault = branch === this.defaultBranch(); this.sql.exec(`INSERT INTO branches (name, status, created_by, created_at) VALUES (?, ?, ?, ?) ON CONFLICT (name) DO NOTHING`, branch, isDefault ? 'kept' : 'new', pusher.handle, now); this.setRef(branch, c.neu); const list = newCommits.get(c.ref) || []; for (const s of list) { const cm = this.commit(s); this.sql.exec(`INSERT INTO commits (sha, branch, status, pusher, pushed_at, subject, author) VALUES (?, ?, 'new', ?, ?, ?, ?) ON CONFLICT (sha) DO NOTHING`, s, branch, pusher.handle, now, cm.message.split('\n')[0].slice(0, 200), personName(cm.author)); } const repo = this.meta('name') || ''; progress.push(`Branchwell: ${branch} updated${list.length ? ` with ${list.length} new commit${list.length === 1 ? '' : 's'}` : ''}. Vote at https://branchwell.ai/${repo}/commits/${encodeURIComponent(branch)}\n`); } this.setMeta('updated_at', String(now)); } for (const c of cmds) { const r = results.get(c.ref); if (r) progress.push(`Branchwell: ${c.ref.replace('refs/heads/', '')} not updated: ${r}\n`); } const report = [pkt(`unpack ${unpack === 'ok' ? 'ok' : unpack.replace(/\n/g, ' ')}\n`)]; for (const c of cmds) { const r = results.get(c.ref); report.push(pkt(r === '' ? `ok ${c.ref}\n` : `ng ${c.ref} ${(r || unpack).replace(/\n/g, ' ')}\n`)); } report.push(FLUSH); const outParts: Uint8Array[] = []; if (band) { for (const p of progress) outParts.push(...sideband(2, te.encode(p))); outParts.push(...sideband(1, concat(report))); outParts.push(FLUSH); } else outParts.push(...report); return new Response(concat(outParts), { headers: { 'content-type': 'application/x-git-receive-pack-result', 'cache-control': 'no-cache' } }); } // ---------------- votes ---------------- async vote(kind: 'commit' | 'branch', target: string, voter: Voter, value: number): Promise<{ ok: boolean; message: string; status?: string; up?: number; down?: number }> { if (!voter.canVote) return { ok: false, message: 'New accounts can vote 24 hours after they are made. This keeps votes fair.' }; value = value > 0 ? 1 : value < 0 ? -1 : 0; const table = kind === 'commit' ? 'commits' : 'branches'; const key = kind === 'commit' ? 'sha' : 'name'; const row = this.sql.exec(`SELECT * FROM ${table} WHERE ${key} = ?`, target).toArray()[0]; if (!row) return { ok: false, message: `That ${kind} isn't open for votes.` }; if (row.status === 'removed') return { ok: false, message: `That ${kind} was already removed by votes.` }; if (row.status === 'system') return { ok: false, message: 'Removals made by votes are not voted on.' }; if (row.status === 'kept') return { ok: false, message: `That ${kind} already got ${VOTES_TO_DECIDE} votes up and stays for good.`, status: 'kept' }; const owner = kind === 'commit' ? row.pusher : row.created_by; if (owner === voter.handle && value > 0) return { ok: false, message: 'You can vote down your own work, but not up. Others decide what stays.' }; if (value === 0) this.sql.exec('DELETE FROM votes WHERE kind = ? AND target = ? AND account = ?', kind, target, voter.id); else this.sql.exec('INSERT INTO votes (kind, target, account, handle, value, at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (kind, target, account) DO UPDATE SET value = excluded.value, at = excluded.at', kind, target, voter.id, voter.handle, value, Date.now()); const t = this.sql.exec('SELECT SUM(value > 0) AS up, SUM(value < 0) AS down FROM votes WHERE kind = ? AND target = ?', kind, target).toArray()[0]; const up = (t.up as number) || 0, down = (t.down as number) || 0; this.sql.exec(`UPDATE ${table} SET up = ?, down = ? WHERE ${key} = ?`, up, down, target); if (down >= VOTES_TO_DECIDE) { const msg = kind === 'commit' ? this.removeCommit(target) : this.removeBranch(target); return { ok: true, message: msg, status: 'removed', up, down }; } if (up >= VOTES_TO_DECIDE) { this.sql.exec(`UPDATE ${table} SET status = 'kept' WHERE ${key} = ?`, target); return { ok: true, message: `${VOTES_TO_DECIDE} votes up: it stays for good.`, status: 'kept', up, down }; } return { ok: true, message: 'Vote counted.', status: row.status as string, up, down }; } removeBranch(name: string): string { if (name === this.defaultBranch()) { this.sql.exec("UPDATE branches SET status = 'kept' WHERE name = ?", name); return 'The main branch always stays.'; } this.sql.exec("UPDATE branches SET status = 'removed', removed_at = ? WHERE name = ?", Date.now(), name); this.sql.exec('DELETE FROM refs WHERE name = ?', 'refs/heads/' + name); return `${VOTES_TO_DECIDE} votes down: the branch ${name} was removed.`; } /** Takes a commit's changes back out of its branch with a new commit, file by file. History is never rewritten. */ removeCommit(sha: string): string { const row = this.sql.exec('SELECT * FROM commits WHERE sha = ?', sha).toArray()[0]; const branch = row.branch as string; const tip = this.refs().get('refs/heads/' + branch); if (!tip) { this.sql.exec("UPDATE commits SET status = 'removed', note = ? WHERE sha = ?", 'branch already removed', sha); return 'Removed.'; } const { commit: c, files } = this.changes(sha); const cur = this.flatten(this.commit(tip).tree); let undone = 0, skipped = 0; for (const f of files) { const now = cur.get(f.path); const same = (a?: { mode: string; sha: string }, b?: { mode: string; sha: string }) => (!a && !b) || (!!a && !!b && a.sha === b.sha && a.mode === b.mode); if (!same(now, f.after)) { skipped++; continue; } // changed again later: leave the newer work alone if (f.before) cur.set(f.path, f.before); else cur.delete(f.path); undone++; } let note = `${undone} file${undone === 1 ? '' : 's'} restored`; if (skipped) note += `, ${skipped} left alone because later commits changed them`; if (undone) { const tree = this.buildTree(cur); const ts = Math.floor(Date.now() / 1000); const who = `Branchwell votes ${ts} +0000`; const subject = c.message.split('\n')[0].slice(0, 120); const msg = `Remove "${subject}" (voted down)\n\n${VOTES_TO_DECIDE} people voted down commit ${sha.slice(0, 10)}, so its changes were taken back out.\n${note}.\n`; const neu = this.make('commit', te.encode(`tree ${tree}\nparent ${tip}\nauthor ${who}\ncommitter ${who}\n\n${msg}`)); this.setRef(branch, neu); this.sql.exec(`INSERT INTO commits (sha, branch, status, pusher, pushed_at, subject, author, note) VALUES (?, ?, 'system', 'branchwell', ?, ?, 'Branchwell votes', ?)`, neu, branch, Date.now(), `Remove "${subject}" (voted down)`, sha); } this.sql.exec("UPDATE commits SET status = 'removed', note = ? WHERE sha = ?", note, sha); return `${VOTES_TO_DECIDE} votes down: the commit was removed from ${branch} (${note}).`; } // ---------------- reads for the web pages ---------------- async init(name: string) { if (!this.meta('name')) { this.setMeta('name', name); this.setMeta('created_at', String(Date.now())); } return true; } resolve(ref: string): string | null { const refs = this.refs(); if (refs.has('refs/heads/' + ref)) return refs.get('refs/heads/' + ref)!; if (/^[0-9a-f]{40}$/.test(ref) && this.has(ref)) return ref; if (/^[0-9a-f]{7,39}$/.test(ref)) { const r = this.sql.exec("SELECT sha FROM objects WHERE sha LIKE ? || '%' AND type = 1 LIMIT 2", ref).toArray(); if (r.length === 1) return r[0].sha as string; } return null; } async overview() { const branches = this.sql.exec('SELECT name, status, up, down, created_by, created_at, removed_at, last_sha FROM branches ORDER BY (name = ?) DESC, created_at DESC', this.defaultBranch()).toArray(); const counts = this.sql.exec("SELECT COUNT(*) AS n, SUM(status = 'new') AS open, SUM(status = 'removed') AS removed FROM commits").toArray()[0]; return { name: this.meta('name'), defaultBranch: this.defaultBranch(), empty: this.refs().size === 0, branches, commits: counts, updatedAt: Number(this.meta('updated_at') || 0) }; } async listTree(ref: string, path: string) { const sha = this.resolve(ref); if (!sha) return null; const c = this.commit(sha); let t = c.tree; for (const part of path.split('/').filter(Boolean)) { const e = this.tree(t).find((x) => x.name === part); if (!e) return null; if (e.mode !== '40000') return { kind: 'blob' as const, commit: sha }; t = e.sha; } const entries = this.tree(t).map((e) => ({ name: e.name, dir: e.mode === '40000', sha: e.sha, size: e.mode === '40000' ? 0 : ((this.sql.exec('SELECT size FROM objects WHERE sha = ?', e.sha).toArray()[0]?.size as number) || 0) })) .sort((a, b) => (a.dir === b.dir ? a.name.localeCompare(b.name) : a.dir ? -1 : 1)); return { kind: 'tree' as const, commit: sha, entries, last: { sha, subject: c.message.split('\n')[0], author: personName(c.author), time: c.time } }; } async readBlob(ref: string, path: string): Promise<{ data: Uint8Array; sha: string; commit: string } | null> { const sha = this.resolve(ref); if (!sha) return null; let t = this.commit(sha).tree; const parts = path.split('/').filter(Boolean); for (let i = 0; i < parts.length; i++) { const e = this.tree(t).find((x) => x.name === parts[i]); if (!e) return null; if (i === parts.length - 1) { if (e.mode === '40000') return null; const o = this.get(e.sha); return o ? { data: o.data, sha: e.sha, commit: sha } : null; } if (e.mode !== '40000') return null; t = e.sha; } return null; } async log(ref: string, skip = 0, limit = 30) { const tip = this.resolve(ref); if (!tip) return null; const out: Record[] = []; const seen = new Set(); const heap: { sha: string; time: number }[] = [{ sha: tip, time: this.commit(tip).time }]; let i = 0; while (heap.length && out.length < limit) { heap.sort((a, b) => b.time - a.time); const { sha } = heap.shift()!; if (seen.has(sha)) continue; seen.add(sha); const c = this.commit(sha); for (const p of c.parents) if (!seen.has(p)) heap.push({ sha: p, time: this.commit(p).time }); if (i++ < skip) continue; const m = this.sql.exec('SELECT branch, status, up, down, pusher, pushed_at, note FROM commits WHERE sha = ?', sha).toArray()[0] || null; out.push({ sha, subject: c.message.split('\n')[0], author: personName(c.author), time: c.time, parents: c.parents, meta: m }); } return { tip, commits: out, more: heap.length > 0 }; } async commitInfo(ref: string) { const sha = this.resolve(ref); if (!sha) return null; const { commit: c, files } = this.changes(sha); const meta = this.sql.exec('SELECT branch, status, up, down, pusher, pushed_at, note FROM commits WHERE sha = ?', sha).toArray()[0] || null; const voters = this.sql.exec("SELECT handle, value FROM votes WHERE kind = 'commit' AND target = ? ORDER BY at", sha).toArray(); const diffs = files.slice(0, 50).map((f) => { const a = f.before ? this.get(f.before.sha) : null, b = f.after ? this.get(f.after.sha) : null; return { path: f.path, status: f.status, before: a && isText(a.data) && a.data.length < 200_000 ? td.decode(a.data) : a ? null : '', after: b && isText(b.data) && b.data.length < 200_000 ? td.decode(b.data) : b ? null : '' }; }); return { sha, commit: c, meta, voters, files: files.map((f) => ({ path: f.path, status: f.status })), diffs }; } async myVotes(account: string, kind: string, targets: string[]): Promise> { const out: Record = {}; for (const t of targets.slice(0, 200)) { const r = this.sql.exec('SELECT value FROM votes WHERE kind = ? AND target = ? AND account = ?', kind, t, account).toArray()[0]; if (r) out[t] = r.value as number; } return out; } async branchVotes(name: string) { return this.sql.exec("SELECT handle, value FROM votes WHERE kind = 'branch' AND target = ? ORDER BY at", name).toArray(); } } export function isText(d: Uint8Array): boolean { const n = Math.min(d.length, 8000); for (let i = 0; i < n; i++) if (d[i] === 0) return false; return true; }