@fangorn-network/sdk 2026.7.12 → 2026.7.13

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.
@@ -1,10 +1,8 @@
1
+ import { buildPages, decodeBlock, encodeBlock, readPages } from "./graph.js";
2
+ import { packCar, readCar } from "./car.js";
1
3
  import { CID } from "multiformats/cid";
2
- import * as dagCbor from "@ipld/dag-cbor";
3
- import * as Batch from "@web3-storage/pail/batch";
4
- import { entries } from "@web3-storage/pail";
5
4
  import { sha256 } from "multiformats/hashes/sha2";
6
5
  import * as Digest from "multiformats/hashes/digest";
7
- import { ShardBlock } from "@web3-storage/pail/shard";
8
6
 
9
7
  //#region src/engine/index.ts
10
8
  var MetagraphRegistry = class {
@@ -32,36 +30,35 @@ var MetagraphRegistry = class {
32
30
  }
33
31
  };
34
32
  const ZERO_BYTES32 = "0x0000000000000000000000000000000000000000000000000000000000000000";
33
+ /**
34
+ * Upper bound on a namespace name's length. Namespaces are keys of the root
35
+ * map block, so this is just a sanity bound keeping that block small and
36
+ * rejecting garbage input early.
37
+ */
38
+ const MAX_NAMESPACE_LENGTH = 256;
39
+ /** Reject invalid namespace names up front with a clear error. */
40
+ function assertValidNamespace(namespace) {
41
+ if (typeof namespace !== "string" || namespace.length === 0) throw new Error("namespace must be a non-empty string");
42
+ if (namespace.length > MAX_NAMESPACE_LENGTH) throw new Error(`namespace exceeds the maximum length of ${MAX_NAMESPACE_LENGTH.toString()} characters (got ${namespace.length.toString()}).`);
43
+ }
35
44
  var FangornEngine = class {
36
- constructor(blockstore, metagraph, registryClient) {
37
- this.blockstore = blockstore;
45
+ /**
46
+ * Local block cache. Written blocks land here immediately; remote blocks
47
+ * are pulled in whole-CAR-at-a-time by `loadCar`. Content addressing makes
48
+ * the cache trivially coherent.
49
+ */
50
+ cache = /* @__PURE__ */ new Map();
51
+ /** Commits whose CAR has already been loaded into the cache. */
52
+ loadedCars = /* @__PURE__ */ new Set();
53
+ constructor(storage, metagraph, registryClient) {
54
+ this.storage = storage;
38
55
  this.metagraph = metagraph;
39
56
  this.registryClient = registryClient;
40
57
  }
41
- async encodeBlock(obj) {
42
- const bytes = dagCbor.encode(obj);
43
- const hash = await sha256.digest(bytes);
44
- return {
45
- cid: CID.createV1(dagCbor.code, hash),
46
- bytes
47
- };
48
- }
49
- async readBlockBytes(cid) {
50
- const chunks = [];
51
- for await (const chunk of this.blockstore.get(cid)) chunks.push(chunk);
52
- const totalLength = chunks.reduce((acc, c) => acc + c.length, 0);
53
- const flatBytes = new Uint8Array(totalLength);
54
- let offset = 0;
55
- for (const chunk of chunks) {
56
- flatBytes.set(chunk, offset);
57
- offset += chunk.length;
58
- }
59
- return flatBytes;
60
- }
61
58
  /**
62
59
  * Reconstructs the CID a commit's raw digest hex refers to. The contract only
63
- * stores the bare 32-byte sha256 digest (see commitBatch), so rebuilding the
64
- * CID must wrap that digest directly via Digest.create — hashing it again
60
+ * stores the bare 32-byte sha256 digest (see commitStateRoot), so rebuilding
61
+ * the CID must wrap that digest directly via Digest.create — hashing it again
65
62
  * with sha256.digest() would produce an unrelated CID pointing at nothing.
66
63
  */
67
64
  hexToRootCid(hex) {
@@ -70,135 +67,203 @@ var FangornEngine = class {
70
67
  const multihash = Digest.create(sha256.code, rawDigestBytes);
71
68
  return CID.createV1(113, multihash);
72
69
  }
70
+ /** Read and decode a commit object by CID (directly addressable — no CAR needed). */
71
+ async getCommit(commitCid) {
72
+ const key = commitCid.toString();
73
+ let bytes = this.cache.get(key);
74
+ if (!bytes) {
75
+ bytes = await this.storage.getRawBlock(key);
76
+ this.cache.set(key, bytes);
77
+ }
78
+ const decoded = decodeBlock(bytes);
79
+ if (decoded.pailRoot !== void 0) throw new Error(`commit ${key} predates the v2 data layer (pail-era). Reset the on-chain head (\`fangorn reset\`) and re-publish.`);
80
+ return {
81
+ root: CID.parse(String(decoded.root)),
82
+ parents: (decoded.parents ?? []).map((p) => CID.parse(String(p))),
83
+ timestamp: decoded.timestamp ?? 0,
84
+ message: decoded.message ?? "",
85
+ car: decoded.car ?? ""
86
+ };
87
+ }
88
+ /** Pull every block of `commit`'s CAR into the local cache. */
89
+ async loadCar(commitCid, commit) {
90
+ const bytes = await this.storage.getFile(commit.car);
91
+ for (const block of await readCar(bytes)) this.cache.set(block.cid.toString(), block.bytes);
92
+ this.loadedCars.add(commitCid.toString());
93
+ }
94
+ /**
95
+ * Resolve a data block: local cache first, then walk the commit chain from
96
+ * `hint`, loading one ancestor CAR at a time until the block turns up.
97
+ */
98
+ async getBlock(cid, hint) {
99
+ const key = cid.toString();
100
+ const hit = this.cache.get(key);
101
+ if (hit) return hit;
102
+ let cursor = hint;
103
+ while (cursor) {
104
+ const commit = await this.getCommit(cursor);
105
+ if (!this.loadedCars.has(cursor.toString())) {
106
+ await this.loadCar(cursor, commit);
107
+ const found = this.cache.get(key);
108
+ if (found) return found;
109
+ }
110
+ cursor = commit.parents.length ? commit.parents[0] : null;
111
+ }
112
+ throw new Error(`Block payload missing for key: ${key}`);
113
+ }
114
+ putLocal(block) {
115
+ this.cache.set(block.cid.toString(), block.bytes);
116
+ }
73
117
  /** Reconstruct the publisher's current on-chain head as a commit CID, or null if none. */
74
118
  async resolveHeadCommit(publisher) {
75
119
  const currentHead = await this.registryClient.getNamespaceHead(publisher);
76
- if (!currentHead || currentHead === ZERO_BYTES32) return null;
120
+ if (currentHead === ZERO_BYTES32) return null;
77
121
  return this.hexToRootCid(currentHead);
78
122
  }
79
- /** Read and decode a commit object by CID. */
80
- async getCommit(commitCid) {
81
- const decoded = dagCbor.decode(await this.readBlockBytes(commitCid));
123
+ /** Decode the root map behind a commit. */
124
+ async rootMapAt(commitCid) {
125
+ const commit = await this.getCommit(commitCid);
126
+ const raw = decodeBlock(await this.getBlock(commit.root, commitCid));
127
+ const rootMap = {};
128
+ for (const [ns, link] of Object.entries(raw)) rootMap[ns] = CID.parse(String(link));
129
+ return rootMap;
130
+ }
131
+ /** The full vertex/edge link sets one commit records for `namespace`. */
132
+ async treeLinksAt(commitCid, namespace) {
133
+ const rootMap = await this.rootMapAt(commitCid);
134
+ if (!(namespace in rootMap)) return {
135
+ vertexLinks: [],
136
+ edgeLinks: [],
137
+ structureCids: /* @__PURE__ */ new Set()
138
+ };
139
+ const treeLink = rootMap[namespace];
140
+ const tree = decodeBlock(await this.getBlock(treeLink, commitCid));
141
+ const get = (cid) => this.getBlock(cid, commitCid);
82
142
  return {
83
- pailRoot: decoded.pailRoot,
84
- parents: decoded.parents ?? [],
85
- timestamp: decoded.timestamp,
86
- message: decoded.message
143
+ vertexLinks: (await readPages(tree.vertices.map((c) => CID.parse(String(c))), get)).map((c) => CID.parse(String(c))),
144
+ edgeLinks: (await readPages(tree.edges.map((c) => CID.parse(String(c))), get)).map((c) => CID.parse(String(c))),
145
+ structureCids: new Set([
146
+ treeLink.toString(),
147
+ ...tree.vertices.map(String),
148
+ ...tree.edges.map(String)
149
+ ])
87
150
  };
88
151
  }
89
- /** Resolve the pail tree root behind the publisher's on-chain head commit, or null. */
90
- async resolvePailRoot(publisher) {
91
- const commitCid = await this.resolveHeadCommit(publisher);
92
- if (!commitCid) return null;
93
- return (await this.getCommit(commitCid)).pailRoot;
94
- }
95
152
  /**
96
- * Open a Pail write batch over `basePailRoot` (or a fresh empty tree when
97
- * null). Pure/local — never reads the chain, so callers control exactly which
98
- * historical root a new commit builds on (on-chain tip vs. a local HEAD).
153
+ * Build a new commit on top of `base` — entirely in memory, then persisted
154
+ * as exactly TWO uploads: one CAR file holding every block this commit
155
+ * introduced (git's packfile), and the small commit block itself (stored
156
+ * individually so the on-chain digest resolves without any index).
157
+ *
158
+ * The new namespace state is the parent state plus the staged graph;
159
+ * unchanged blocks are shared byte-for-byte with ancestors and are NOT
160
+ * re-uploaded. Does not touch the chain — `pushCommit` settles it.
99
161
  */
100
- async openBatch(basePailRoot) {
101
- let activePailRoot;
102
- if (basePailRoot) activePailRoot = basePailRoot;
103
- else {
104
- const init = await ShardBlock.create();
105
- await this.blockstore.put(init.cid, init.bytes);
106
- activePailRoot = init.cid;
162
+ async createCommit(opts) {
163
+ assertValidNamespace(opts.namespace);
164
+ const { namespace, base } = opts;
165
+ const rootMap = base ? await this.rootMapAt(base) : {};
166
+ const old = base ? await this.treeLinksAt(base, namespace) : {
167
+ vertexLinks: [],
168
+ edgeLinks: [],
169
+ structureCids: /* @__PURE__ */ new Set()
170
+ };
171
+ const oldVertexSet = new Set(old.vertexLinks.map(String));
172
+ const oldEdgeSet = new Set(old.edgeLinks.map(String));
173
+ const carBlocks = [];
174
+ const vertexCids = {};
175
+ const idInfo = /* @__PURE__ */ new Map();
176
+ const vertexLinks = opts.replace ? [] : [...old.vertexLinks];
177
+ const newVertexSet = new Set(vertexLinks.map(String));
178
+ for (const v of opts.vertices) {
179
+ if (!this.metagraph.validateVertex(namespace, v.schemaId, v.payload)) throw new Error(`Schema violation for vertex type [${v.schemaId}] in namespace [${namespace}]`);
180
+ const block = await encodeBlock({
181
+ schemaId: v.schemaId,
182
+ payload: v.payload
183
+ });
184
+ idInfo.set(v.id, {
185
+ cid: block.cid,
186
+ tag: v.schemaId
187
+ });
188
+ vertexCids[v.id] = block.cid.toString();
189
+ const key = block.cid.toString();
190
+ if (!newVertexSet.has(key)) {
191
+ newVertexSet.add(key);
192
+ vertexLinks.push(block.cid);
193
+ if (!oldVertexSet.has(key)) carBlocks.push(block);
194
+ }
107
195
  }
108
- return Batch.create({ get: async (cid) => {
196
+ const resolveEndpoint = (ref) => {
197
+ const info = idInfo.get(ref);
198
+ if (info) return info;
109
199
  try {
110
200
  return {
111
- cid,
112
- bytes: await this.readBlockBytes(cid)
201
+ cid: CID.parse(ref),
202
+ tag: null
113
203
  };
114
- } catch (error) {
115
- if (cid.toString() === activePailRoot.toString()) {
116
- const freshInit = await ShardBlock.create();
117
- return {
118
- cid: freshInit.cid,
119
- bytes: freshInit.bytes
120
- };
121
- }
122
- throw error;
204
+ } catch {
205
+ throw new Error(`edge references unknown local id (or invalid CID): ${ref}`);
123
206
  }
124
- } }, activePailRoot);
125
- }
126
- /**
127
- * Open a batch that continues the publisher's on-chain head (immediate-write
128
- * path). Returns the base commit CID and raw head hex so the caller can parent
129
- * the next commit and pass the expected old root to the on-chain CAS.
130
- */
131
- async createBatch(publisher) {
132
- const contractHeadHex = await this.registryClient.getNamespaceHead(publisher) || ZERO_BYTES32;
133
- const baseCommitCid = contractHeadHex === ZERO_BYTES32 ? null : this.hexToRootCid(contractHeadHex);
134
- const basePailRoot = baseCommitCid ? (await this.getCommit(baseCommitCid)).pailRoot : null;
135
- return {
136
- batch: await this.openBatch(basePailRoot),
137
- contractHeadHex,
138
- baseCommitCid
139
- };
140
- }
141
- async stageVertex(batch, namespace, schemaId, payload) {
142
- if (!this.metagraph.validateVertex(namespace, schemaId, payload)) throw new Error(`Schema violation for vertex type [${schemaId}] in namespace [${namespace}]`);
143
- const vertexObj = {
144
- schemaId,
145
- payload
146
- };
147
- const { cid, bytes } = await this.encodeBlock(vertexObj);
148
- await this.blockstore.put(cid, bytes);
149
- const vertexStringId = cid.toString();
150
- const partitionedKey = `${namespace}/v/${vertexStringId}`;
151
- await batch.put(partitionedKey, cid);
152
- return vertexStringId;
153
- }
154
- async stageEdge(batch, namespace, edge, sourceSchema, targetSchema) {
155
- if (!this.metagraph.validateEdge(namespace, sourceSchema, edge.relation, targetSchema)) throw new Error(`Invalid structural link relation [${edge.relation}] in namespace [${namespace}]`);
156
- const { cid, bytes } = await this.encodeBlock(edge);
157
- await this.blockstore.put(cid, bytes);
158
- const partitionedKey = `${namespace}/e/${edge.sourceCid}|${edge.relation}|${edge.targetCid}`;
159
- await batch.put(partitionedKey, cid);
160
- }
161
- /**
162
- * Seal a write batch into a new commit *locally*: flatten the pail tree, then
163
- * wrap its root in a CommitObject parented on `parents`. Writes blocks to the
164
- * blockstore but does NOT touch the chain — the git `commit` step. The
165
- * returned commit isn't on-chain until pushCommit() settles it.
166
- */
167
- async sealBatch(batch, parents, message) {
168
- const collections = await Batch.commit(batch);
169
- if (collections.additions && Array.isArray(collections.additions)) for (const block of collections.additions) await this.blockstore.put(block.cid, block.bytes);
170
- const pailRoot = collections.root;
171
- return {
172
- commitCid: await this.writeCommit(pailRoot, parents, message),
173
- pailRoot
174
207
  };
175
- }
176
- /** Build, encode and store a CommitObject block; returns its CID. */
177
- async writeCommit(pailRoot, parents, message) {
178
- const commitObj = {
179
- pailRoot,
180
- parents,
208
+ const edgeLinks = opts.replace ? [] : [...old.edgeLinks];
209
+ const newEdgeSet = new Set(edgeLinks.map(String));
210
+ for (const e of opts.edges) {
211
+ const source = resolveEndpoint(e.from);
212
+ const target = resolveEndpoint(e.to);
213
+ if (source.tag && target.tag && !this.metagraph.validateEdge(namespace, source.tag, e.relation, target.tag)) throw new Error(`Invalid structural link relation [${e.relation}] in namespace [${namespace}]`);
214
+ const block = await encodeBlock({
215
+ source: source.cid,
216
+ relation: e.relation,
217
+ target: target.cid
218
+ });
219
+ const key = block.cid.toString();
220
+ if (!newEdgeSet.has(key)) {
221
+ newEdgeSet.add(key);
222
+ edgeLinks.push(block.cid);
223
+ if (!oldEdgeSet.has(key)) carBlocks.push(block);
224
+ }
225
+ }
226
+ const { pages: vertexPages, pageLinks: vertexPageLinks } = await buildPages(vertexLinks);
227
+ const { pages: edgePages, pageLinks: edgePageLinks } = await buildPages(edgeLinks);
228
+ for (const page of [...vertexPages, ...edgePages]) if (!old.structureCids.has(page.cid.toString())) carBlocks.push(page);
229
+ const treeBlock = await encodeBlock({
230
+ vertices: vertexPageLinks,
231
+ edges: edgePageLinks
232
+ });
233
+ if (!old.structureCids.has(treeBlock.cid.toString())) carBlocks.push(treeBlock);
234
+ const rootBlock = await encodeBlock({
235
+ ...rootMap,
236
+ [namespace]: treeBlock.cid
237
+ });
238
+ carBlocks.push(rootBlock);
239
+ for (const block of carBlocks) this.putLocal(block);
240
+ const carBytes = await packCar(rootBlock.cid, carBlocks);
241
+ const carUri = await this.storage.putFile(carBytes, `${rootBlock.cid.toString()}.car`);
242
+ const commitBlock = await encodeBlock({
243
+ root: rootBlock.cid,
244
+ parents: base ? [base] : [],
181
245
  timestamp: Date.now(),
182
- message
246
+ message: opts.message,
247
+ car: carUri
248
+ });
249
+ await this.storage.putBlock(commitBlock);
250
+ this.putLocal(commitBlock);
251
+ this.loadedCars.add(commitBlock.cid.toString());
252
+ return {
253
+ commitCid: commitBlock.cid,
254
+ root: rootBlock.cid,
255
+ vertexCids
183
256
  };
184
- const { cid, bytes } = await this.encodeBlock(commitObj);
185
- await this.blockstore.put(cid, bytes);
186
- return cid;
187
- }
188
- /** Upload every block written locally since the last flush to the remote backend. */
189
- async flush() {
190
- if (typeof this.blockstore.flush === "function") await this.blockstore.flush();
191
257
  }
192
258
  /**
193
259
  * Settle a local commit as the publisher's on-chain head — the permissioned,
194
- * git `push` step. Flushes pending blocks to remote storage first (so the
195
- * commit resolves for anyone reading the chain), then does the compare-and-swap
196
- * against the current head. Unless `force`, the on-chain head must be an
197
- * ancestor of `commitCid` (fast-forward only).
260
+ * git `push` step. The commit and its CAR are already durable in storage
261
+ * (createCommit uploads them), so this is just the compare-and-swap against
262
+ * the current head. Unless `force`, the on-chain head must be an ancestor of
263
+ * `commitCid` (fast-forward only).
198
264
  */
199
265
  async pushCommit(publisher, commitCid, opts) {
200
- await this.flush();
201
- const onChainHex = await this.registryClient.getNamespaceHead(publisher) || ZERO_BYTES32;
266
+ const onChainHex = await this.registryClient.getNamespaceHead(publisher);
202
267
  const onChainCommit = onChainHex === ZERO_BYTES32 ? null : this.hexToRootCid(onChainHex);
203
268
  if (!opts?.force && onChainCommit && onChainCommit.toString() !== commitCid.toString()) {
204
269
  if (!await this.isAncestor(onChainCommit, commitCid)) throw new Error("non-fast-forward: the on-chain tip is not an ancestor of this commit — clone/rebuild onto the current tip, or push with force.");
@@ -231,43 +296,58 @@ var FangornEngine = class {
231
296
  commitCidFromRootHex(hex) {
232
297
  return this.hexToRootCid(hex).toString();
233
298
  }
299
+ /** Decode a vertex block into the public read shape. */
300
+ async decodeVertex(link, hint) {
301
+ const decoded = decodeBlock(await this.getBlock(link, hint));
302
+ return {
303
+ cid: link.toString(),
304
+ schemaId: decoded.schemaId,
305
+ payload: decoded.payload
306
+ };
307
+ }
308
+ /** Decode an edge block into the public read shape. */
309
+ async decodeEdge(link, hint) {
310
+ const decoded = decodeBlock(await this.getBlock(link, hint));
311
+ return {
312
+ sourceCid: String(decoded.source),
313
+ relation: decoded.relation,
314
+ targetCid: String(decoded.target)
315
+ };
316
+ }
234
317
  /**
235
318
  * Net change to a single namespace between two on-chain roots — the core of
236
- * the subscription light-client. Resolves the pail tree behind each commit
237
- * root and diffs only the `<namespace>/` slice, so pushes that touched *other*
238
- * namespaces of the same publisher produce an empty diff.
319
+ * the subscription light-client. Namespace trees are explicit link sets, so
320
+ * the diff is a plain set difference; only blocks that actually changed are
321
+ * decoded (each side resolves through its own commit's CAR chain).
239
322
  *
240
323
  * Diffing root-to-root (rather than walking commits) is deliberately robust:
241
324
  * it yields the correct net delta even across a force-push / non-fast-forward
242
325
  * reorg — exactly what an index builder needs (which vertices to (re)embed,
243
- * which to evict). Added vertices are decoded to their payloads; removed items
244
- * and all edges are recovered from the pail key alone (no extra fetch), since
245
- * an edge key already encodes `source|relation|target`.
326
+ * which to evict).
246
327
  */
247
328
  async namespaceDiff(oldRootHex, newRootHex, namespace) {
248
- const prefix = `${namespace}/`;
249
- const pailRootFor = async (rootHex) => (await this.getCommit(this.hexToRootCid(rootHex))).pailRoot;
250
- const before = oldRootHex && oldRootHex !== ZERO_BYTES32 ? await this.entriesAt(await pailRootFor(oldRootHex), prefix) : /* @__PURE__ */ new Map();
251
- const after = await this.entriesAt(await pailRootFor(newRootHex), prefix);
329
+ const newCommit = newRootHex === ZERO_BYTES32 ? null : this.hexToRootCid(newRootHex);
330
+ const oldCommit = oldRootHex && oldRootHex !== ZERO_BYTES32 ? this.hexToRootCid(oldRootHex) : null;
331
+ const after = newCommit ? await this.treeLinksAt(newCommit, namespace) : {
332
+ vertexLinks: [],
333
+ edgeLinks: []
334
+ };
335
+ const before = oldCommit ? await this.treeLinksAt(oldCommit, namespace) : {
336
+ vertexLinks: [],
337
+ edgeLinks: []
338
+ };
339
+ const beforeV = new Set(before.vertexLinks.map(String));
340
+ const beforeE = new Set(before.edgeLinks.map(String));
341
+ const afterV = new Set(after.vertexLinks.map(String));
342
+ const afterE = new Set(after.edgeLinks.map(String));
252
343
  const addedVertices = [];
344
+ for (const link of after.vertexLinks) if (!beforeV.has(link.toString())) addedVertices.push(await this.decodeVertex(link, newCommit));
253
345
  const addedEdges = [];
254
- const removedVertexCids = [];
346
+ for (const link of after.edgeLinks) if (!beforeE.has(link.toString())) addedEdges.push(await this.decodeEdge(link, newCommit));
347
+ const removedVertexCids = before.vertexLinks.map(String).filter((c) => !afterV.has(c));
255
348
  const removedEdges = [];
256
- for (const [key, cidStr] of after) {
257
- if (before.get(key) === cidStr) continue;
258
- if (key.startsWith(`${prefix}v/`)) {
259
- const decoded = dagCbor.decode(await this.readBlockBytes(CID.parse(cidStr)));
260
- addedVertices.push({
261
- cid: cidStr,
262
- schemaId: decoded.schemaId,
263
- payload: decoded.payload
264
- });
265
- } else if (key.startsWith(`${prefix}e/`)) addedEdges.push(this.edgeFromKey(key, prefix));
266
- }
267
- for (const [key, cidStr] of before) {
268
- if (after.has(key)) continue;
269
- if (key.startsWith(`${prefix}v/`)) removedVertexCids.push(cidStr);
270
- else if (key.startsWith(`${prefix}e/`)) removedEdges.push(this.edgeFromKey(key, prefix));
349
+ if (oldCommit) {
350
+ for (const link of before.edgeLinks) if (!afterE.has(link.toString())) removedEdges.push(await this.decodeEdge(link, oldCommit));
271
351
  }
272
352
  return {
273
353
  addedVertices,
@@ -276,92 +356,79 @@ var FangornEngine = class {
276
356
  removedEdges
277
357
  };
278
358
  }
279
- /** Recover an Edge from its pail key `<ns>/e/<source>|<relation>|<target>`. */
280
- edgeFromKey(key, prefix) {
281
- const [sourceCid, relation, targetCid] = key.slice(`${prefix}e/`.length).split("|");
282
- return {
283
- sourceCid,
284
- relation,
285
- targetCid
286
- };
287
- }
288
- /** Diff a commit against its first parent, by namespaced pail key. */
359
+ /** Diff a commit against its first parent, across every namespace. */
289
360
  async diffCommit(commitCid) {
290
361
  const commit = await this.getCommit(commitCid);
291
- const child = await this.entriesAt(commit.pailRoot);
292
- const parent = commit.parents.length ? await this.entriesAt((await this.getCommit(commit.parents[0])).pailRoot) : /* @__PURE__ */ new Map();
293
- const added = [...child.entries()].filter(([k, v]) => parent.get(k) !== v).map(([k]) => k);
294
- const removed = [...parent.keys()].filter((k) => !child.has(k));
362
+ const parent = commit.parents.length ? commit.parents[0] : null;
363
+ const childRoot = await this.rootMapAt(commitCid);
364
+ const parentRoot = parent ? await this.rootMapAt(parent) : {};
365
+ const added = [];
366
+ const removed = [];
367
+ const namespaces = new Set([...Object.keys(childRoot), ...Object.keys(parentRoot)]);
368
+ for (const ns of namespaces) {
369
+ const inParent = ns in parentRoot;
370
+ const inChild = ns in childRoot;
371
+ if (inParent && inChild && String(parentRoot[ns]) === String(childRoot[ns])) continue;
372
+ const child = inChild ? await this.treeLinksAt(commitCid, ns) : {
373
+ vertexLinks: [],
374
+ edgeLinks: []
375
+ };
376
+ const par = parent && inParent ? await this.treeLinksAt(parent, ns) : {
377
+ vertexLinks: [],
378
+ edgeLinks: []
379
+ };
380
+ const parV = new Set(par.vertexLinks.map(String));
381
+ const parE = new Set(par.edgeLinks.map(String));
382
+ const childV = new Set(child.vertexLinks.map(String));
383
+ const childE = new Set(child.edgeLinks.map(String));
384
+ for (const c of childV) if (!parV.has(c)) added.push(`${ns}/v/${c}`);
385
+ for (const c of childE) if (!parE.has(c)) added.push(`${ns}/e/${c}`);
386
+ for (const c of parV) if (!childV.has(c)) removed.push(`${ns}/v/${c}`);
387
+ for (const c of parE) if (!childE.has(c)) removed.push(`${ns}/e/${c}`);
388
+ }
295
389
  return {
296
390
  message: commit.message,
297
391
  parents: commit.parents.map((c) => c.toString()),
298
392
  timestamp: commit.timestamp,
299
- pailRoot: commit.pailRoot.toString(),
393
+ root: commit.root.toString(),
300
394
  added: added.sort(),
301
395
  removed: removed.sort()
302
396
  };
303
397
  }
304
- /** Every content-linked pail key → linked CID string, under an optional prefix. */
305
- async entriesAt(pailRoot, prefix = "") {
306
- const blocks = { get: async (cid) => ({
307
- cid,
308
- bytes: await this.readBlockBytes(cid)
309
- }) };
310
- const out = /* @__PURE__ */ new Map();
311
- for await (const [key, value] of entries(blocks, pailRoot, { prefix })) {
312
- const linkCid = CID.asCID(value);
313
- if (linkCid) out.set(key, linkCid.toString());
314
- }
315
- return out;
316
- }
317
- /**
318
- * Cheap existence check: does anything (including the bare `sys/init`
319
- * marker) exist under this namespace prefix yet? Short-circuits on the
320
- * first entry found instead of decoding the whole namespace, unlike
321
- * listNamespace (which also skips non-CID values like the marker itself).
322
- */
398
+ /** Does this namespace exist under the publisher's on-chain root yet? */
323
399
  async namespaceExists(namespace, publisher) {
324
- const rootCid = await this.resolvePailRoot(publisher);
325
- if (!rootCid) return false;
326
- const blocks = { get: async (cid) => ({
327
- cid,
328
- bytes: await this.readBlockBytes(cid)
329
- }) };
330
- const prefix = `${namespace}/`;
331
- for await (const _entry of entries(blocks, rootCid, { prefix })) return true;
332
- return false;
400
+ const head = await this.resolveHeadCommit(publisher);
401
+ if (!head) return false;
402
+ return namespace in await this.rootMapAt(head);
333
403
  }
334
- /** Lists every vertex and edge currently staged under a namespace, resolved from the on-chain root. */
404
+ /** Lists every vertex and edge currently committed under a namespace, resolved from the on-chain root. */
335
405
  async listNamespace(namespace, publisher) {
406
+ const head = await this.resolveHeadCommit(publisher);
407
+ if (!head) return {
408
+ vertices: [],
409
+ edges: []
410
+ };
411
+ const { vertexLinks, edgeLinks } = await this.treeLinksAt(head, namespace);
336
412
  const vertices = [];
413
+ for (const link of vertexLinks) vertices.push(await this.decodeVertex(link, head));
337
414
  const edges = [];
338
- const rootCid = await this.resolvePailRoot(publisher);
339
- if (!rootCid) return {
340
- vertices,
341
- edges
342
- };
343
- const blocks = { get: async (cid) => ({
344
- cid,
345
- bytes: await this.readBlockBytes(cid)
346
- }) };
347
- const prefix = `${namespace}/`;
348
- for await (const [key, value] of entries(blocks, rootCid, { prefix })) {
349
- const linkCid = CID.asCID(value);
350
- if (!linkCid) continue;
351
- const decoded = dagCbor.decode(await this.readBlockBytes(linkCid));
352
- if (key.startsWith(`${prefix}v/`)) vertices.push({
353
- cid: linkCid.toString(),
354
- schemaId: decoded.schemaId,
355
- payload: decoded.payload
356
- });
357
- else if (key.startsWith(`${prefix}e/`)) edges.push(decoded);
358
- }
415
+ for (const link of edgeLinks) edges.push(await this.decodeEdge(link, head));
359
416
  return {
360
417
  vertices,
361
418
  edges
362
419
  };
363
420
  }
421
+ /**
422
+ * Fetch a single vertex by CID, resolving through the publisher's commit
423
+ * CAR chain (vertex blocks are not individually pinned — they live inside
424
+ * commit CARs).
425
+ */
426
+ async readVertex(cid, publisher) {
427
+ const head = await this.resolveHeadCommit(publisher);
428
+ if (!head) throw new Error(`publisher ${publisher} has no on-chain commits`);
429
+ return this.decodeVertex(CID.parse(cid), head);
430
+ }
364
431
  };
365
432
 
366
433
  //#endregion
367
- export { FangornEngine, MetagraphRegistry };
434
+ export { FangornEngine, MAX_NAMESPACE_LENGTH, MetagraphRegistry, assertValidNamespace };
@@ -0,0 +1,43 @@
1
+ import { DataRegistryClient } from "../contracts/data-registry/index.js";
2
+ import "../contracts/index.js";
3
+ import { MetadataStorage, RawBlock, StorageMeta } from "../providers/storage/types.js";
4
+ import { Hex } from "viem";
5
+ import { CID } from "multiformats/cid";
6
+
7
+ //#region src/engine/test-helpers.d.ts
8
+ declare const ZERO_BYTES32 = "0x0000000000000000000000000000000000000000000000000000000000000000";
9
+ /** The raw 32-byte root hex a commit CID settles to on-chain (bare sha256 digest). */
10
+ declare const rootHex: (commitCid: CID) => string;
11
+ /**
12
+ * In-memory MetadataStorage: individually-pinned blocks + opaque files, with
13
+ * write/read counters — remote writes are the publish cost driver, so tests
14
+ * assert on them directly.
15
+ */
16
+ declare class MemStorage implements MetadataStorage {
17
+ blocks: Map<string, Uint8Array<ArrayBufferLike>>;
18
+ files: Map<string, Uint8Array<ArrayBufferLike>>;
19
+ /** Remote uploads performed (putBlock + putFile). */
20
+ writes: number;
21
+ /** Remote fetches performed (getRawBlock + getFile). */
22
+ reads: number;
23
+ putBlock(block: RawBlock): Promise<void>;
24
+ putFile(bytes: Uint8Array, name: string): Promise<string>;
25
+ getFile(uri: string): Promise<Uint8Array>;
26
+ getRawBlock(uri: string): Promise<Uint8Array>;
27
+ put(_data: unknown, _meta?: StorageMeta): Promise<string>;
28
+ putMany(_items: {
29
+ data: unknown;
30
+ name: string;
31
+ }[]): Promise<Record<string, string>>;
32
+ get<T>(_uri: string): Promise<T>;
33
+ delete(_uri: string): Promise<void>;
34
+ }
35
+ /** Registry stub holding one publisher head in memory (enough for the engine). */
36
+ declare class StubRegistry {
37
+ head: string;
38
+ getNamespaceHead(_publisher: string): Promise<string>;
39
+ commitStateRoot(_oldRoot: Hex, newRoot: Hex): Promise<Hex>;
40
+ asClient(): DataRegistryClient;
41
+ }
42
+ //#endregion
43
+ export { MemStorage, StubRegistry, ZERO_BYTES32, rootHex };