@fangorn-network/sdk 2026.7.12 → 2026.7.14

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 (72) hide show
  1. package/README.md +104 -69
  2. package/lib/cli/cli.js +26 -19
  3. package/lib/cli/index.d.ts +13 -13
  4. package/lib/config.d.ts +93 -92
  5. package/lib/contracts/data-registry/abi.d.ts +207 -35
  6. package/lib/contracts/data-registry/index.js +4 -4
  7. package/lib/contracts/index.d.ts +3 -1
  8. package/lib/contracts/index.js +3 -1
  9. package/lib/contracts/settlement-registry/abi.d.ts +47 -0
  10. package/lib/contracts/settlement-registry/abi.js +48 -0
  11. package/lib/contracts/settlement-registry/index.d.ts +25 -0
  12. package/lib/contracts/settlement-registry/index.js +40 -0
  13. package/lib/crypto/aes.d.ts +1 -8
  14. package/lib/crypto/aes.js +2 -34
  15. package/lib/crypto/encryption.d.ts +112 -26
  16. package/lib/crypto/encryption.js +105 -21
  17. package/lib/engine/car.d.ts +10 -0
  18. package/lib/engine/car.js +37 -0
  19. package/lib/engine/graph.d.ts +70 -0
  20. package/lib/engine/graph.js +73 -0
  21. package/lib/engine/index.d.ts +109 -70
  22. package/lib/engine/index.js +296 -226
  23. package/lib/engine/test-helpers.d.ts +43 -0
  24. package/lib/engine/test-helpers.js +69 -0
  25. package/lib/fangorn.d.ts +28 -25
  26. package/lib/fangorn.js +118 -83
  27. package/lib/harness/index.d.ts +4 -3
  28. package/lib/harness/index.js +9 -3
  29. package/lib/index.d.ts +3 -3
  30. package/lib/index.js +2 -2
  31. package/lib/node_modules/{.pnpm/@noble_ciphers@1.3.0/node_modules/@noble → @noble}/ciphers/esm/_polyval.js +1 -1
  32. package/lib/node_modules/{.pnpm/@noble_ciphers@1.3.0/node_modules/@noble → @noble}/ciphers/esm/aes.js +1 -1
  33. package/lib/node_modules/{.pnpm/@noble_ciphers@1.3.0/node_modules/@noble → @noble}/ciphers/esm/utils.js +1 -1
  34. package/lib/node_modules/{.pnpm/@noble_curves@1.9.7/node_modules/@noble → @noble}/curves/esm/abstract/curve.js +1 -1
  35. package/lib/node_modules/{.pnpm/@noble_curves@1.9.7/node_modules/@noble → @noble}/curves/esm/abstract/edwards.js +1 -1
  36. package/lib/node_modules/{.pnpm/@noble_curves@1.9.7/node_modules/@noble → @noble}/curves/esm/abstract/modular.js +1 -1
  37. package/lib/node_modules/{.pnpm/@noble_curves@1.9.7/node_modules/@noble → @noble}/curves/esm/abstract/montgomery.js +1 -1
  38. package/lib/node_modules/{.pnpm/@noble_curves@1.9.7/node_modules/@noble → @noble}/curves/esm/ed25519.js +1 -1
  39. package/lib/node_modules/{.pnpm/@noble_curves@1.9.7/node_modules/@noble → @noble}/curves/esm/utils.js +1 -1
  40. package/lib/providers/storage/car.js +2 -1
  41. package/lib/providers/storage/pinata.d.ts +16 -9
  42. package/lib/providers/storage/pinata.js +34 -25
  43. package/lib/providers/storage/types.d.ts +18 -8
  44. package/lib/{roles/repo → repo}/index.d.ts +1 -1
  45. package/lib/{roles/repo → repo}/index.js +1 -1
  46. package/lib/test/testbed.d.ts +9 -7
  47. package/lib/test/testbed.js +3 -2
  48. package/package.json +3 -9
  49. package/lib/ crypto/constants.d.ts +0 -4
  50. package/lib/ crypto/constants.js +0 -5
  51. package/lib/ crypto/merkle.d.ts +0 -10
  52. package/lib/ crypto/merkle.js +0 -34
  53. package/lib/ crypto/utils.d.ts +0 -1
  54. package/lib/ crypto/utils.js +0 -1
  55. package/lib/builders/a2aCardBuilder.d.ts +0 -28
  56. package/lib/builders/a2aCardBuilder.js +0 -105
  57. package/lib/engine/blockstore.d.ts +0 -24
  58. package/lib/engine/blockstore.js +0 -85
  59. package/lib/roles/index.d.ts +0 -1
  60. package/lib/roles/index.js +0 -1
  61. package/lib/test/car_smoke.d.ts +0 -1
  62. package/lib/test/car_smoke.js +0 -81
  63. package/lib/test/cleanup-embeddings-testdata.d.ts +0 -1
  64. package/lib/test/cleanup-embeddings-testdata.js +0 -75
  65. package/lib/test/index.d.ts +0 -10
  66. package/lib/test/index.js +0 -27
  67. package/lib/test/setup-embeddings-testdata.d.ts +0 -11
  68. package/lib/test/setup-embeddings-testdata.js +0 -155
  69. package/lib/utils/index.d.ts +0 -11
  70. package/lib/utils/index.js +0 -29
  71. package/lib/utils/manifest.d.ts +0 -23
  72. package/lib/utils/manifest.js +0 -77
