@fangorn-network/sdk 2026.6.16 → 2026.7.1-2.1
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.
- package/README.md +210 -266
- package/lib/cli/cli.d.ts +0 -0
- package/lib/cli/cli.js +261 -167
- package/lib/cli/index.d.ts +13 -651
- package/lib/config.d.ts +137 -792
- package/lib/config.js +6 -22
- package/lib/contracts/data-registry/abi.d.ts +38 -0
- package/lib/contracts/data-registry/abi.js +237 -0
- package/lib/contracts/data-registry/index.d.ts +81 -0
- package/lib/contracts/data-registry/index.js +184 -0
- package/lib/contracts/index.d.ts +3 -0
- package/lib/contracts/index.js +4 -0
- package/lib/crypto/aes.d.ts +26 -0
- package/lib/crypto/aes.js +58 -0
- package/lib/crypto/encryption.d.ts +53 -0
- package/lib/crypto/encryption.js +82 -0
- package/lib/{modules/encryption → crypto}/rand.d.ts +1 -1
- package/lib/{modules/encryption → crypto}/rand.js +1 -1
- package/lib/{modules/encryption → crypto}/types.d.ts +1 -1
- package/lib/engine/blockstore.d.ts +24 -0
- package/lib/engine/blockstore.js +85 -0
- package/lib/engine/index.d.ts +180 -0
- package/lib/engine/index.js +367 -0
- package/lib/fangorn.d.ts +149 -16
- package/lib/fangorn.js +256 -37
- package/lib/harness/examples/hackmd/build-markdown-graph.js +17 -0
- package/lib/harness/index.d.ts +57 -0
- package/lib/harness/index.js +67 -0
- package/lib/index.d.ts +3 -2
- package/lib/index.js +2 -1
- package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/_polyval.js +218 -0
- package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/aes.js +261 -0
- package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/utils.js +156 -0
- package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/curve.js +299 -0
- package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/edwards.js +532 -0
- package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/modular.js +344 -0
- package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/montgomery.js +137 -0
- package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/ed25519.js +262 -0
- package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/utils.js +150 -0
- package/lib/providers/storage/car.d.ts +36 -0
- package/lib/providers/storage/car.js +80 -0
- package/lib/providers/storage/pinata.d.ts +29 -1
- package/lib/providers/storage/pinata.js +135 -20
- package/lib/providers/storage/types.d.ts +25 -18
- package/lib/roles/repo/index.d.ts +56 -0
- package/lib/roles/repo/index.js +73 -0
- package/lib/test/car_smoke.d.ts +1 -0
- package/lib/test/car_smoke.js +81 -0
- package/lib/test/cleanup-embeddings-testdata.js +9 -38
- package/lib/test/setup-embeddings-testdata.d.ts +4 -6
- package/lib/test/setup-embeddings-testdata.js +40 -94
- package/lib/test/testbed.d.ts +35 -32
- package/lib/test/testbed.js +48 -138
- package/lib/types/index.d.ts +3 -19
- package/lib/utils/manifest.d.ts +23 -0
- package/lib/utils/manifest.js +77 -0
- package/package.json +99 -81
- package/lib/modules/encryption/actions.d.ts +0 -4
- package/lib/modules/encryption/actions.js +0 -18
- package/lib/modules/encryption/aes.d.ts +0 -10
- package/lib/modules/encryption/aes.js +0 -51
- package/lib/registries/datasource-registry/abi.d.ts +0 -186
- package/lib/registries/datasource-registry/abi.js +0 -229
- package/lib/registries/datasource-registry/index.d.ts +0 -39
- package/lib/registries/datasource-registry/index.js +0 -158
- package/lib/registries/index.d.ts +0 -3
- package/lib/registries/index.js +0 -4
- package/lib/registries/schema-registry/abi.d.ts +0 -218
- package/lib/registries/schema-registry/abi.js +0 -246
- package/lib/registries/schema-registry/index.d.ts +0 -34
- package/lib/registries/schema-registry/index.js +0 -179
- package/lib/registries/settlement-registry/abi.d.ts +0 -218
- package/lib/registries/settlement-registry/abi.js +0 -259
- package/lib/registries/settlement-registry/index.d.ts +0 -63
- package/lib/registries/settlement-registry/index.js +0 -325
- package/lib/registries/settlement-registry/types.d.ts +0 -54
- package/lib/registries/settlement-registry/types.js +0 -1
- package/lib/roles/consumer/index.d.ts +0 -39
- package/lib/roles/consumer/index.js +0 -150
- package/lib/roles/consumer/types.d.ts +0 -47
- package/lib/roles/consumer/types.js +0 -1
- package/lib/roles/publisher/builders/bundle.d.ts +0 -32
- package/lib/roles/publisher/builders/bundle.js +0 -137
- package/lib/roles/publisher/builders/record-set.d.ts +0 -17
- package/lib/roles/publisher/builders/record-set.js +0 -55
- package/lib/roles/publisher/builders/types.d.ts +0 -38
- package/lib/roles/publisher/builders/types.js +0 -1
- package/lib/roles/publisher/builders/utils.d.ts +0 -9
- package/lib/roles/publisher/builders/utils.js +0 -29
- package/lib/roles/publisher/encryption.d.ts +0 -18
- package/lib/roles/publisher/encryption.js +0 -38
- package/lib/roles/publisher/index.d.ts +0 -68
- package/lib/roles/publisher/index.js +0 -179
- package/lib/roles/publisher/types.d.ts +0 -114
- package/lib/roles/publisher/types.js +0 -1
- package/lib/roles/schema/index.d.ts +0 -44
- package/lib/roles/schema/index.js +0 -127
- package/lib/roles/schema/types.d.ts +0 -113
- package/lib/roles/schema/types.js +0 -1
- package/lib/roles/schema/validate.d.ts +0 -9
- package/lib/roles/schema/validate.js +0 -128
- package/lib/test/publish_mb_bundle.js +0 -296
- /package/lib/{modules/encryption/index.d.ts → contracts/data-registry/test.d.ts} +0 -0
- /package/lib/{modules/encryption/index.js → contracts/data-registry/test.js} +0 -0
- /package/lib/{modules/encryption → crypto}/types.js +0 -0
- /package/lib/{test/publish_mb_bundle.d.ts → harness/examples/hackmd/build-markdown-graph.d.ts} +0 -0
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
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
|
+
import { sha256 } from "multiformats/hashes/sha2";
|
|
6
|
+
import * as Digest from "multiformats/hashes/digest";
|
|
7
|
+
import { ShardBlock } from "@web3-storage/pail/shard";
|
|
8
|
+
|
|
9
|
+
//#region src/engine/index.ts
|
|
10
|
+
var MetagraphRegistry = class {
|
|
11
|
+
vertexSchemas = /* @__PURE__ */ new Map();
|
|
12
|
+
edgeSchemas = /* @__PURE__ */ new Set();
|
|
13
|
+
registerVertex(namespace, schema) {
|
|
14
|
+
this.vertexSchemas.set(`${namespace}|${schema.id}`, schema);
|
|
15
|
+
}
|
|
16
|
+
hasVertexSchema(namespace, schemaId) {
|
|
17
|
+
return this.vertexSchemas.has(`${namespace}|${schemaId}`);
|
|
18
|
+
}
|
|
19
|
+
registerEdge(namespace, rule) {
|
|
20
|
+
this.edgeSchemas.add(`${namespace}|${rule.sourceSchema}|${rule.relation}|${rule.targetSchema}`);
|
|
21
|
+
}
|
|
22
|
+
hasEdgeSchema(namespace, sourceSchema, relation, targetSchema) {
|
|
23
|
+
return this.edgeSchemas.has(`${namespace}|${sourceSchema}|${relation}|${targetSchema}`);
|
|
24
|
+
}
|
|
25
|
+
validateVertex(namespace, schemaId, payload) {
|
|
26
|
+
const schema = this.vertexSchemas.get(`${namespace}|${schemaId}`);
|
|
27
|
+
if (!schema) return false;
|
|
28
|
+
return schema.requiredFields.every((field) => field in payload);
|
|
29
|
+
}
|
|
30
|
+
validateEdge(namespace, sourceSchema, relation, targetSchema) {
|
|
31
|
+
return this.edgeSchemas.has(`${namespace}|${sourceSchema}|${relation}|${targetSchema}`);
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
const ZERO_BYTES32 = "0x0000000000000000000000000000000000000000000000000000000000000000";
|
|
35
|
+
var FangornEngine = class {
|
|
36
|
+
constructor(blockstore, metagraph, registryClient) {
|
|
37
|
+
this.blockstore = blockstore;
|
|
38
|
+
this.metagraph = metagraph;
|
|
39
|
+
this.registryClient = registryClient;
|
|
40
|
+
}
|
|
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
|
+
/**
|
|
62
|
+
* 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
|
|
65
|
+
* with sha256.digest() would produce an unrelated CID pointing at nothing.
|
|
66
|
+
*/
|
|
67
|
+
hexToRootCid(hex) {
|
|
68
|
+
const cleanHex = hex.startsWith("0x") ? hex.slice(2) : hex;
|
|
69
|
+
const rawDigestBytes = Uint8Array.from(Buffer.from(cleanHex, "hex"));
|
|
70
|
+
const multihash = Digest.create(sha256.code, rawDigestBytes);
|
|
71
|
+
return CID.createV1(113, multihash);
|
|
72
|
+
}
|
|
73
|
+
/** Reconstruct the publisher's current on-chain head as a commit CID, or null if none. */
|
|
74
|
+
async resolveHeadCommit(publisher) {
|
|
75
|
+
const currentHead = await this.registryClient.getNamespaceHead(publisher);
|
|
76
|
+
if (!currentHead || currentHead === ZERO_BYTES32) return null;
|
|
77
|
+
return this.hexToRootCid(currentHead);
|
|
78
|
+
}
|
|
79
|
+
/** Read and decode a commit object by CID. */
|
|
80
|
+
async getCommit(commitCid) {
|
|
81
|
+
const decoded = dagCbor.decode(await this.readBlockBytes(commitCid));
|
|
82
|
+
return {
|
|
83
|
+
pailRoot: decoded.pailRoot,
|
|
84
|
+
parents: decoded.parents ?? [],
|
|
85
|
+
timestamp: decoded.timestamp,
|
|
86
|
+
message: decoded.message
|
|
87
|
+
};
|
|
88
|
+
}
|
|
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
|
+
/**
|
|
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).
|
|
99
|
+
*/
|
|
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;
|
|
107
|
+
}
|
|
108
|
+
return Batch.create({ get: async (cid) => {
|
|
109
|
+
try {
|
|
110
|
+
return {
|
|
111
|
+
cid,
|
|
112
|
+
bytes: await this.readBlockBytes(cid)
|
|
113
|
+
};
|
|
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;
|
|
123
|
+
}
|
|
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
|
+
};
|
|
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,
|
|
181
|
+
timestamp: Date.now(),
|
|
182
|
+
message
|
|
183
|
+
};
|
|
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
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* 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).
|
|
198
|
+
*/
|
|
199
|
+
async pushCommit(publisher, commitCid, opts) {
|
|
200
|
+
await this.flush();
|
|
201
|
+
const onChainHex = await this.registryClient.getNamespaceHead(publisher) || ZERO_BYTES32;
|
|
202
|
+
const onChainCommit = onChainHex === ZERO_BYTES32 ? null : this.hexToRootCid(onChainHex);
|
|
203
|
+
if (!opts?.force && onChainCommit && onChainCommit.toString() !== commitCid.toString()) {
|
|
204
|
+
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.");
|
|
205
|
+
}
|
|
206
|
+
const newRootHex = `0x${Buffer.from(commitCid.multihash.digest).toString("hex")}`;
|
|
207
|
+
return {
|
|
208
|
+
txHash: await this.registryClient.commitStateRoot(onChainHex, newRootHex),
|
|
209
|
+
onChainTip: commitCid
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
/** Walk the first-parent chain from `tip` toward the root, newest first. */
|
|
213
|
+
async *walkParents(tip, max) {
|
|
214
|
+
let cursor = tip;
|
|
215
|
+
for (let n = 0; cursor && (max === void 0 || n < max); n++) {
|
|
216
|
+
const commit = await this.getCommit(cursor);
|
|
217
|
+
yield {
|
|
218
|
+
cid: cursor,
|
|
219
|
+
commit
|
|
220
|
+
};
|
|
221
|
+
cursor = commit.parents.length ? commit.parents[0] : null;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
/** True if `ancestor` appears on the first-parent chain of `tip`. */
|
|
225
|
+
async isAncestor(ancestor, tip) {
|
|
226
|
+
const target = ancestor.toString();
|
|
227
|
+
for await (const { cid } of this.walkParents(tip)) if (cid.toString() === target) return true;
|
|
228
|
+
return false;
|
|
229
|
+
}
|
|
230
|
+
/** The commit CID string a raw on-chain root hex points at. */
|
|
231
|
+
commitCidFromRootHex(hex) {
|
|
232
|
+
return this.hexToRootCid(hex).toString();
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* 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.
|
|
239
|
+
*
|
|
240
|
+
* Diffing root-to-root (rather than walking commits) is deliberately robust:
|
|
241
|
+
* it yields the correct net delta even across a force-push / non-fast-forward
|
|
242
|
+
* 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`.
|
|
246
|
+
*/
|
|
247
|
+
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);
|
|
252
|
+
const addedVertices = [];
|
|
253
|
+
const addedEdges = [];
|
|
254
|
+
const removedVertexCids = [];
|
|
255
|
+
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));
|
|
271
|
+
}
|
|
272
|
+
return {
|
|
273
|
+
addedVertices,
|
|
274
|
+
addedEdges,
|
|
275
|
+
removedVertexCids,
|
|
276
|
+
removedEdges
|
|
277
|
+
};
|
|
278
|
+
}
|
|
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. */
|
|
289
|
+
async diffCommit(commitCid) {
|
|
290
|
+
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));
|
|
295
|
+
return {
|
|
296
|
+
message: commit.message,
|
|
297
|
+
parents: commit.parents.map((c) => c.toString()),
|
|
298
|
+
timestamp: commit.timestamp,
|
|
299
|
+
pailRoot: commit.pailRoot.toString(),
|
|
300
|
+
added: added.sort(),
|
|
301
|
+
removed: removed.sort()
|
|
302
|
+
};
|
|
303
|
+
}
|
|
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
|
+
*/
|
|
323
|
+
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;
|
|
333
|
+
}
|
|
334
|
+
/** Lists every vertex and edge currently staged under a namespace, resolved from the on-chain root. */
|
|
335
|
+
async listNamespace(namespace, publisher) {
|
|
336
|
+
const vertices = [];
|
|
337
|
+
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
|
+
}
|
|
359
|
+
return {
|
|
360
|
+
vertices,
|
|
361
|
+
edges
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
};
|
|
365
|
+
|
|
366
|
+
//#endregion
|
|
367
|
+
export { FangornEngine, MetagraphRegistry };
|
package/lib/fangorn.d.ts
CHANGED
|
@@ -1,30 +1,163 @@
|
|
|
1
1
|
import { AppConfig } from "./config.js";
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { SettlementRegistry } from "./registries/settlement-registry/index.js";
|
|
7
|
-
import { ConsumerRole } from "./roles/consumer/index.js";
|
|
2
|
+
import { DataRegistryClient } from "./contracts/data-registry/index.js";
|
|
3
|
+
import "./contracts/index.js";
|
|
4
|
+
import { MetadataStorage } from "./providers/storage/types.js";
|
|
5
|
+
import { CommitDiff, FangornEngine, MetagraphRegistry, NamespaceContents, NamespaceDiff } from "./engine/index.js";
|
|
8
6
|
import { FangornCreateOptions } from "./types/index.js";
|
|
9
7
|
import { Hex, WalletClient } from "viem";
|
|
10
8
|
|
|
11
9
|
//#region src/fangorn.d.ts
|
|
10
|
+
/** One namespace-scoped update surfaced by `subscribe`. */
|
|
11
|
+
interface NamespaceChange extends NamespaceDiff {
|
|
12
|
+
namespace: string;
|
|
13
|
+
owner: Hex;
|
|
14
|
+
/** The commit CID (string) this update settled to — the new on-chain tip. */
|
|
15
|
+
commitCid: string;
|
|
16
|
+
/** Raw on-chain roots this delta spans (`oldRoot` → `newRoot`). */
|
|
17
|
+
oldRoot: Hex;
|
|
18
|
+
newRoot: Hex;
|
|
19
|
+
/** Block the `StateCommitted` event landed in — persist as the resume cursor. */
|
|
20
|
+
blockNumber: bigint;
|
|
21
|
+
}
|
|
22
|
+
interface SubscribeOptions {
|
|
23
|
+
namespace: string;
|
|
24
|
+
/** Publisher whose root to watch (defaults to this wallet's address). */
|
|
25
|
+
owner?: Hex;
|
|
26
|
+
/**
|
|
27
|
+
* Replay `StateCommitted` events from this block before going live (the resume
|
|
28
|
+
* cursor). Omit to start live from the current chain tip — seed initial state
|
|
29
|
+
* separately via `inspectNamespace`.
|
|
30
|
+
*/
|
|
31
|
+
fromBlock?: bigint;
|
|
32
|
+
/** Poll interval (ms) for the live watch over an HTTP transport. */
|
|
33
|
+
pollingInterval?: number;
|
|
34
|
+
/** Abort to stop the subscription and release the watch. */
|
|
35
|
+
signal?: AbortSignal;
|
|
36
|
+
}
|
|
12
37
|
declare class Fangorn {
|
|
13
38
|
private readonly ctx;
|
|
14
|
-
private
|
|
15
|
-
private
|
|
16
|
-
private _consumer;
|
|
39
|
+
private _engine;
|
|
40
|
+
private _metagraph;
|
|
17
41
|
private constructor();
|
|
18
|
-
get
|
|
19
|
-
get
|
|
20
|
-
get consumer(): ConsumerRole;
|
|
42
|
+
get engine(): FangornEngine;
|
|
43
|
+
get metagraph(): MetagraphRegistry;
|
|
21
44
|
static create(options: FangornCreateOptions): Fangorn;
|
|
45
|
+
reset(): Promise<void>;
|
|
46
|
+
/**
|
|
47
|
+
* Allocates a namespace key directly within the transactional Pail index tree.
|
|
48
|
+
* A no-op (no on-chain tx) if the namespace is already initialized, so callers
|
|
49
|
+
* can call this unconditionally before every publish.
|
|
50
|
+
*/
|
|
51
|
+
initRepo(repoName: string): Promise<{
|
|
52
|
+
cid: undefined;
|
|
53
|
+
commitCid: undefined;
|
|
54
|
+
txHash: undefined;
|
|
55
|
+
alreadyInitialized: true;
|
|
56
|
+
} | {
|
|
57
|
+
cid: string;
|
|
58
|
+
commitCid: string;
|
|
59
|
+
txHash: `0x${string}`;
|
|
60
|
+
alreadyInitialized: false;
|
|
61
|
+
}>;
|
|
62
|
+
/**
|
|
63
|
+
* Stages a node payload against structural metadata rules inside the Pail collection context.
|
|
64
|
+
*/
|
|
65
|
+
upload(repoName: string, payload: any, schemaId: string): Promise<{
|
|
66
|
+
payloadCid: string;
|
|
67
|
+
commitCid: string;
|
|
68
|
+
txHash: `0x${string}`;
|
|
69
|
+
}>;
|
|
70
|
+
/**
|
|
71
|
+
* Stages vertices (and edges resolved by local id) into a namespace against an
|
|
72
|
+
* already-open batch. Shared by the immediate `uploadBatch` path and the git
|
|
73
|
+
* `commit` path. Returns the local-id → staged-CID map.
|
|
74
|
+
*/
|
|
75
|
+
private stageGraph;
|
|
76
|
+
/**
|
|
77
|
+
* Stages many vertices (and optionally edges between them) in a single
|
|
78
|
+
* on-chain commit, instead of one tx per vertex. Edges reference vertices by
|
|
79
|
+
* the caller-supplied local `id`, resolved to their staged CID before staging.
|
|
80
|
+
*/
|
|
81
|
+
uploadBatch(repoName: string, vertices: {
|
|
82
|
+
id: string;
|
|
83
|
+
tag: string;
|
|
84
|
+
payload: any;
|
|
85
|
+
}[], edges?: {
|
|
86
|
+
rel: string;
|
|
87
|
+
from: string;
|
|
88
|
+
to: string;
|
|
89
|
+
}[]): Promise<{
|
|
90
|
+
commitCid: string;
|
|
91
|
+
txHash: `0x${string}`;
|
|
92
|
+
vertexCids: {
|
|
93
|
+
[k: string]: string;
|
|
94
|
+
};
|
|
95
|
+
}>;
|
|
96
|
+
/**
|
|
97
|
+
* Build a new commit locally (no on-chain tx) that stages vertices/edges into
|
|
98
|
+
* `namespace` on top of `parent` (a commit CID string, or undefined for a root
|
|
99
|
+
* commit). Blocks are flushed to storage so a later `push` — even in a separate
|
|
100
|
+
* process — can settle it.
|
|
101
|
+
*/
|
|
102
|
+
commit(opts: {
|
|
103
|
+
namespace: string;
|
|
104
|
+
vertices?: {
|
|
105
|
+
id: string;
|
|
106
|
+
tag: string;
|
|
107
|
+
payload: any;
|
|
108
|
+
}[];
|
|
109
|
+
edges?: {
|
|
110
|
+
rel: string;
|
|
111
|
+
from: string;
|
|
112
|
+
to: string;
|
|
113
|
+
}[];
|
|
114
|
+
parent?: string;
|
|
115
|
+
message: string;
|
|
116
|
+
}): Promise<{
|
|
117
|
+
commitCid: string;
|
|
118
|
+
parents: string[];
|
|
119
|
+
pailRoot: string;
|
|
120
|
+
vertexCids: Record<string, string>;
|
|
121
|
+
}>;
|
|
122
|
+
/** Settle a local commit as the on-chain head (fast-forward unless `force`). */
|
|
123
|
+
push(commitCid: string, opts?: {
|
|
124
|
+
force?: boolean;
|
|
125
|
+
}): Promise<{
|
|
126
|
+
txHash: string;
|
|
127
|
+
onChainTip: string;
|
|
128
|
+
}>;
|
|
129
|
+
/** The owner's current on-chain tip commit CID, or null if they have no commits. */
|
|
130
|
+
onChainTip(owner: Hex): Promise<string | null>;
|
|
131
|
+
/** Walk commit history from `head` (newest first). */
|
|
132
|
+
log(head: string, max?: number): AsyncGenerator<{
|
|
133
|
+
cid: string;
|
|
134
|
+
parents: string[];
|
|
135
|
+
timestamp: number;
|
|
136
|
+
message: string;
|
|
137
|
+
pailRoot: string;
|
|
138
|
+
}>;
|
|
139
|
+
/** Show a commit and what it changed vs. its first parent. */
|
|
140
|
+
show(commitCid: string): Promise<CommitDiff>;
|
|
141
|
+
/**
|
|
142
|
+
* Lists every vertex and edge currently committed under a namespace, resolved
|
|
143
|
+
* from the publisher's on-chain root — useful for verifying what actually
|
|
144
|
+
* made it into the repository, as opposed to what a given call staged.
|
|
145
|
+
*/
|
|
146
|
+
inspectNamespace(repoName: string): Promise<NamespaceContents>;
|
|
147
|
+
/**
|
|
148
|
+
* Stream namespace-scoped changes as the on-chain root advances. Optionally
|
|
149
|
+
* replays from `fromBlock` first (resume cursor), then watches live until the
|
|
150
|
+
* `signal` aborts. Each yielded change carries `blockNumber` — persist it to
|
|
151
|
+
* resume exactly where you left off.
|
|
152
|
+
*/
|
|
153
|
+
subscribe(opts: SubscribeOptions): AsyncGenerator<NamespaceChange>;
|
|
154
|
+
/** Resolve a raw `StateCommitted` log into a namespace change, or null if the namespace slice was untouched. */
|
|
155
|
+
private toNamespaceChange;
|
|
22
156
|
getConfig(): AppConfig;
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
getSettlementRegistry(): SettlementRegistry;
|
|
157
|
+
getDataRegistry(): DataRegistryClient;
|
|
158
|
+
getStorage(): MetadataStorage;
|
|
26
159
|
getWalletClient(): WalletClient;
|
|
27
160
|
getAddress(): Hex;
|
|
28
161
|
}
|
|
29
162
|
//#endregion
|
|
30
|
-
export { Fangorn };
|
|
163
|
+
export { Fangorn, NamespaceChange, SubscribeOptions };
|