@fangorn-network/sdk 0.1.0-dev

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/LICENSE.md +20 -0
  2. package/README.md +80 -0
  3. package/lib/cli/cli.d.ts +2 -0
  4. package/lib/cli/cli.js +571 -0
  5. package/lib/cli/index.d.ts +10 -0
  6. package/lib/cli/index.js +18 -0
  7. package/lib/cli/sell.d.ts +28 -0
  8. package/lib/cli/sell.js +95 -0
  9. package/lib/cli/stage.d.ts +19 -0
  10. package/lib/cli/stage.js +94 -0
  11. package/lib/config.d.ts +697 -0
  12. package/lib/config.js +45 -0
  13. package/lib/contracts/data-registry/abi.d.ts +442 -0
  14. package/lib/contracts/data-registry/abi.js +508 -0
  15. package/lib/contracts/data-registry/index.d.ts +131 -0
  16. package/lib/contracts/data-registry/index.js +183 -0
  17. package/lib/contracts/index.d.ts +6 -0
  18. package/lib/contracts/index.js +6 -0
  19. package/lib/contracts/logs.d.ts +17 -0
  20. package/lib/contracts/logs.js +28 -0
  21. package/lib/contracts/settlement-registry/abi.d.ts +810 -0
  22. package/lib/contracts/settlement-registry/abi.js +962 -0
  23. package/lib/contracts/settlement-registry/index.d.ts +143 -0
  24. package/lib/contracts/settlement-registry/index.js +213 -0
  25. package/lib/contracts/write.d.ts +59 -0
  26. package/lib/contracts/write.js +102 -0
  27. package/lib/crypto/aes.d.ts +19 -0
  28. package/lib/crypto/aes.js +26 -0
  29. package/lib/crypto/encryption.d.ts +38 -0
  30. package/lib/crypto/encryption.js +68 -0
  31. package/lib/crypto/paid.d.ts +104 -0
  32. package/lib/crypto/paid.js +147 -0
  33. package/lib/crypto/rand.d.ts +5 -0
  34. package/lib/crypto/rand.js +16 -0
  35. package/lib/crypto/types.d.ts +23 -0
  36. package/lib/crypto/types.js +1 -0
  37. package/lib/engine/car.d.ts +14 -0
  38. package/lib/engine/car.js +42 -0
  39. package/lib/engine/index.d.ts +206 -0
  40. package/lib/engine/index.js +377 -0
  41. package/lib/engine/records.d.ts +121 -0
  42. package/lib/engine/records.js +239 -0
  43. package/lib/engine/test-helpers.d.ts +38 -0
  44. package/lib/engine/test-helpers.js +63 -0
  45. package/lib/erc8004.d.ts +56 -0
  46. package/lib/erc8004.js +140 -0
  47. package/lib/fangorn.d.ts +342 -0
  48. package/lib/fangorn.js +642 -0
  49. package/lib/feed.d.ts +34 -0
  50. package/lib/feed.js +67 -0
  51. package/lib/index.d.ts +17 -0
  52. package/lib/index.js +16 -0
  53. package/lib/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.js +77 -0
  54. package/lib/node_modules/@vitest/expect/dist/index.js +1414 -0
  55. package/lib/node_modules/@vitest/pretty-format/dist/index.js +858 -0
  56. package/lib/node_modules/@vitest/runner/dist/chunk-tasks.js +51 -0
  57. package/lib/node_modules/@vitest/runner/dist/index.js +1199 -0
  58. package/lib/node_modules/@vitest/runner/dist/utils.js +3 -0
  59. package/lib/node_modules/@vitest/snapshot/dist/index.js +1075 -0
  60. package/lib/node_modules/@vitest/spy/dist/index.js +353 -0
  61. package/lib/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js +7 -0
  62. package/lib/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js +81 -0
  63. package/lib/node_modules/@vitest/utils/dist/diff.js +1345 -0
  64. package/lib/node_modules/@vitest/utils/dist/display.js +534 -0
  65. package/lib/node_modules/@vitest/utils/dist/error.js +30 -0
  66. package/lib/node_modules/@vitest/utils/dist/helpers.js +118 -0
  67. package/lib/node_modules/@vitest/utils/dist/serialize.js +76 -0
  68. package/lib/node_modules/@vitest/utils/dist/source-map.js +93 -0
  69. package/lib/node_modules/@vitest/utils/dist/timers.js +36 -0
  70. package/lib/node_modules/chai/index.js +2874 -0
  71. package/lib/node_modules/magic-string/dist/magic-string.es.js +939 -0
  72. package/lib/node_modules/pathe/dist/shared/pathe.M-eThtNZ.js +81 -0
  73. package/lib/node_modules/tinyrainbow/dist/index.js +85 -0
  74. package/lib/node_modules/vitest/dist/chunks/_commonjsHelpers.D26ty3Ew.js +5 -0
  75. package/lib/node_modules/vitest/dist/chunks/date.Bq6ZW5rf.js +50 -0
  76. package/lib/node_modules/vitest/dist/chunks/utils.DvEY5TfP.js +44 -0
  77. package/lib/node_modules/vitest/dist/chunks/vi.2VT5v0um.js +2578 -0
  78. package/lib/providers/storage/car.d.ts +36 -0
  79. package/lib/providers/storage/car.js +81 -0
  80. package/lib/providers/storage/index.d.ts +5 -0
  81. package/lib/providers/storage/index.js +5 -0
  82. package/lib/providers/storage/pinata.d.ts +53 -0
  83. package/lib/providers/storage/pinata.js +178 -0
  84. package/lib/providers/storage/signed-url.d.ts +54 -0
  85. package/lib/providers/storage/signed-url.js +122 -0
  86. package/lib/providers/storage/types.d.ts +62 -0
  87. package/lib/providers/storage/types.js +1 -0
  88. package/lib/providers/storage/utils.d.ts +30 -0
  89. package/lib/providers/storage/utils.js +107 -0
  90. package/lib/repo/index.d.ts +56 -0
  91. package/lib/repo/index.js +73 -0
  92. package/lib/test/key-server.d.ts +12 -0
  93. package/lib/test/key-server.js +30 -0
  94. package/lib/test/mem-registry.d.ts +46 -0
  95. package/lib/test/mem-registry.js +114 -0
  96. package/lib/test/sdk-suite.d.ts +10 -0
  97. package/lib/test/sdk-suite.js +155 -0
  98. package/lib/test/testbed.d.ts +16786 -0
  99. package/lib/test/testbed.js +175 -0
  100. package/lib/types/index.d.ts +37 -0
  101. package/lib/types/index.js +1 -0
  102. package/package.json +87 -0