@@ -0,0 +1,69 @@
1
+ //#region src/engine/test-helpers.ts
2
+ const ZERO_BYTES32 = "0x0000000000000000000000000000000000000000000000000000000000000000";
3
+ /** The raw 32-byte root hex a commit CID settles to on-chain (bare sha256 digest). */
4
+ const rootHex = (commitCid) => `0x${Buffer.from(commitCid.multihash.digest).toString("hex")}`;
5
+ /**
6
+ * In-memory MetadataStorage: individually-pinned blocks + opaque files, with
7
+ * write/read counters — remote writes are the publish cost driver, so tests
8
+ * assert on them directly.
9
+ */
10
+ var MemStorage = class {
11
+ blocks = /* @__PURE__ */ new Map();
12
+ files = /* @__PURE__ */ new Map();
13
+ /** Remote uploads performed (putBlock + putFile). */
14
+ writes = 0;
15
+ /** Remote fetches performed (getRawBlock + getFile). */
16
+ reads = 0;
17
+ putBlock(block) {
18
+ this.writes++;
19
+ this.blocks.set(block.cid.toString(), block.bytes);
20
+ return Promise.resolve();
21
+ }
22
+ putFile(bytes, name) {
23
+ this.writes++;
24
+ const uri = `mem://${this.files.size.toString()}/${name}`;
25
+ this.files.set(uri, bytes);
26
+ return Promise.resolve(uri);
27
+ }
28
+ getFile(uri) {
29
+ const bytes = this.files.get(uri);
30
+ if (!bytes) return Promise.reject(/* @__PURE__ */ new Error(`no such file: ${uri}`));
31
+ this.reads++;
32
+ return Promise.resolve(bytes);
33
+ }
34
+ getRawBlock(uri) {
35
+ const bytes = this.blocks.get(uri);
36
+ if (!bytes) return Promise.reject(/* @__PURE__ */ new Error(`no such block: ${uri}`));
37
+ this.reads++;
38
+ return Promise.resolve(bytes);
39
+ }
40
+ put(_data, _meta) {
41
+ return Promise.reject(/* @__PURE__ */ new Error("MemStorage.put not implemented"));
42
+ }
43
+ putMany(_items) {
44
+ return Promise.reject(/* @__PURE__ */ new Error("MemStorage.putMany not implemented"));
45
+ }
46
+ get(_uri) {
47
+ return Promise.reject(/* @__PURE__ */ new Error("MemStorage.get not implemented"));
48
+ }
49
+ delete(_uri) {
50
+ return Promise.resolve();
51
+ }
52
+ };
53
+ /** Registry stub holding one publisher head in memory (enough for the engine). */
54
+ var StubRegistry = class {
55
+ head = ZERO_BYTES32;
56
+ getNamespaceHead(_publisher) {
57
+ return Promise.resolve(this.head);
58
+ }
59
+ commitStateRoot(_oldRoot, newRoot) {
60
+ this.head = newRoot;
61
+ return Promise.resolve("0xdeadbeef");
62
+ }
63
+ asClient() {
64
+ return this;
65
+ }
66
+ };
67
+
68
+ //#endregion
69
+ export { MemStorage, StubRegistry, ZERO_BYTES32, rootHex };
package/lib/fangorn.d.ts CHANGED
@@ -44,9 +44,17 @@ declare class Fangorn {
44
44
  static create(options: FangornCreateOptions): Fangorn;
45
45
  reset(): Promise<void>;
46
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.
47
+ * Register permissive (no required fields) schemas for every tag/relation a
48
+ * staged graph uses, unless the caller has already registered stricter rules
49
+ * via `this.metagraph` directly — schema ids are free-form tags by default.
50
+ */
51
+ private registerPermissiveSchemas;
52
+ /** Stage a graph into one commit on top of `base` (engine shapes adapted from CLI shapes). */
53
+ private createCommit;
54
+ /**
55
+ * Allocates a namespace in the publisher's root map. A no-op (no on-chain tx)
56
+ * if the namespace is already initialized, so callers can call this
57
+ * unconditionally before every publish.
50
58
  */
51
59
  initRepo(repoName: string): Promise<{
52
60
  cid: undefined;
@@ -60,28 +68,23 @@ declare class Fangorn {
60
68
  alreadyInitialized: false;
61
69
  }>;
62
70
  /**
63
- * Stages a node payload against structural metadata rules inside the Pail collection context.
71
+ * Stage one vertex and settle it on-chain in a single shot.
64
72
  */
65
- upload(repoName: string, payload: any, schemaId: string): Promise<{
73
+ upload(repoName: string, payload: unknown, schemaId: string): Promise<{
66
74
  payloadCid: string;
67
75
  commitCid: string;
68
76
  txHash: `0x${string}`;
69
77
  }>;
70
78
  /**
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.
79
+ * Stages many vertices (and optionally edges between them) under one publisher
80
+ * root, instead of one tx per vertex. The whole graph is built in memory and
81
+ * persisted as ONE CAR upload plus one commit block, then settled in a single
82
+ * fast-forward tx. Edges reference vertices by the caller-supplied local `id`.
80
83
  */
81
84
  uploadBatch(repoName: string, vertices: {
82
85
  id: string;
83
86
  tag: string;
84
- payload: any;
87
+ payload: unknown;
85
88
  }[], edges?: {
86
89
  rel: string;
87
90
  from: string;
@@ -89,22 +92,20 @@ declare class Fangorn {
89
92
  }[]): Promise<{
90
93
  commitCid: string;
91
94
  txHash: `0x${string}`;
92
- vertexCids: {
93
- [k: string]: string;
94
- };
95
+ vertexCids: Record<string, string>;
95
96
  }>;
96
97
  /**
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.
98
+ * Build a new commit (no on-chain tx) that stages vertices/edges into
99
+ * `namespace` on top of `parent` (a commit CID string, or undefined for a
100
+ * root commit). The commit and its CAR are uploaded to storage, so a later
101
+ * `push` — even in a separate process — can settle it.
101
102
  */
102
103
  commit(opts: {
103
104
  namespace: string;
104
105
  vertices?: {
105
106
  id: string;
106
107
  tag: string;
107
- payload: any;
108
+ payload: unknown;
108
109
  }[];
109
110
  edges?: {
110
111
  rel: string;
@@ -113,10 +114,12 @@ declare class Fangorn {
113
114
  }[];
114
115
  parent?: string;
115
116
  message: string;
117
+ /** Snapshot semantics: the staged graph replaces the namespace's previous contents. */
118
+ replace?: boolean;
116
119
  }): Promise<{
117
120
  commitCid: string;
118
121
  parents: string[];
119
- pailRoot: string;
122
+ root: string;
120
123
  vertexCids: Record<string, string>;
121
124
  }>;
122
125
  /** Settle a local commit as the on-chain head (fast-forward unless `force`). */
@@ -134,7 +137,7 @@ declare class Fangorn {
134
137
  parents: string[];
135
138
  timestamp: number;
136
139
  message: string;
137
- pailRoot: string;
140
+ root: string;
138
141
  }>;
139
142
  /** Show a commit and what it changed vs. its first parent. */
140
143
  show(commitCid: string): Promise<CommitDiff>;
package/lib/fangorn.js CHANGED
@@ -1,7 +1,6 @@
1
1
  import { FangornConfig } from "./config.js";
2
2
  import { PinataBackend } from "./providers/storage/pinata.js";
3
- import { FangornEngine, MetagraphRegistry } from "./engine/index.js";
4
- import { StorageBlockstoreAdapter } from "./engine/blockstore.js";
3
+ import { FangornEngine, MetagraphRegistry, assertValidNamespace } from "./engine/index.js";
5
4
  import { DataRegistryClient } from "./contracts/data-registry/index.js";
6
5
  import { createPublicClient, createWalletClient, http } from "viem";
7
6
  import { privateKeyToAccount } from "viem/accounts";
@@ -27,14 +26,13 @@ var Fangorn = class Fangorn {
27
26
  get engine() {
28
27
  if (!this.ctx.metadataStorage) throw new Error("fangorn.engine requires storage configurations. Pass { pinata: { ... } } to Fangorn.create()");
29
28
  if (!this._engine) {
30
- const blockstoreAdapter = new StorageBlockstoreAdapter(this.ctx.metadataStorage);
31
29
  this._metagraph = new MetagraphRegistry();
32
- this._engine = new FangornEngine(blockstoreAdapter, this._metagraph, this.ctx.dataRegistry);
30
+ this._engine = new FangornEngine(this.ctx.metadataStorage, this._metagraph, this.ctx.dataRegistry);
33
31
  }
34
32
  return this._engine;
35
33
  }
36
34
  get metagraph() {
37
- this.engine;
35
+ if (!this._metagraph) throw new Error("MetagraphRegistry has not been initialized. Ensure the client is connected.");
38
36
  return this._metagraph;
39
37
  }
40
38
  static create(options) {
@@ -62,11 +60,60 @@ var Fangorn = class Fangorn {
62
60
  await registry.commitStateRoot(currentRoot, ZERO_BYTES32);
63
61
  }
64
62
  /**
65
- * Allocates a namespace key directly within the transactional Pail index tree.
66
- * A no-op (no on-chain tx) if the namespace is already initialized, so callers
67
- * can call this unconditionally before every publish.
63
+ * Register permissive (no required fields) schemas for every tag/relation a
64
+ * staged graph uses, unless the caller has already registered stricter rules
65
+ * via `this.metagraph` directly — schema ids are free-form tags by default.
66
+ */
67
+ registerPermissiveSchemas(repoName, vertices, edges) {
68
+ const tagOf = /* @__PURE__ */ new Map();
69
+ for (const v of vertices) {
70
+ tagOf.set(v.id, v.tag);
71
+ if (!this.metagraph.hasVertexSchema(repoName, v.tag)) this.metagraph.registerVertex(repoName, {
72
+ id: v.tag,
73
+ requiredFields: []
74
+ });
75
+ }
76
+ for (const e of edges) {
77
+ const sourceTag = tagOf.get(e.from);
78
+ const targetTag = tagOf.get(e.to);
79
+ if (!sourceTag || !targetTag) continue;
80
+ if (!this.metagraph.hasEdgeSchema(repoName, sourceTag, e.rel, targetTag)) this.metagraph.registerEdge(repoName, {
81
+ sourceSchema: sourceTag,
82
+ relation: e.rel,
83
+ targetSchema: targetTag
84
+ });
85
+ }
86
+ }
87
+ /** Stage a graph into one commit on top of `base` (engine shapes adapted from CLI shapes). */
88
+ createCommit(opts) {
89
+ this.registerPermissiveSchemas(opts.namespace, opts.vertices, opts.edges);
90
+ return this.engine.createCommit({
91
+ namespace: opts.namespace,
92
+ base: opts.base,
93
+ vertices: opts.vertices.map((v) => {
94
+ const safePayload = v.payload && typeof v.payload === "object" && !Array.isArray(v.payload) ? v.payload : { value: v.payload };
95
+ return {
96
+ id: v.id,
97
+ schemaId: v.tag,
98
+ payload: safePayload
99
+ };
100
+ }),
101
+ edges: opts.edges.map((e) => ({
102
+ relation: e.rel,
103
+ from: e.from,
104
+ to: e.to
105
+ })),
106
+ message: opts.message,
107
+ replace: opts.replace
108
+ });
109
+ }
110
+ /**
111
+ * Allocates a namespace in the publisher's root map. A no-op (no on-chain tx)
112
+ * if the namespace is already initialized, so callers can call this
113
+ * unconditionally before every publish.
68
114
  */
69
115
  async initRepo(repoName) {
116
+ assertValidNamespace(repoName);
70
117
  const publisher = this.getAddress();
71
118
  if (await this.engine.namespaceExists(repoName, publisher)) return {
72
119
  cid: void 0,
@@ -74,9 +121,14 @@ var Fangorn = class Fangorn {
74
121
  txHash: void 0,
75
122
  alreadyInitialized: true
76
123
  };
77
- const { batch, baseCommitCid } = await this.engine.createBatch(publisher);
78
- await batch.put(`${repoName}/sys/init`, "initialized");
79
- const { commitCid } = await this.engine.sealBatch(batch, baseCommitCid ? [baseCommitCid] : [], `Initialize repository workspace: ${repoName}`);
124
+ const head = await this.engine.resolveHeadCommit(publisher);
125
+ const { commitCid } = await this.createCommit({
126
+ namespace: repoName,
127
+ base: head,
128
+ vertices: [],
129
+ edges: [],
130
+ message: `Initialize repository workspace: ${repoName}`
131
+ });
80
132
  const { txHash } = await this.engine.pushCommit(publisher, commitCid);
81
133
  return {
82
134
  cid: commitCid.toString(),
@@ -86,98 +138,78 @@ var Fangorn = class Fangorn {
86
138
  };
87
139
  }
88
140
  /**
89
- * Stages a node payload against structural metadata rules inside the Pail collection context.
141
+ * Stage one vertex and settle it on-chain in a single shot.
90
142
  */
91
143
  async upload(repoName, payload, schemaId) {
92
144
  const publisher = this.getAddress();
93
- const { batch, contractHeadHex, baseCommitCid } = await this.engine.createBatch(publisher);
94
- if (contractHeadHex === ZERO_BYTES32) throw new Error(`Repository '${repoName}' does not exist. Call initRepo() prior to uploading.`);
95
- if (!this.metagraph.hasVertexSchema(repoName, schemaId)) this.metagraph.registerVertex(repoName, {
96
- id: schemaId,
97
- requiredFields: []
145
+ const head = await this.engine.resolveHeadCommit(publisher);
146
+ if (!head) throw new Error(`Repository '${repoName}' does not exist. Call initRepo() prior to uploading.`);
147
+ const { commitCid, vertexCids } = await this.createCommit({
148
+ namespace: repoName,
149
+ base: head,
150
+ vertices: [{
151
+ id: "v0",
152
+ tag: schemaId,
153
+ payload
154
+ }],
155
+ edges: [],
156
+ message: `Upload to namespace ${repoName} under schema ${schemaId}`
98
157
  });
99
- const vertexCidString = await this.engine.stageVertex(batch, repoName, schemaId, payload);
100
- const { commitCid } = await this.engine.sealBatch(batch, baseCommitCid ? [baseCommitCid] : [], `Upload to namespace ${repoName} under schema ${schemaId}`);
101
158
  const { txHash } = await this.engine.pushCommit(publisher, commitCid);
102
159
  return {
103
- payloadCid: vertexCidString,
160
+ payloadCid: vertexCids.v0,
104
161
  commitCid: commitCid.toString(),
105
162
  txHash
106
163
  };
107
164
  }
108
165
  /**
109
- * Stages vertices (and edges resolved by local id) into a namespace against an
110
- * already-open batch. Shared by the immediate `uploadBatch` path and the git
111
- * `commit` path. Returns the local-id → staged-CID map.
112
- */
113
- async stageGraph(batch, repoName, vertices, edges) {
114
- const idToCid = /* @__PURE__ */ new Map();
115
- const idToTag = /* @__PURE__ */ new Map();
116
- for (const v of vertices) {
117
- if (!this.metagraph.hasVertexSchema(repoName, v.tag)) this.metagraph.registerVertex(repoName, {
118
- id: v.tag,
119
- requiredFields: []
120
- });
121
- const cid = await this.engine.stageVertex(batch, repoName, v.tag, v.payload);
122
- idToCid.set(v.id, cid);
123
- idToTag.set(v.id, v.tag);
124
- }
125
- for (const e of edges) {
126
- const sourceCid = idToCid.get(e.from);
127
- const targetCid = idToCid.get(e.to);
128
- const sourceTag = idToTag.get(e.from);
129
- const targetTag = idToTag.get(e.to);
130
- if (!sourceCid || !targetCid || !sourceTag || !targetTag) throw new Error(`edge references unknown local id (from=${e.from}, to=${e.to})`);
131
- if (!this.metagraph.hasEdgeSchema(repoName, sourceTag, e.rel, targetTag)) this.metagraph.registerEdge(repoName, {
132
- sourceSchema: sourceTag,
133
- relation: e.rel,
134
- targetSchema: targetTag
135
- });
136
- await this.engine.stageEdge(batch, repoName, {
137
- sourceCid,
138
- relation: e.rel,
139
- targetCid
140
- }, sourceTag, targetTag);
141
- }
142
- return idToCid;
143
- }
144
- /**
145
- * Stages many vertices (and optionally edges between them) in a single
146
- * on-chain commit, instead of one tx per vertex. Edges reference vertices by
147
- * the caller-supplied local `id`, resolved to their staged CID before staging.
166
+ * Stages many vertices (and optionally edges between them) under one publisher
167
+ * root, instead of one tx per vertex. The whole graph is built in memory and
168
+ * persisted as ONE CAR upload plus one commit block, then settled in a single
169
+ * fast-forward tx. Edges reference vertices by the caller-supplied local `id`.
148
170
  */
149
171
  async uploadBatch(repoName, vertices, edges = []) {
172
+ assertValidNamespace(repoName);
173
+ if (vertices.length === 0 && edges.length === 0) throw new Error("uploadBatch requires at least one vertex or edge");
150
174
  const publisher = this.getAddress();
151
- const { batch, contractHeadHex, baseCommitCid } = await this.engine.createBatch(publisher);
152
- if (contractHeadHex === ZERO_BYTES32) throw new Error(`Repository '${repoName}' does not exist. Call initRepo() prior to uploading.`);
153
- const idToCid = await this.stageGraph(batch, repoName, vertices, edges);
154
- const { commitCid } = await this.engine.sealBatch(batch, baseCommitCid ? [baseCommitCid] : [], `Batch upload to namespace ${repoName}: ${vertices.length.toString()} vertices, ${edges.length.toString()} edges`);
175
+ const head = await this.engine.resolveHeadCommit(publisher);
176
+ if (!head) throw new Error(`Repository '${repoName}' does not exist. Call initRepo() prior to uploading.`);
177
+ const { commitCid, vertexCids } = await this.createCommit({
178
+ namespace: repoName,
179
+ base: head,
180
+ vertices,
181
+ edges,
182
+ message: `Batch upload to namespace ${repoName}`
183
+ });
155
184
  const { txHash } = await this.engine.pushCommit(publisher, commitCid);
156
185
  return {
157
186
  commitCid: commitCid.toString(),
158
187
  txHash,
159
- vertexCids: Object.fromEntries(idToCid)
188
+ vertexCids
160
189
  };
161
190
  }
162
191
  /**
163
- * Build a new commit locally (no on-chain tx) that stages vertices/edges into
164
- * `namespace` on top of `parent` (a commit CID string, or undefined for a root
165
- * commit). Blocks are flushed to storage so a later `push` — even in a separate
166
- * process — can settle it.
192
+ * Build a new commit (no on-chain tx) that stages vertices/edges into
193
+ * `namespace` on top of `parent` (a commit CID string, or undefined for a
194
+ * root commit). The commit and its CAR are uploaded to storage, so a later
195
+ * `push` — even in a separate process — can settle it.
167
196
  */
168
197
  async commit(opts) {
198
+ assertValidNamespace(opts.namespace);
169
199
  const parentCid = opts.parent ? CID.parse(opts.parent) : null;
170
- const basePailRoot = parentCid ? (await this.engine.getCommit(parentCid)).pailRoot : null;
171
- const batch = await this.engine.openBatch(basePailRoot);
172
- if (!parentCid) await batch.put(`${opts.namespace}/sys/init`, "initialized");
173
- const idToCid = await this.stageGraph(batch, opts.namespace, opts.vertices ?? [], opts.edges ?? []);
174
- const { commitCid, pailRoot } = await this.engine.sealBatch(batch, parentCid ? [parentCid] : [], opts.message);
175
- await this.engine.flush();
200
+ const { commitCid, root, vertexCids } = await this.createCommit({
201
+ namespace: opts.namespace,
202
+ base: parentCid,
203
+ vertices: opts.vertices ?? [],
204
+ edges: opts.edges ?? [],
205
+ message: opts.message,
206
+ replace: opts.replace
207
+ });
176
208
  return {
177
209
  commitCid: commitCid.toString(),
178
210
  parents: parentCid ? [parentCid.toString()] : [],
179
- pailRoot: pailRoot.toString(),
180
- vertexCids: Object.fromEntries(idToCid)
211
+ root: root.toString(),
212
+ vertexCids
181
213
  };
182
214
  }
183
215
  /** Settle a local commit as the on-chain head (fast-forward unless `force`). */
@@ -200,7 +232,7 @@ var Fangorn = class Fangorn {
200
232
  parents: commit.parents.map((c) => c.toString()),
201
233
  timestamp: commit.timestamp,
202
234
  message: commit.message,
203
- pailRoot: commit.pailRoot.toString()
235
+ root: commit.root.toString()
204
236
  };
205
237
  }
206
238
  /** Show a commit and what it changed vs. its first parent. */
@@ -228,8 +260,10 @@ var Fangorn = class Fangorn {
228
260
  const seen = /* @__PURE__ */ new Set();
229
261
  const buffer = [];
230
262
  let wake = null;
231
- let failure = null;
232
- let stopped = false;
263
+ const subState = {
264
+ failure: null,
265
+ stopped: false
266
+ };
233
267
  const signal = () => {
234
268
  const w = wake;
235
269
  wake = null;
@@ -239,11 +273,11 @@ var Fangorn = class Fangorn {
239
273
  buffer.push(log);
240
274
  signal();
241
275
  }, (err) => {
242
- failure = err;
276
+ subState.failure = err;
243
277
  signal();
244
278
  }, opts.pollingInterval);
245
279
  const onAbort = () => {
246
- stopped = true;
280
+ subState.stopped = true;
247
281
  signal();
248
282
  };
249
283
  opts.signal?.addEventListener("abort", onAbort);
@@ -254,8 +288,8 @@ var Fangorn = class Fangorn {
254
288
  const change = await this.toNamespaceChange(log, ns, owner);
255
289
  if (change) yield change;
256
290
  }
257
- while (!stopped) {
258
- if (failure) throw failure;
291
+ while (!subState.stopped) {
292
+ if (subState.failure) throw subState.failure;
259
293
  if (buffer.length === 0) {
260
294
  await new Promise((res) => {
261
295
  wake = res;
@@ -263,6 +297,7 @@ var Fangorn = class Fangorn {
263
297
  continue;
264
298
  }
265
299
  const log = buffer.shift();
300
+ if (!log) continue;
266
301
  if (seen.has(log.logId)) continue;
267
302
  seen.add(log.logId);
268
303
  const change = await this.toNamespaceChange(log, ns, owner);
@@ -21,7 +21,7 @@ interface ProcessorResult {
21
21
  /** The entity type/tag for the graph vertex (defaults to "asset") */
22
22
  tag?: string;
23
23
  /** Custom metadata object attached to the vertex */
24
- payload?: Record<string, any>;
24
+ payload?: Record<string, unknown>;
25
25
  /** An array of target vertex IDs that this file links to */
26
26
  links?: string[];
27
27
  }
@@ -33,7 +33,7 @@ interface BuildAssetGraphOptions {
33
33
  interface Vertex {
34
34
  id: string;
35
35
  tag: string;
36
- payload: Record<string, any>;
36
+ payload: Record<string, unknown>;
37
37
  }
38
38
  interface Edge {
39
39
  rel: string;
@@ -53,5 +53,6 @@ declare function buildAssetGraph(dir: string, options?: BuildAssetGraphOptions):
53
53
  * Utility helper to scan markdown strings for standard markdown links or wikilinks.
54
54
  */
55
55
  declare function extractMarkdownLinks(content: string): string[];
56
+ declare const buildMarkdownGraph: (dir: string) => CommitFileGraph;
56
57
  //#endregion
57
- export { AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, Edge, FileFacade, ProcessorResult, Vertex, buildAssetGraph, extractMarkdownLinks };
58
+ export { AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, Edge, FileFacade, ProcessorResult, Vertex, buildAssetGraph, buildMarkdownGraph, extractMarkdownLinks };
@@ -16,7 +16,6 @@ function buildAssetGraph(dir, options = {}) {
16
16
  for (const f of rawFiles) {
17
17
  const ext = extname(f).toLowerCase();
18
18
  const processor = processors[ext];
19
- if (!processor) continue;
20
19
  const fromId = getId(f);
21
20
  const fullPath = join(dir, f);
22
21
  const fileFacade = {
@@ -57,11 +56,18 @@ function extractMarkdownLinks(content) {
57
56
  const links = [];
58
57
  const convertToId = (str) => basename(str, extname(str));
59
58
  for (const match of content.matchAll(LINK_REGEX)) {
60
- const rawTarget = match[1] ?? match[2];
59
+ const rawTarget = match[1];
61
60
  if (rawTarget) links.push(convertToId(rawTarget));
62
61
  }
63
62
  return links;
64
63
  }
64
+ const buildMarkdownGraph = (dir) => {
65
+ return buildAssetGraph(dir, { processors: { ".md": (file) => ({
66
+ tag: "doc",
67
+ payload: { content: file.readText() },
68
+ links: extractMarkdownLinks(file.readText())
69
+ }) } });
70
+ };
65
71
 
66
72
  //#endregion
67
- export { buildAssetGraph, extractMarkdownLinks };
73
+ export { buildAssetGraph, buildMarkdownGraph, extractMarkdownLinks };
package/lib/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { AppConfig, FangornConfig, SupportedNetworks } from "./config.js";
2
+ import { Fangorn, NamespaceChange, SubscribeOptions } from "./fangorn.js";
3
+ import { AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, Edge, FileFacade, ProcessorResult, Vertex, buildAssetGraph, buildMarkdownGraph, extractMarkdownLinks } from "./harness/index.js";
2
4
  import { PinataBackend } from "./providers/storage/pinata.js";
3
5
  import { deserialize, retrieveByCid, serialize } from "./providers/storage/utils.js";
4
- import { Fangorn, NamespaceChange, SubscribeOptions } from "./fangorn.js";
5
- import { addressToBytes32Array, computeSchemaId, fieldToHex, hexToBytes32Array, hexToField, stringToBytes32Array } from "./utils/index.js";
6
- export { AppConfig, Fangorn, FangornConfig, NamespaceChange, PinataBackend, SubscribeOptions, SupportedNetworks, addressToBytes32Array, computeSchemaId, deserialize, fieldToHex, hexToBytes32Array, hexToField, retrieveByCid, serialize, stringToBytes32Array };
6
+ export { AppConfig, AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, Edge, Fangorn, FangornConfig, FileFacade, NamespaceChange, PinataBackend, ProcessorResult, SubscribeOptions, SupportedNetworks, Vertex, buildAssetGraph, buildMarkdownGraph, deserialize, extractMarkdownLinks, retrieveByCid, serialize };
package/lib/index.js CHANGED
@@ -2,6 +2,6 @@ import { FangornConfig, SupportedNetworks } from "./config.js";
2
2
  import { deserialize, retrieveByCid, serialize } from "./providers/storage/utils.js";
3
3
  import { PinataBackend } from "./providers/storage/pinata.js";
4
4
  import { Fangorn } from "./fangorn.js";
5
- import { addressToBytes32Array, computeSchemaId, fieldToHex, hexToBytes32Array, hexToField, stringToBytes32Array } from "./utils/index.js";
5
+ import { buildAssetGraph, buildMarkdownGraph, extractMarkdownLinks } from "./harness/index.js";
6
6
 
7
- export { Fangorn, FangornConfig, PinataBackend, SupportedNetworks, addressToBytes32Array, computeSchemaId, deserialize, fieldToHex, hexToBytes32Array, hexToField, retrieveByCid, serialize, stringToBytes32Array };
7
+ export { Fangorn, FangornConfig, PinataBackend, SupportedNetworks, buildAssetGraph, buildMarkdownGraph, deserialize, extractMarkdownLinks, retrieveByCid, serialize };
@@ -1,6 +1,6 @@
1
1
  import { abytes, aexists, aoutput, clean, copyBytes, createView, toBytes, u32 } from "./utils.js";
2
2
 
3
- //#region node_modules/.pnpm/@noble+ciphers@1.3.0/node_modules/@noble/ciphers/esm/_polyval.js
3
+ //#region node_modules/@noble/ciphers/esm/_polyval.js
4
4
  /**
5
5
  * GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV.
6
6
  *
@@ -1,7 +1,7 @@
1
1
  import { abytes, clean, copyBytes, createView, equalBytes, getOutput, isAligned32, setBigUint64, u32, u64Lengths, u8, wrapCipher } from "./utils.js";
2
2
  import { ghash } from "./_polyval.js";
3
3
 
4
- //#region node_modules/.pnpm/@noble+ciphers@1.3.0/node_modules/@noble/ciphers/esm/aes.js
4
+ //#region node_modules/@noble/ciphers/esm/aes.js
5
5
  /**
6
6
  * [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard)
7
7
  * a.k.a. Advanced Encryption Standard
@@ -1,4 +1,4 @@
1
- //#region node_modules/.pnpm/@noble+ciphers@1.3.0/node_modules/@noble/ciphers/esm/utils.js
1
+ //#region node_modules/@noble/ciphers/esm/utils.js
2
2
  /**
3
3
  * Utilities for hex, bytes, CSPRNG.
4
4
  * @module
@@ -1,7 +1,7 @@
1
1
  import { bitLen, bitMask } from "../utils.js";
2
2
  import { Field, FpInvertBatch, validateField } from "./modular.js";
3
3
 
4
- //#region node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/curve.js
4
+ //#region node_modules/@noble/curves/esm/abstract/curve.js
5
5
  /**
6
6
  * Methods for elliptic curve multiplication by scalars.
7
7
  * Contains wNAF, pippenger.
@@ -2,7 +2,7 @@ import { _abool2, _abytes2, _validateObject, aInRange, bytesToHex, bytesToNumber
2
2
  import { Field } from "./modular.js";
3
3
  import { _createCurveFields, normalizeZ, pippenger, wNAF } from "./curve.js";
4
4
 
5
- //#region node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/edwards.js
5
+ //#region node_modules/@noble/curves/esm/abstract/edwards.js
6
6
  /**
7
7
  * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².
8
8
  * For design rationale of types / exports, see weierstrass module documentation.
@@ -1,6 +1,6 @@
1
1
  import { _validateObject, anumber, bitMask, bytesToNumberBE, bytesToNumberLE, numberToBytesBE, numberToBytesLE } from "../utils.js";
2
2
 
3
- //#region node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/modular.js
3
+ //#region node_modules/@noble/curves/esm/abstract/modular.js
4
4
  /**
5
5
  * Utils for modular division and fields.
6
6
  * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
@@ -1,7 +1,7 @@
1
1
  import { _validateObject, aInRange, abytes, bytesToNumberLE, ensureBytes, numberToBytesLE, randomBytes } from "../utils.js";
2
2
  import { mod } from "./modular.js";
3
3
 
4
- //#region node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/montgomery.js
4
+ //#region node_modules/@noble/curves/esm/abstract/montgomery.js
5
5
  /**
6
6
  * Montgomery curve methods. It's not really whole montgomery curve,
7
7
  * just bunch of very specific methods for X25519 / X448 from
@@ -6,7 +6,7 @@ import { montgomery } from "./abstract/montgomery.js";
6
6
  import { sha512 } from "@noble/hashes/sha2.js";
7
7
  import { abytes } from "@noble/hashes/utils.js";
8
8
 
9
- //#region node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/ed25519.js
9
+ //#region node_modules/@noble/curves/esm/ed25519.js
10
10
  /**
11
11
  * ed25519 Twisted Edwards curve with following addons:
12
12
  * - X25519 ECDH
@@ -1,6 +1,6 @@
1
1
  import { abytes, abytes as abytes$1, anumber, bytesToHex, bytesToHex as bytesToHex$1, concatBytes as concatBytes$1, hexToBytes, isBytes, isBytes as isBytes$1, randomBytes } from "@noble/hashes/utils.js";
2
2
 
3
- //#region node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/utils.js
3
+ //#region node_modules/@noble/curves/esm/utils.js
4
4
  /**
5
5
  * Hex, bytes and number utilities.
6
6
  * @module