UNPKG

@atproto/repo

Version:

atproto repo and MST implementation

117 lines 3.49 kB
import { TID } from '@atproto/common-web'; import * as crypto from '@atproto/crypto'; import * as cbor from '@atproto/lex-cbor'; import { isPlainObject } from '@atproto/lex-data'; import { WriteOpAction, } from './types.js'; export const diffToWriteDescripts = (diff) => { return Promise.all([ ...diff.addList().map(async (add) => { const { collection, rkey } = parseDataKey(add.key); return { action: WriteOpAction.Create, collection, rkey, cid: add.cid, }; }), ...diff.updateList().map(async (upd) => { const { collection, rkey } = parseDataKey(upd.key); return { action: WriteOpAction.Update, collection, rkey, cid: upd.cid, prev: upd.prev, }; }), ...diff.deleteList().map((del) => { const { collection, rkey } = parseDataKey(del.key); return { action: WriteOpAction.Delete, collection, rkey, cid: del.cid, }; }), ]); }; export const ensureCreates = (descripts) => { const creates = []; for (const descript of descripts) { if (descript.action !== WriteOpAction.Create) { throw new Error(`Unexpected action: ${descript.action}`); } else { creates.push(descript); } } return creates; }; export const parseDataKey = (key) => { const { length, 0: collection, 1: rkey } = key.split('/'); if (length !== 2) throw new Error(`Invalid record key: ${key}`); return { collection, rkey }; }; export const formatDataKey = (collection, rkey) => { return collection + '/' + rkey; }; export const metaEqual = (a, b) => { return a.did === b.did && a.version === b.version; }; export const signCommit = async (unsigned, keypair) => { const encoded = cbor.encode(unsigned); const sig = await keypair.sign(encoded); return { ...unsigned, sig, }; }; export const verifyCommitSig = async (commit, didKey) => { const { sig, ...rest } = commit; const encoded = cbor.encode(rest); return crypto.verifySignature(didKey, encoded, sig); }; export const cborToLex = cbor.decode; export const cborToLexRecord = (val) => { const parsed = cborToLex(val); if (!isPlainObject(parsed)) { throw new Error('lexicon records be a json object'); } return parsed; }; export const cidForRecord = cbor.cidForLex; export const ensureV3Commit = (commit) => { if (commit.version === 3) { return commit; } else { return { ...commit, version: 3, rev: commit.rev ?? TID.nextStr(), }; } }; export async function concatBytesAsync(iterable) { const chunks = []; for await (const chunk of iterable) chunks.push(chunk); return concatBytes(chunks); } /** * This is the same as {@link Buffer.concat}, without the `totalLength` argument. */ export function concatBytes(chunks) { let totalLength = 0; for (const chunk of chunks) totalLength += chunk.byteLength; const result = new Uint8Array(totalLength); let offset = 0; for (const chunk of chunks) { result.set(chunk, offset); offset += chunk.byteLength; } return result; } //# sourceMappingURL=util.js.map