@@ -0,0 +1,377 @@
1
+ import { assertBlockMatches, assertValidRecordId, buildMst, decodeBlock, diffMst, encodeBlock, lookupMst, readMst } from "./records.js";
2
+ import { packCar, readCar } from "./car.js";
3
+ import { ZERO_HEAD } from "../contracts/data-registry/index.js";
4
+ import "../contracts/index.js";
5
+ import { bytesToHex, hexToBytes } from "viem";
6
+ import { CID } from "multiformats/cid";
7
+ import * as dagCbor from "@ipld/dag-cbor";
8
+ import { sha256 } from "multiformats/hashes/sha2";
9
+ import * as Digest from "multiformats/hashes/digest";
10
+
11
+ //#region src/engine/index.ts
12
+ const ZERO_BYTES32 = ZERO_HEAD;
13
+ /**
14
+ * Upper bound on a repo name's length. The name is stored in every commit
15
+ * block, so this is just a sanity bound keeping that block small and
16
+ * rejecting garbage input early.
17
+ */
18
+ const MAX_REPO_NAME_LENGTH = 256;
19
+ /**
20
+ * The root of the graph, committed to IPFS, as hex
21
+ */
22
+ function rootHexFromCid(commitCid) {
23
+ return bytesToHex(commitCid.multihash.digest);
24
+ }
25
+ /** The update that settles `commit`. */
26
+ function commitUpdate(commit) {
27
+ return {
28
+ repo: commit.repo,
29
+ epoch: commit.epoch,
30
+ parent: commit.parent ? rootHexFromCid(commit.parent) : ZERO_HEAD,
31
+ root: rootHexFromCid(commit.root),
32
+ car: bytesToHex(commit.car.bytes)
33
+ };
34
+ }
35
+ /** The head the registry computes for `u`. */
36
+ async function commitHead(u) {
37
+ const link = (digest) => CID.createV1(dagCbor.code, Digest.create(sha256.code, hexToBytes(digest)));
38
+ return rootHexFromCid((await encodeBlock({
39
+ epoch: u.epoch,
40
+ parent: u.parent === ZERO_HEAD ? null : link(u.parent),
41
+ root: link(u.root),
42
+ repo: u.repo,
43
+ car: CID.decode(hexToBytes(u.car))
44
+ })).cid);
45
+ }
46
+ /** The CID a storage backend returned for a file, with or without an `ipfs://` prefix. */
47
+ function fileCid(uri) {
48
+ try {
49
+ return CID.parse(uri.replace(/^ipfs:\/\//, ""));
50
+ } catch {
51
+ throw new Error(`storage returned ${JSON.stringify(uri)} for a CAR file; expected its CID`);
52
+ }
53
+ }
54
+ /** Repos must be non-empty strings whose length does not exceed MAX_REPO_NAME_LENGTH */
55
+ function assertValidRepoName(repo) {
56
+ if (typeof repo !== "string" || repo.length === 0) throw new Error("repo must be a non-empty string");
57
+ if (repo.length > MAX_REPO_NAME_LENGTH) throw new Error(`repo exceeds the maximum length of ${MAX_REPO_NAME_LENGTH.toString()} characters (got ${repo.length.toString()}).`);
58
+ }
59
+ const EMPTY_STATE = {
60
+ state: /* @__PURE__ */ new Map(),
61
+ nodeCids: /* @__PURE__ */ new Set()
62
+ };
63
+ var FangornEngine = class {
64
+ /**
65
+ * Local block cache. Written blocks land here immediately; remote blocks
66
+ * are pulled in whole-CAR-at-a-time by `loadCar`. Content addressing makes
67
+ * the cache trivially coherent.
68
+ */
69
+ cache = /* @__PURE__ */ new Map();
70
+ /** Commits whose CAR has already been loaded into the cache. */
71
+ loadedCars = /* @__PURE__ */ new Set();
72
+ /**
73
+ * Blocks from a loaded CAR, not yet hash-checked. A CAR holds every block its commit introduced
74
+ * (the first commit of a 50k-record repo: all of them), and a diff reads a handful: each block is
75
+ * checked when `getBlock` first hands it out, then moves to `cache`.
76
+ */
77
+ unverified = /* @__PURE__ */ new Map();
78
+ constructor(storage, registry) {
79
+ this.storage = storage;
80
+ this.registry = registry;
81
+ }
82
+ /**
83
+ * Reconstructs the CID a commit's raw digest hex refers to. The contract only
84
+ * stores the bare 32-byte sha256 digest (see commitStateRoot), so rebuilding
85
+ * the CID must wrap that digest directly via Digest.create — hashing it again
86
+ * with sha256.digest() would produce an unrelated CID pointing at nothing.
87
+ */
88
+ hexToRootCid(hex) {
89
+ const rawDigestBytes = hexToBytes(`0x${hex.startsWith("0x") ? hex.slice(2) : hex}`);
90
+ const multihash = Digest.create(sha256.code, rawDigestBytes);
91
+ return CID.createV1(113, multihash);
92
+ }
93
+ /** Read and decode a commit object by CID (directly addressable — no CAR needed). */
94
+ async getCommit(commitCid) {
95
+ const key = commitCid.toString();
96
+ let bytes = this.cache.get(key);
97
+ if (!bytes) {
98
+ bytes = await this.storage.getRawBlock(key);
99
+ assertBlockMatches(commitCid, bytes);
100
+ this.cache.set(key, bytes);
101
+ }
102
+ const decoded = decodeBlock(bytes);
103
+ if (typeof decoded.epoch !== "number" || typeof decoded.repo !== "string") throw new Error(`commit ${key} predates the (e, parent, root) commit format. Reset the on-chain head (\`fangorn reset\`) and re-publish.`);
104
+ return {
105
+ epoch: decoded.epoch,
106
+ parent: decoded.parent ? CID.parse(String(decoded.parent)) : null,
107
+ root: CID.parse(String(decoded.root)),
108
+ repo: decoded.repo,
109
+ car: CID.parse(String(decoded.car))
110
+ };
111
+ }
112
+ /** Pull every block of `commit`'s CAR into the local cache. */
113
+ async loadCar(commitCid, commit) {
114
+ const bytes = await this.storage.getFile(commit.car.toString());
115
+ for (const block of await readCar(bytes, { verify: false })) {
116
+ const key = block.cid.toString();
117
+ if (!this.cache.has(key)) this.unverified.set(key, block.bytes);
118
+ }
119
+ this.loadedCars.add(commitCid.toString());
120
+ }
121
+ /**
122
+ * Resolve a data block: local cache first, then walk the commit chain from
123
+ * `hint`, loading one ancestor CAR at a time until the block turns up.
124
+ */
125
+ async getBlock(cid, hint) {
126
+ const key = cid.toString();
127
+ const local = () => {
128
+ const hit$1 = this.cache.get(key);
129
+ if (hit$1) return hit$1;
130
+ const raw = this.unverified.get(key);
131
+ if (!raw) return null;
132
+ assertBlockMatches(cid, raw);
133
+ this.unverified.delete(key);
134
+ this.cache.set(key, raw);
135
+ return raw;
136
+ };
137
+ const hit = local();
138
+ if (hit) return hit;
139
+ let cursor = hint;
140
+ while (cursor) {
141
+ const commit = await this.getCommit(cursor);
142
+ if (!this.loadedCars.has(cursor.toString())) {
143
+ await this.loadCar(cursor, commit);
144
+ const found = local();
145
+ if (found) return found;
146
+ }
147
+ cursor = commit.parent;
148
+ }
149
+ throw new Error(`Block payload missing for key: ${key}`);
150
+ }
151
+ putLocal(block) {
152
+ this.cache.set(block.cid.toString(), block.bytes);
153
+ }
154
+ /**
155
+ * Reconstruct the current on-chain head of one publisher's repo as a
156
+ * commit CID, or null if none. Each repo is its own on-chain timeline,
157
+ * so this is per-(publisher, repo) rather than per-publisher.
158
+ */
159
+ async resolveHeadCommit(publisher, repo) {
160
+ const currentHead = await this.registry.head({
161
+ publisher,
162
+ repo
163
+ });
164
+ if (currentHead === ZERO_BYTES32) return null;
165
+ return this.hexToRootCid(currentHead);
166
+ }
167
+ /**
168
+ * Which repo a commit belongs to. Events carry only `keccak256(name)`, so
169
+ * this is how a subscriber to every repo recovers the name.
170
+ */
171
+ async repoOf(rootHex) {
172
+ return (await this.getCommit(this.hexToRootCid(rootHex))).repo;
173
+ }
174
+ /** The record state a commit holds. */
175
+ async stateAt(commitCid) {
176
+ return readMst((await this.getCommit(commitCid)).root, (cid) => this.getBlock(cid, commitCid));
177
+ }
178
+ /**
179
+ * Build a new commit on top of `base` — entirely in memory, then persisted
180
+ * as exactly TWO uploads: one CAR file holding every block this commit
181
+ * introduced (git's packfile), and the small commit block itself (stored
182
+ * individually so the on-chain digest resolves without any index).
183
+ *
184
+ * Unchanged records and MST nodes re-derive their old CIDs and are NOT
185
+ * re-uploaded. Does not touch the chain — `pushCommit` settles it.
186
+ */
187
+ async createCommit(opts) {
188
+ assertValidRepoName(opts.repo);
189
+ const { repo, base } = opts;
190
+ if (base && (await this.getCommit(base)).repo !== repo) throw new Error(`commit ${base.toString()} belongs to another repo than ${repo}`);
191
+ const old = base ? await this.stateAt(base) : EMPTY_STATE;
192
+ const oldRecordCids = new Set([...old.state.values()].map(String));
193
+ const state = opts.replace ? /* @__PURE__ */ new Map() : new Map(old.state);
194
+ for (const id of opts.deletes ?? []) state.delete(id);
195
+ const carBlocks = [];
196
+ const recordCids = {};
197
+ for (const r of opts.records) {
198
+ const id = r.id ?? globalThis.crypto.randomUUID();
199
+ assertValidRecordId(id);
200
+ if (id in recordCids) throw new Error(`record id ${id} staged twice`);
201
+ const block = await encodeBlock({
202
+ id,
203
+ type: r.type,
204
+ payload: r.payload
205
+ });
206
+ state.set(id, block.cid);
207
+ recordCids[id] = block.cid.toString();
208
+ if (!oldRecordCids.has(block.cid.toString())) carBlocks.push(block);
209
+ }
210
+ const mst = await buildMst(state);
211
+ for (const node of mst.nodes) if (!old.nodeCids.has(node.cid.toString())) carBlocks.push(node);
212
+ for (const block of carBlocks) this.putLocal(block);
213
+ const carBytes = await packCar(mst.root, carBlocks);
214
+ const car = fileCid(await this.storage.putFile(carBytes, `${mst.root.toString()}.car`));
215
+ const commitBlock = await encodeBlock({
216
+ epoch: await this.registry.epoch(),
217
+ parent: base,
218
+ root: mst.root,
219
+ repo,
220
+ car
221
+ });
222
+ await this.storage.putBlock(commitBlock);
223
+ this.putLocal(commitBlock);
224
+ this.loadedCars.add(commitBlock.cid.toString());
225
+ return {
226
+ commitCid: commitBlock.cid,
227
+ root: mst.root,
228
+ recordCids
229
+ };
230
+ }
231
+ /**
232
+ * Settle a local commit as the on-chain head of one repo — the `update` of
233
+ * WHITEPAPER_1 §3.2. The commit and its CAR are already durable in storage
234
+ * (createCommit uploads them), so this is just the compare-and-swap.
235
+ */
236
+ async pushCommit(publisher, repo, commitCid) {
237
+ const update = await this.settleable(publisher, repo, commitCid);
238
+ return {
239
+ txHash: await this.registry.update(update),
240
+ onChainTip: commitCid
241
+ };
242
+ }
243
+ /** `pushCommit`, signed by this registry's wallet for anyone to submit with `relayCommit`. */
244
+ async signCommit(publisher, repo, commitCid) {
245
+ const update = await this.settleable(publisher, repo, commitCid);
246
+ return {
247
+ publisher,
248
+ update,
249
+ signature: await this.registry.signUpdate(update)
250
+ };
251
+ }
252
+ relayCommit(s) {
253
+ return this.registry.updateBySig(s.publisher, s.update, s.signature);
254
+ }
255
+ /** The update for `commitCid`, once it is one the registry will take as the next head. */
256
+ async settleable(publisher, repo, commitCid) {
257
+ const commit = await this.getCommit(commitCid);
258
+ if (commit.repo !== repo) throw new Error(`commit ${commitCid.toString()} is a commit of ${commit.repo}, not ${repo}`);
259
+ const update = commitUpdate(commit);
260
+ if (update.parent !== await this.registry.head({
261
+ publisher,
262
+ repo
263
+ })) throw new Error("stale parent: this commit's parent is not the on-chain head — rebuild it onto the current head.");
264
+ if (await commitHead(update) !== rootHexFromCid(commitCid)) throw new Error(`commit ${commitCid.toString()} is not in the current commit format — rebuild it`);
265
+ return update;
266
+ }
267
+ /** Walk the parent chain from `tip` toward the root, newest first. */
268
+ async *walkParents(tip, max) {
269
+ let cursor = tip;
270
+ for (let n = 0; cursor && (max === void 0 || n < max); n++) {
271
+ const commit = await this.getCommit(cursor);
272
+ yield {
273
+ cid: cursor,
274
+ commit
275
+ };
276
+ cursor = commit.parent;
277
+ }
278
+ }
279
+ /** The commit CID string a raw on-chain root hex points at. */
280
+ commitCidFromRootHex(hex) {
281
+ return this.hexToRootCid(hex).toString();
282
+ }
283
+ /** Inverse of `commitCidFromRootHex`: the on-chain root hex for a commit CID. */
284
+ rootHexFromCommitCid(commitCid) {
285
+ return rootHexFromCid(CID.parse(commitCid));
286
+ }
287
+ /** Decode a record block, checking it is filed under its own id. */
288
+ async decodeRecord(id, link, hint) {
289
+ const r = decodeBlock(await this.getBlock(link, hint));
290
+ if (r.id !== id) throw new Error(`record ${link.toString()} has id ${r.id}, filed under ${id}`);
291
+ return {
292
+ id,
293
+ cid: link.toString(),
294
+ type: r.type,
295
+ payload: r.payload
296
+ };
297
+ }
298
+ /**
299
+ * Net change to a single repo between two on-chain roots — the core of
300
+ * the subscription light-client. A plain comparison of the two id → CID
301
+ * maps; only records that actually changed are decoded.
302
+ *
303
+ * Diffing root-to-root (rather than walking commits) is deliberately robust:
304
+ * it yields the correct net delta even across a force-push / non-fast-forward
305
+ * reorg — exactly what an index builder needs (what to (re)embed, what to evict).
306
+ * Reads only the nodes on changed paths (`diffMst`): 10 new records in a
307
+ * 50k-record repo cost ~10 × depth nodes, not two 50k-key walks.
308
+ */
309
+ async repoDiff(oldRootHex, newRootHex) {
310
+ const newCommit = newRootHex === ZERO_BYTES32 ? null : this.hexToRootCid(newRootHex);
311
+ const oldCommit = oldRootHex && oldRootHex !== ZERO_BYTES32 ? this.hexToRootCid(oldRootHex) : null;
312
+ const root = async (c) => c ? (await this.getCommit(c)).root : null;
313
+ const diff = await diffMst(await root(oldCommit), await root(newCommit), (cid) => this.getBlock(cid, oldCommit), (cid) => this.getBlock(cid, newCommit));
314
+ const puts = [];
315
+ if (newCommit) for (const [id, cid] of diff.puts) puts.push(await this.decodeRecord(id, cid, newCommit));
316
+ return {
317
+ puts,
318
+ deletes: diff.deletes,
319
+ superseded: [...diff.before.values()].map(String)
320
+ };
321
+ }
322
+ /** Diff a commit against its parent. */
323
+ async diffCommit(commitCid) {
324
+ const commit = await this.getCommit(commitCid);
325
+ const ns = commit.repo;
326
+ const child = (await this.stateAt(commitCid)).state;
327
+ const par = commit.parent ? (await this.stateAt(commit.parent)).state : /* @__PURE__ */ new Map();
328
+ const added = [];
329
+ const updated = [];
330
+ const removed = [];
331
+ for (const [id, cid] of child) {
332
+ const prev = par.get(id);
333
+ if (!prev) added.push(`${ns}/${id}`);
334
+ else if (prev.toString() !== cid.toString()) updated.push(`${ns}/${id}`);
335
+ }
336
+ for (const id of par.keys()) if (!child.has(id)) removed.push(`${ns}/${id}`);
337
+ return {
338
+ parent: commit.parent?.toString() ?? null,
339
+ epoch: commit.epoch,
340
+ repo: ns,
341
+ root: commit.root.toString(),
342
+ added: added.sort(),
343
+ updated: updated.sort(),
344
+ removed: removed.sort()
345
+ };
346
+ }
347
+ /** check if the repo already exists (head resolves) */
348
+ async repoExists(publisher, repo) {
349
+ return await this.resolveHeadCommit(publisher, repo) !== null;
350
+ }
351
+ /** Lists every record currently committed under a repo, resolved from the on-chain root. */
352
+ async listRepo(publisher, repo) {
353
+ return this.listAt(await this.resolveHeadCommit(publisher, repo));
354
+ }
355
+ /** Every record in the state a commit holds; none for no commit. */
356
+ async listAt(head) {
357
+ if (!head) return { records: [] };
358
+ const { state } = await this.stateAt(head);
359
+ const records = [];
360
+ for (const [id, cid] of state) records.push(await this.decodeRecord(id, cid, head));
361
+ return { records };
362
+ }
363
+ /**
364
+ * Fetch the current version of one record by id — one MST path from the
365
+ * on-chain root, then the record block. Null if the repo has no such id.
366
+ */
367
+ async readRecord(publisher, repo, id) {
368
+ const head = await this.resolveHeadCommit(publisher, repo);
369
+ if (!head) throw new Error(`publisher ${publisher} has no on-chain commits in repo ${repo}`);
370
+ const get = (cid$1) => this.getBlock(cid$1, head);
371
+ const cid = await lookupMst((await this.getCommit(head)).root, id, get);
372
+ return cid ? this.decodeRecord(id, cid, head) : null;
373
+ }
374
+ };
375
+
376
+ //#endregion
377
+ export { FangornEngine, MAX_REPO_NAME_LENGTH, assertValidRepoName, commitHead, commitUpdate, fileCid, rootHexFromCid };
@@ -0,0 +1,121 @@
1
+ import { CID } from "multiformats/cid";
2
+
3
+ //#region src/engine/records.d.ts
4
+ /** A content-addressed IPLD block. */
5
+ interface Block {
6
+ cid: CID;
7
+ bytes: Uint8Array;
8
+ }
9
+ /** Encode any value as canonical dag-cbor and derive its CIDv1 (sha256). */
10
+ declare function encodeBlock(obj: unknown): Promise<Block>;
11
+ /**
12
+ * Decode a dag-cbor block. The decoder is strict (minimal encodings, sorted
13
+ * map keys), so a block has one accepted byte form (FOUNDATIONS P1).
14
+ */
15
+ declare function decodeBlock<T>(bytes: Uint8Array): T;
16
+ /** Throw unless `bytes` hash to `cid`. Hosts are untrusted; every fetched block goes through this. */
17
+ declare function assertBlockMatches(cid: CID, bytes: Uint8Array): void;
18
+ /** Record block: one version of an entity. `id` is repeated so a record can't be filed under another key. */
19
+ interface RecordBlock {
20
+ id: string;
21
+ type: string;
22
+ payload: Record<string, unknown>;
23
+ }
24
+ /**
25
+ * A reference from one record to another (FOUNDATIONS §2.2), stored as a plain
26
+ * payload value. `local`: a record id in the same repo state, follows
27
+ * updates. `pinned`: one exact record version, by CID.
28
+ * ponytail: no `live` (cross-repo) refs and no resolver yet — add with
29
+ * the §10 graph extension.
30
+ */
31
+ type Ref = {
32
+ local: string;
33
+ } | {
34
+ pinned: string;
35
+ };
36
+ /**
37
+ * Commit block: γ = (e, parent, root) of WHITEPAPER_1 §3.1, whose name is the
38
+ * on-chain head. `root` is the repo's MST root.
39
+ *
40
+ * Two more fields:
41
+ * • `repo`: the repo's name, which events carry only as keccak256(name);
42
+ * • `car`: the CID of the CAR file holding every block this commit
43
+ * introduced. The commit block itself is stored OUTSIDE that CAR
44
+ * (individually addressable), so a reader goes digest → commit → CAR with
45
+ * no index lookups.
46
+ */
47
+ interface CommitBlock {
48
+ epoch: number;
49
+ parent: CID | null;
50
+ root: CID;
51
+ repo: string;
52
+ car: CID;
53
+ }
54
+ /** Upper bound on a record id's length. */
55
+ declare const MAX_RECORD_ID_LENGTH = 256;
56
+ /**
57
+ * Record ids are printable ASCII, so JS string order is byte order and every
58
+ * implementation sorts MST keys the same way. Ids of sealed data should be
59
+ * random (FOUNDATIONS P7): a guessable id lets an observer test what exists.
60
+ */
61
+ declare function assertValidRecordId(id: string): void;
62
+ /** b: expected fanout 2^b = 16. */
63
+ declare const MST_BITS = 4;
64
+ interface MstEntry {
65
+ key: string;
66
+ value: CID;
67
+ /** Subtree of keys between this key and the next one. */
68
+ right: CID | null;
69
+ }
70
+ interface MstNode {
71
+ level: number;
72
+ /** Subtree of keys before the first entry. */
73
+ left: CID | null;
74
+ entries: MstEntry[];
75
+ }
76
+ /** level(k) = ⌊leading zero bits of sha256(k) / b⌋ */
77
+ declare function keyLevel(key: string): number;
78
+ /**
79
+ * Build the MST for a state. Returns the root and every node block; callers
80
+ * diff node CIDs against the parent's to find what to upload.
81
+ * ponytail: rebuilds the whole tree per commit (O(n) hashing, same as the
82
+ * page model it replaced); update only the changed paths if large repos
83
+ * make commits CPU-bound.
84
+ */
85
+ declare function buildMst(state: Map<string, CID>): Promise<{
86
+ root: CID;
87
+ nodes: Block[];
88
+ }>;
89
+ /**
90
+ * Read a whole MST back into its state, rejecting any tree that isn't exactly
91
+ * what `buildMst` makes of that state (MSTCheck, FOUNDATIONS P2): rebuilding
92
+ * and comparing roots catches duplicate, misordered, misplaced and wrong-level
93
+ * keys in one check.
94
+ */
95
+ declare function readMst(root: CID, getBlock: (cid: CID) => Promise<Uint8Array>): Promise<{
96
+ state: Map<string, CID>;
97
+ nodeCids: Set<string>;
98
+ }>;
99
+ /**
100
+ * What changed from one tree to another: `puts` (new keys, and keys with a new value) and `deletes`
101
+ * (keys gone), each with its old value in `before`. Both trees are read as in-order streams of entries
102
+ * and unopened subtrees; a subtree with the same CID at the head of both streams holds the same keys
103
+ * and values, so it is dropped unread. Only nodes on changed paths are fetched: ~changes × depth,
104
+ * not the size of either tree.
105
+ * ponytail: unlike readMst, does not prove either tree canonical (that needs every key). Blocks are
106
+ * still hash-checked by `getBlock`; a publisher's malformed tree can only misreport its own records.
107
+ */
108
+ declare function diffMst(oldRoot: CID | null, newRoot: CID | null, getOld: (cid: CID) => Promise<Uint8Array>, getNew: (cid: CID) => Promise<Uint8Array>): Promise<{
109
+ puts: Map<string, CID>;
110
+ deletes: string[];
111
+ before: Map<string, CID>;
112
+ }>;
113
+ /**
114
+ * The record CID stored under `key`, or null if absent — one node per level.
115
+ * ponytail: trusts node ordering on the path, so a malformed tree can hide a
116
+ * record (never forge one: the caller checks the record's id). Run `readMst`
117
+ * first where absence must be proven.
118
+ */
119
+ declare function lookupMst(root: CID, key: string, getBlock: (cid: CID) => Promise<Uint8Array>): Promise<CID | null>;
120
+ //#endregion
121
+ export { Block, CommitBlock, MAX_RECORD_ID_LENGTH, MST_BITS, MstEntry, MstNode, RecordBlock, Ref, assertBlockMatches, assertValidRecordId, buildMst, decodeBlock, diffMst, encodeBlock, keyLevel, lookupMst, readMst };