@fangorn-network/sdk 2026.6.16 → 2026.7.1-2.0

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 (105) hide show
  1. package/README.md +210 -266
  2. package/lib/cli/cli.d.ts +0 -0
  3. package/lib/cli/cli.js +261 -167
  4. package/lib/cli/index.d.ts +13 -651
  5. package/lib/config.d.ts +137 -792
  6. package/lib/config.js +6 -22
  7. package/lib/contracts/data-registry/abi.d.ts +38 -0
  8. package/lib/contracts/data-registry/abi.js +237 -0
  9. package/lib/contracts/data-registry/index.d.ts +81 -0
  10. package/lib/contracts/data-registry/index.js +184 -0
  11. package/lib/contracts/index.d.ts +3 -0
  12. package/lib/contracts/index.js +4 -0
  13. package/lib/crypto/aes.d.ts +26 -0
  14. package/lib/crypto/aes.js +58 -0
  15. package/lib/crypto/encryption.d.ts +53 -0
  16. package/lib/crypto/encryption.js +82 -0
  17. package/lib/{modules/encryption → crypto}/rand.d.ts +1 -1
  18. package/lib/{modules/encryption → crypto}/rand.js +1 -1
  19. package/lib/{modules/encryption → crypto}/types.d.ts +1 -1
  20. package/lib/engine/blockstore.d.ts +24 -0
  21. package/lib/engine/blockstore.js +85 -0
  22. package/lib/engine/index.d.ts +180 -0
  23. package/lib/engine/index.js +367 -0
  24. package/lib/fangorn.d.ts +149 -16
  25. package/lib/fangorn.js +256 -37
  26. package/lib/harness/examples/hackmd/build-markdown-graph.js +17 -0
  27. package/lib/harness/index.d.ts +57 -0
  28. package/lib/harness/index.js +67 -0
  29. package/lib/index.d.ts +2 -2
  30. package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/_polyval.js +218 -0
  31. package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/aes.js +261 -0
  32. package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/utils.js +156 -0
  33. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/curve.js +299 -0
  34. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/edwards.js +532 -0
  35. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/modular.js +344 -0
  36. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/montgomery.js +137 -0
  37. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/ed25519.js +262 -0
  38. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/utils.js +150 -0
  39. package/lib/providers/storage/car.d.ts +36 -0
  40. package/lib/providers/storage/car.js +80 -0
  41. package/lib/providers/storage/pinata.d.ts +29 -1
  42. package/lib/providers/storage/pinata.js +135 -20
  43. package/lib/providers/storage/types.d.ts +25 -18
  44. package/lib/roles/repo/index.d.ts +56 -0
  45. package/lib/roles/repo/index.js +73 -0
  46. package/lib/test/car_smoke.d.ts +1 -0
  47. package/lib/test/car_smoke.js +81 -0
  48. package/lib/test/cleanup-embeddings-testdata.js +9 -38
  49. package/lib/test/setup-embeddings-testdata.d.ts +4 -6
  50. package/lib/test/setup-embeddings-testdata.js +40 -94
  51. package/lib/test/testbed.d.ts +35 -32
  52. package/lib/test/testbed.js +48 -138
  53. package/lib/types/index.d.ts +3 -19
  54. package/lib/utils/manifest.d.ts +23 -0
  55. package/lib/utils/manifest.js +77 -0
  56. package/package.json +99 -81
  57. package/lib/modules/encryption/actions.d.ts +0 -4
  58. package/lib/modules/encryption/actions.js +0 -18
  59. package/lib/modules/encryption/aes.d.ts +0 -10
  60. package/lib/modules/encryption/aes.js +0 -51
  61. package/lib/registries/datasource-registry/abi.d.ts +0 -186
  62. package/lib/registries/datasource-registry/abi.js +0 -229
  63. package/lib/registries/datasource-registry/index.d.ts +0 -39
  64. package/lib/registries/datasource-registry/index.js +0 -158
  65. package/lib/registries/index.d.ts +0 -3
  66. package/lib/registries/index.js +0 -4
  67. package/lib/registries/schema-registry/abi.d.ts +0 -218
  68. package/lib/registries/schema-registry/abi.js +0 -246
  69. package/lib/registries/schema-registry/index.d.ts +0 -34
  70. package/lib/registries/schema-registry/index.js +0 -179
  71. package/lib/registries/settlement-registry/abi.d.ts +0 -218
  72. package/lib/registries/settlement-registry/abi.js +0 -259
  73. package/lib/registries/settlement-registry/index.d.ts +0 -63
  74. package/lib/registries/settlement-registry/index.js +0 -325
  75. package/lib/registries/settlement-registry/types.d.ts +0 -54
  76. package/lib/registries/settlement-registry/types.js +0 -1
  77. package/lib/roles/consumer/index.d.ts +0 -39
  78. package/lib/roles/consumer/index.js +0 -150
  79. package/lib/roles/consumer/types.d.ts +0 -47
  80. package/lib/roles/consumer/types.js +0 -1
  81. package/lib/roles/publisher/builders/bundle.d.ts +0 -32
  82. package/lib/roles/publisher/builders/bundle.js +0 -137
  83. package/lib/roles/publisher/builders/record-set.d.ts +0 -17
  84. package/lib/roles/publisher/builders/record-set.js +0 -55
  85. package/lib/roles/publisher/builders/types.d.ts +0 -38
  86. package/lib/roles/publisher/builders/types.js +0 -1
  87. package/lib/roles/publisher/builders/utils.d.ts +0 -9
  88. package/lib/roles/publisher/builders/utils.js +0 -29
  89. package/lib/roles/publisher/encryption.d.ts +0 -18
  90. package/lib/roles/publisher/encryption.js +0 -38
  91. package/lib/roles/publisher/index.d.ts +0 -68
  92. package/lib/roles/publisher/index.js +0 -179
  93. package/lib/roles/publisher/types.d.ts +0 -114
  94. package/lib/roles/publisher/types.js +0 -1
  95. package/lib/roles/schema/index.d.ts +0 -44
  96. package/lib/roles/schema/index.js +0 -127
  97. package/lib/roles/schema/types.d.ts +0 -113
  98. package/lib/roles/schema/types.js +0 -1
  99. package/lib/roles/schema/validate.d.ts +0 -9
  100. package/lib/roles/schema/validate.js +0 -128
  101. package/lib/test/publish_mb_bundle.js +0 -296
  102. /package/lib/{modules/encryption/index.d.ts → contracts/data-registry/test.d.ts} +0 -0
  103. /package/lib/{modules/encryption/index.js → contracts/data-registry/test.js} +0 -0
  104. /package/lib/{modules/encryption → crypto}/types.js +0 -0
  105. /package/lib/{test/publish_mb_bundle.d.ts → harness/examples/hackmd/build-markdown-graph.d.ts} +0 -0
@@ -1,39 +0,0 @@
1
- import { DataSourceRegistry } from "../../registries/datasource-registry/index.js";
2
- import { ManifestEntry } from "../publisher/types.js";
3
- import { PrepareSettleParams, PrepareSettleResult, TransferWithAuthParams, TransferWithAuthPayload } from "../../registries/settlement-registry/types.js";
4
- import { SettlementRegistry } from "../../registries/settlement-registry/index.js";
5
- import { ClaimParams, ClaimResult, FetchParams, FetchResult, PurchaseParams, PurchaseResult } from "./types.js";
6
- import { Address, Hex, WalletClient } from "viem";
7
- import { Identity } from "@semaphore-protocol/identity";
8
-
9
- //#region src/roles/consumer/index.d.ts
10
- declare class ConsumerRole {
11
- private readonly dataSourceRegistry;
12
- private readonly settlementRegistry;
13
- constructor(dataSourceRegistry: DataSourceRegistry, settlementRegistry: SettlementRegistry);
14
- prepareRegister(params: TransferWithAuthParams): Promise<TransferWithAuthPayload>;
15
- prepareSettle(params: PrepareSettleParams): Promise<PrepareSettleResult>;
16
- register(params: PurchaseParams): Promise<PurchaseResult>;
17
- claim(params: ClaimParams): Promise<ClaimResult>;
18
- /**
19
- * Fetch a handle field's content from the Fangorn access worker.
20
- *
21
- * The consumer signs { nullifier, resourceId, objectKey, timestamp } with
22
- * their stealth address private key. The worker recovers the address,
23
- * verifies is_settled() on-chain, and proxies the R2 bytes.
24
- *
25
- * Plain fields can be read freely via getEntry() without any of this.
26
- */
27
- fetch(params: FetchParams): Promise<FetchResult>;
28
- checkManifestExists(who: Address, schemaId: Hex, name: string): Promise<boolean>;
29
- getEntry(owner: Address, schemaId: Hex, name: string, gateway?: string): Promise<ManifestEntry | undefined>;
30
- /**
31
- * Resolves the handle URI for a specific field
32
- * and fetches it via the worker in one call.
33
- */
34
- fetchField(owner: Address, schemaId: Hex, name: string, field: string, nullifier: string, walletClient: WalletClient): Promise<FetchResult>;
35
- isRegistered(owner: Address, schemaId: Hex, name: string, identity: Identity): Promise<boolean>;
36
- private deriveResourceId;
37
- }
38
- //#endregion
39
- export { ConsumerRole };
@@ -1,150 +0,0 @@
1
- import { DataSourceRegistry } from "../../registries/datasource-registry/index.js";
2
- import { PinataBackend } from "../../providers/storage/pinata.js";
3
- import "../../providers/storage/index.js";
4
- import { encodePacked, keccak256 } from "viem";
5
-
6
- //#region src/roles/consumer/index.ts
7
- var ConsumerRole = class {
8
- constructor(dataSourceRegistry, settlementRegistry) {
9
- this.dataSourceRegistry = dataSourceRegistry;
10
- this.settlementRegistry = settlementRegistry;
11
- }
12
- async prepareRegister(params) {
13
- return this.settlementRegistry.prepareTransferWithAuth(params);
14
- }
15
- async prepareSettle(params) {
16
- return this.settlementRegistry.prepareSettle(params);
17
- }
18
- async register(params) {
19
- const resourceId = this.deriveResourceId(params.owner, params.schemaId, params.name);
20
- return {
21
- txHash: await this.settlementRegistry.register({
22
- resourceId,
23
- identityCommitment: params.identityCommitment,
24
- relayerPrivateKey: params.relayerPrivateKey,
25
- preparedRegister: params.preparedRegister
26
- }),
27
- resourceId
28
- };
29
- }
30
- async claim(params) {
31
- const resourceId = this.deriveResourceId(params.owner, params.schemaId, params.name);
32
- const { hash, nullifier } = await this.settlementRegistry.settle({
33
- relayerPrivateKey: params.relayerPrivateKey,
34
- preparedSettle: params.preparedSettle
35
- });
36
- return {
37
- txHash: hash,
38
- nullifier,
39
- resourceId
40
- };
41
- }
42
- /**
43
- * Fetch a handle field's content from the Fangorn access worker.
44
- *
45
- * The consumer signs { nullifier, resourceId, objectKey, timestamp } with
46
- * their stealth address private key. The worker recovers the address,
47
- * verifies is_settled() on-chain, and proxies the R2 bytes.
48
- *
49
- * Plain fields can be read freely via getEntry() without any of this.
50
- */
51
- async fetch(params) {
52
- const { nullifier, resourceId, objectKey, workerUrl, walletClient } = params;
53
- const timestamp = Math.floor(Date.now() / 1e3);
54
- const msgHash = keccak256(encodePacked([
55
- "uint256",
56
- "bytes32",
57
- "string",
58
- "uint64"
59
- ], [
60
- BigInt(nullifier),
61
- resourceId,
62
- objectKey,
63
- BigInt(timestamp)
64
- ]));
65
- const account = walletClient.account;
66
- if (!account) throw new Error("walletClient account must be defined");
67
- const signature = await walletClient.signMessage({
68
- message: { raw: msgHash },
69
- account
70
- });
71
- const res = await globalThis.fetch(`${workerUrl}/access`, {
72
- method: "POST",
73
- headers: { "Content-Type": "application/json" },
74
- body: JSON.stringify({
75
- nullifier,
76
- resourceId,
77
- objectKey,
78
- timestamp,
79
- signature
80
- })
81
- });
82
- if (!res.ok) {
83
- const data = await res.json().catch(() => ({}));
84
- const message = data && typeof data === "object" && "error" in data && typeof data.error === "string" ? data.error : res.statusText;
85
- throw new Error(`Worker fetch failed: ${message}`);
86
- }
87
- const buffer = await res.arrayBuffer();
88
- return {
89
- data: new Uint8Array(buffer),
90
- contentType: res.headers.get("Content-Type") ?? "application/octet-stream"
91
- };
92
- }
93
- async checkManifestExists(who, schemaId, name) {
94
- try {
95
- const ds = await this.dataSourceRegistry.get(who, schemaId, name);
96
- return !!ds.manifestCid && ds.manifestCid !== "";
97
- } catch {
98
- return false;
99
- }
100
- }
101
- async getEntry(owner, schemaId, name, gateway) {
102
- try {
103
- const ds = await this.dataSourceRegistry.get(owner, schemaId, name);
104
- if (!ds.manifestCid || ds.manifestCid === "") return void 0;
105
- (await PinataBackend.getStatic(ds.manifestCid, gateway)).entries.forEach((entry) => {
106
- if (entry.name === name) return entry;
107
- });
108
- return;
109
- } catch {
110
- return;
111
- }
112
- }
113
- /**
114
- * Resolves the handle URI for a specific field
115
- * and fetches it via the worker in one call.
116
- */
117
- async fetchField(owner, schemaId, name, field, nullifier, walletClient) {
118
- const entry = await this.getEntry(owner, schemaId, name);
119
- if (!entry) throw new Error("Entry not found");
120
- const fieldValue = entry.fields[field];
121
- if (!fieldValue || typeof fieldValue !== "object") throw new Error(`Field "${field}" is missing or is not a handle field`);
122
- if (typeof fieldValue !== "object" || !("@type" in fieldValue)) throw new Error(`Field "${field}" is missing or is not a handle field`);
123
- if (fieldValue["@type"] !== "handle") throw new Error(`Field "${field}" is not a handle field. Read it directly from the entry`);
124
- const handle = fieldValue;
125
- const objectKey = parseObjectKey(handle.uri);
126
- const resourceId = this.deriveResourceId(owner, schemaId, name);
127
- return this.fetch({
128
- nullifier,
129
- resourceId,
130
- objectKey,
131
- workerUrl: handle.workerUrl,
132
- walletClient
133
- });
134
- }
135
- async isRegistered(owner, schemaId, name, identity) {
136
- const resourceId = this.deriveResourceId(owner, schemaId, name);
137
- return this.settlementRegistry.isRegistered(resourceId, identity.commitment);
138
- }
139
- deriveResourceId(owner, schemaId, name) {
140
- return DataSourceRegistry.resourceId(owner, schemaId, name);
141
- }
142
- };
143
- function parseObjectKey(uri) {
144
- if (uri.startsWith("r2://")) return uri.slice(5);
145
- if (uri.startsWith("ipfs://")) return uri.slice(7);
146
- return uri;
147
- }
148
-
149
- //#endregion
150
- export { ConsumerRole };
@@ -1,47 +0,0 @@
1
- import { ManifestEntry } from "../publisher/types.js";
2
- import { PrepareSettleResult, TransferWithAuthPayload } from "../../registries/settlement-registry/types.js";
3
- import { Address, Hex, WalletClient } from "viem";
4
-
5
- //#region src/roles/consumer/types.d.ts
6
- interface PurchaseParams {
7
- owner: Address;
8
- schemaId: Hex;
9
- name: string;
10
- identityCommitment: bigint;
11
- relayerPrivateKey: Hex;
12
- preparedRegister: TransferWithAuthPayload;
13
- }
14
- interface ClaimParams {
15
- owner: Address;
16
- schemaId: Hex;
17
- name: string;
18
- relayerPrivateKey: Hex;
19
- preparedSettle: PrepareSettleResult;
20
- }
21
- interface PurchaseResult {
22
- txHash: Hex;
23
- resourceId: Hex;
24
- }
25
- interface ClaimResult {
26
- txHash: Hex;
27
- nullifier: bigint;
28
- resourceId: Hex;
29
- }
30
- interface AccessResult {
31
- data: Uint8Array;
32
- resourceId: Hex;
33
- entry: ManifestEntry;
34
- }
35
- interface FetchParams {
36
- nullifier: string;
37
- resourceId: Hex;
38
- objectKey: string;
39
- workerUrl: string;
40
- walletClient: WalletClient;
41
- }
42
- interface FetchResult {
43
- data: Uint8Array;
44
- contentType: string;
45
- }
46
- //#endregion
47
- export { AccessResult, ClaimParams, ClaimResult, FetchParams, FetchResult, PurchaseParams, PurchaseResult };
@@ -1 +0,0 @@
1
- export { };
@@ -1,32 +0,0 @@
1
- import { SchemaRegistry } from "../../../registries/schema-registry/index.js";
2
- import { MetadataStorage } from "../../../providers/storage/types.js";
3
- import { BundleManifest, FieldInput } from "../types.js";
4
- import { BuildContext, ChunkDraft, ChunkRef, ManifestBuilder, ResolvedSchemaShape } from "./types.js";
5
-
6
- //#region src/roles/publisher/builders/bundle.d.ts
7
- interface BundleUploadInput {
8
- bundleName: string;
9
- nodes: {
10
- id: string;
11
- type: string;
12
- fields: Record<string, FieldInput>;
13
- }[];
14
- edges?: {
15
- rel: string;
16
- from: string;
17
- to: string;
18
- }[];
19
- }
20
- declare class BundleBuilder implements ManifestBuilder<BundleUploadInput, BundleManifest> {
21
- private readonly storage;
22
- private readonly schemaRegistry;
23
- readonly kind = "bundle";
24
- constructor(storage: MetadataStorage, schemaRegistry: SchemaRegistry);
25
- validate(schema: ResolvedSchemaShape, input: BundleUploadInput): void;
26
- chunk(input: BundleUploadInput, schema: ResolvedSchemaShape): AsyncIterable<ChunkDraft>;
27
- compareChunks(a: ChunkRef, b: ChunkRef): number;
28
- assemble(ctx: BuildContext): BundleManifest;
29
- private resolveNodes;
30
- }
31
- //#endregion
32
- export { BundleBuilder, BundleUploadInput };
@@ -1,137 +0,0 @@
1
- import { resolveRecord, validateRecord } from "./utils.js";
2
-
3
- //#region src/roles/publisher/builders/bundle.ts
4
- var BundleBuilder = class {
5
- kind = "bundle";
6
- constructor(storage, schemaRegistry) {
7
- this.storage = storage;
8
- this.schemaRegistry = schemaRegistry;
9
- }
10
- validate(schema, input) {
11
- if (!isBundleSchema(schema)) throw new Error("BundleBuilder requires a bundle schema");
12
- if (input.nodes.length === 0) throw new Error("bundle has no nodes");
13
- }
14
- async *chunk(input, schema) {
15
- const bundle = schema;
16
- const { nodeType, byType } = await this.resolveNodes(bundle, input.nodes);
17
- validateBundleEdges(bundle, input.edges ?? [], nodeType);
18
- for (const type of [...byType.keys()].sort()) {
19
- const data = byType.get(type);
20
- if (!data) continue;
21
- yield {
22
- name: `bundle-node:${type}`,
23
- data,
24
- meta: {
25
- kind: "node",
26
- type
27
- }
28
- };
29
- }
30
- yield {
31
- name: "bundle-edges",
32
- data: input.edges ?? [],
33
- meta: { kind: "edges" }
34
- };
35
- }
36
- compareChunks(a, b) {
37
- const aIsEdge = a.meta?.kind === "edges";
38
- const bIsEdge = b.meta?.kind === "edges";
39
- if (aIsEdge && !bIsEdge) return 1;
40
- if (!aIsEdge && bIsEdge) return -1;
41
- const aType = typeof a.meta?.type === "string" ? a.meta.type : "";
42
- const bType = typeof b.meta?.type === "string" ? b.meta.type : "";
43
- return aType.localeCompare(bType);
44
- }
45
- assemble(ctx) {
46
- const nodeChunks = ctx.chunks.filter((c) => c.meta?.kind === "node").map((c) => ({
47
- type: c.meta?.type ?? "",
48
- dataCid: c.cid,
49
- leaf: ctx.leaves[Number(c.index)]
50
- }));
51
- const edgeChunk = ctx.chunks.find((c) => c.meta?.kind === "edges");
52
- if (!edgeChunk) throw new Error("Missing edge chunk during assembly");
53
- return {
54
- kind: "bundle",
55
- schemaId: ctx.schemaId,
56
- root: ctx.root,
57
- nodeChunks,
58
- edgeChunk: {
59
- dataCid: edgeChunk.cid,
60
- leaf: ctx.leaves[Number(edgeChunk.index)]
61
- },
62
- tree: ctx.layers
63
- };
64
- }
65
- async resolveNodes(bundle, nodes) {
66
- const defByType = /* @__PURE__ */ new Map();
67
- await Promise.all(Object.entries(bundle.nodes).map(async ([type, schemaId]) => {
68
- const { specCid } = await this.schemaRegistry.getSchema(schemaId);
69
- const blob = await this.storage.get(specCid);
70
- if (!blob.definition) throw new Error(`node schema ${schemaId} is not a resolver schema`);
71
- defByType.set(type, {
72
- fields: blob.definition,
73
- types: blob.types
74
- });
75
- }));
76
- const nodeType = /* @__PURE__ */ new Map();
77
- const seen = /* @__PURE__ */ new Set();
78
- const byType = /* @__PURE__ */ new Map();
79
- for (const node of nodes) {
80
- if (!(node.type in bundle.nodes)) throw new Error(`node "${node.id}" has undeclared type "${node.type}"`);
81
- if (seen.has(node.id)) throw new Error(`duplicate node id "${node.id}"`);
82
- seen.add(node.id);
83
- nodeType.set(node.id, node.type);
84
- const def = defByType.get(node.type);
85
- if (!def) throw new Error(`Missing definition schema for type "${node.type}"`);
86
- const record = {
87
- name: node.id,
88
- fields: node.fields
89
- };
90
- validateRecord(record, def);
91
- const resolved = resolveRecord(record, def);
92
- const list = byType.get(node.type) ?? [];
93
- list.push({
94
- id: node.id,
95
- type: node.type,
96
- fields: resolved.fields
97
- });
98
- byType.set(node.type, list);
99
- }
100
- return {
101
- nodeType,
102
- byType
103
- };
104
- }
105
- };
106
- function isBundleSchema(schema) {
107
- return "nodes" in schema && "edges" in schema;
108
- }
109
- function validateBundleEdges(bundle, edges, nodeType) {
110
- const errors = [];
111
- const declared = new Set(bundle.edges.map((e) => `${e.rel}:${e.from}:${e.to}`));
112
- edges.forEach((edge, i) => {
113
- const ft = nodeType.get(edge.from);
114
- const tt = nodeType.get(edge.to);
115
- const indexStr = i.toString();
116
- if (!ft) return errors.push(`edge[${indexStr}] "${edge.rel}" from unknown node "${edge.from}"`);
117
- if (!tt) return errors.push(`edge[${indexStr}] "${edge.rel}" to unknown node "${edge.to}"`);
118
- if (!declared.has(`${edge.rel}:${ft}:${tt}`)) errors.push(`edge[${indexStr}] undeclared relation "${edge.rel}" (${ft} → ${tt})`);
119
- });
120
- for (const shape of bundle.edges) {
121
- const min = shape.min ?? 0;
122
- const max = shape.max ?? null;
123
- for (const [id, type] of nodeType) {
124
- if (type !== shape.from) continue;
125
- const count = edges.filter((e) => e.rel === shape.rel && e.from === id && nodeType.get(e.to) === shape.to).length;
126
- const countStr = count.toString();
127
- const minStr = min.toString();
128
- const maxStr = max !== null ? max.toString() : "";
129
- if (count < min) errors.push(`node "${id}" has ${countStr} "${shape.rel}" edges, needs min ${minStr}`);
130
- if (max !== null && count > max) errors.push(`node "${id}" has ${countStr} "${shape.rel}" edges, exceeds max ${maxStr}`);
131
- }
132
- }
133
- if (errors.length) throw new Error("Bundle edge validation failed:\n" + errors.map((e) => ` - ${e}`).join("\n"));
134
- }
135
-
136
- //#endregion
137
- export { BundleBuilder };
@@ -1,17 +0,0 @@
1
- import { Manifest, PublishRecord } from "../types.js";
2
- import { BuildContext, ChunkDraft, ChunkRef, ManifestBuilder, ResolvedSchemaShape } from "./types.js";
3
-
4
- //#region src/roles/publisher/builders/record-set.d.ts
5
- interface RecordSetInput {
6
- records: PublishRecord[] | AsyncIterable<PublishRecord>;
7
- chunkSize?: number;
8
- }
9
- declare class RecordSetBuilder implements ManifestBuilder<RecordSetInput, Manifest> {
10
- readonly kind = "record-set";
11
- validate(schema: ResolvedSchemaShape, input: RecordSetInput): void;
12
- chunk(input: RecordSetInput, schema: ResolvedSchemaShape): AsyncIterable<ChunkDraft>;
13
- compareChunks(a: ChunkRef, b: ChunkRef): number;
14
- assemble(ctx: BuildContext): Manifest;
15
- }
16
- //#endregion
17
- export { RecordSetBuilder, RecordSetInput };
@@ -1,55 +0,0 @@
1
- import { resolveRecord, validateRecord } from "./utils.js";
2
-
3
- //#region src/roles/publisher/builders/record-set.ts
4
- var RecordSetBuilder = class {
5
- kind = "record-set";
6
- validate(schema, input) {
7
- if (!isRecordSchema(schema)) throw new Error("RecordSetBuilder requires a resolver schema, not a bundle");
8
- if (input.chunkSize !== void 0 && (!Number.isInteger(input.chunkSize) || input.chunkSize <= 0)) throw new Error(`chunkSize must be a positive integer, got ${input.chunkSize.toString()}`);
9
- }
10
- async *chunk(input, schema) {
11
- if (!isRecordSchema(schema)) throw new Error("expected resolver schema");
12
- const chunkSize = input.chunkSize ?? 1e3;
13
- let buffer = [];
14
- let chunkIdx = 0;
15
- const flush = () => {
16
- const draft = {
17
- name: `chunk:${chunkIdx.toString()}`,
18
- data: buffer
19
- };
20
- buffer = [];
21
- chunkIdx++;
22
- return draft;
23
- };
24
- for await (const record of input.records) {
25
- validateRecord(record, schema);
26
- buffer.push(resolveRecord(record, schema));
27
- if (buffer.length >= chunkSize) yield flush();
28
- }
29
- if (buffer.length > 0) yield flush();
30
- }
31
- compareChunks(a, b) {
32
- return a.cid.localeCompare(b.cid);
33
- }
34
- assemble(ctx) {
35
- return {
36
- kind: "record-set",
37
- schemaId: ctx.schemaId,
38
- root: ctx.root,
39
- entries: ctx.chunks.map((chunk, i) => ({
40
- name: chunk.name,
41
- fields: {
42
- dataCid: chunk.cid,
43
- leaf: ctx.leaves[i]
44
- }
45
- })),
46
- tree: ctx.layers
47
- };
48
- }
49
- };
50
- function isRecordSchema(schema) {
51
- return "fields" in schema;
52
- }
53
-
54
- //#endregion
55
- export { RecordSetBuilder };
@@ -1,38 +0,0 @@
1
- import { ResolvedBundle, SchemaDoc } from "../../schema/types.js";
2
- import { Hex } from "viem";
3
-
4
- //#region src/roles/publisher/builders/types.d.ts
5
- interface ChunkDraft {
6
- name: string;
7
- data: unknown;
8
- meta?: Record<string, unknown>;
9
- }
10
- interface ChunkRef {
11
- index: bigint;
12
- cid: string;
13
- name: string;
14
- meta?: Record<string, unknown>;
15
- }
16
- interface BuildContext {
17
- schemaId: Hex;
18
- chunks: ChunkRef[];
19
- leaves: Hex[];
20
- root: Hex;
21
- layers: Hex[][];
22
- }
23
- interface BaseManifest {
24
- kind: string;
25
- schemaId: Hex;
26
- root: Hex;
27
- tree: Hex[][];
28
- }
29
- type ResolvedSchemaShape = SchemaDoc | ResolvedBundle;
30
- interface ManifestBuilder<TInput, TManifest extends BaseManifest> {
31
- readonly kind: string;
32
- validate(schema: ResolvedSchemaShape, input: TInput): void | Promise<void>;
33
- chunk(input: TInput, schema: ResolvedSchemaShape): AsyncIterable<ChunkDraft>;
34
- compareChunks(a: ChunkRef, b: ChunkRef): number;
35
- assemble(context: BuildContext, input: TInput, schema: ResolvedSchemaShape): TManifest;
36
- }
37
- //#endregion
38
- export { BaseManifest, BuildContext, ChunkDraft, ChunkRef, ManifestBuilder, ResolvedSchemaShape };
@@ -1 +0,0 @@
1
- export { };
@@ -1,9 +0,0 @@
1
- import { SchemaDoc } from "../../schema/types.js";
2
- import { FieldInput, HandleFieldInput, ManifestEntry, PublishRecord } from "../types.js";
3
-
4
- //#region src/roles/publisher/builders/utils.d.ts
5
- declare function isHandleFieldInput(value: FieldInput | undefined): value is HandleFieldInput;
6
- declare function resolveRecord(record: PublishRecord, schema: SchemaDoc): ManifestEntry;
7
- declare function validateRecord(record: PublishRecord, schema: SchemaDoc): void;
8
- //#endregion
9
- export { isHandleFieldInput, resolveRecord, validateRecord };
@@ -1,29 +0,0 @@
1
- import { validate } from "../../schema/validate.js";
2
-
3
- //#region src/roles/publisher/builders/utils.ts
4
- function isHandleFieldInput(value) {
5
- return typeof value === "object" && value !== null && "@type" in value && value["@type"] === "handle";
6
- }
7
- function resolveRecord(record, schema) {
8
- const resolved = {};
9
- for (const [fieldName] of Object.entries(schema.fields)) {
10
- const value = record.fields[fieldName];
11
- if (isHandleFieldInput(value)) resolved[fieldName] = {
12
- "@type": "handle",
13
- uri: value.uri,
14
- workerUrl: value.workerUrl
15
- };
16
- else resolved[fieldName] = value;
17
- }
18
- return {
19
- name: record.name,
20
- fields: resolved
21
- };
22
- }
23
- function validateRecord(record, schema) {
24
- const errors = validate(record.fields, schema);
25
- if (errors.length > 0) throw new Error(`Validation failed for "${record.name}":\n` + errors.map((e) => ` - ${e}`).join("\n"));
26
- }
27
-
28
- //#endregion
29
- export { isHandleFieldInput, resolveRecord, validateRecord };
@@ -1,18 +0,0 @@
1
- import { HandleFieldInput } from "./types.js";
2
-
3
- //#region src/roles/publisher/encryption.d.ts
4
- interface EncryptAndUploadParams {
5
- plaintext: Uint8Array;
6
- manifestId: string;
7
- fieldName: string;
8
- storage: {
9
- workerUrl: string;
10
- authToken: string;
11
- contentType: string;
12
- };
13
- teeEndpoint: string;
14
- gadget?: string;
15
- }
16
- declare function encryptAndUpload(params: EncryptAndUploadParams): Promise<HandleFieldInput>;
17
- //#endregion
18
- export { EncryptAndUploadParams, encryptAndUpload };
@@ -1,38 +0,0 @@
1
- //#region src/roles/publisher/encryption.ts
2
- async function encryptAndUpload(params) {
3
- const { plaintext, manifestId, fieldName, storage, teeEndpoint, gadget = "tee-aes-v1" } = params;
4
- const encRes = await fetch(`${teeEndpoint}/encrypt`, {
5
- method: "POST",
6
- headers: { "Content-Type": "application/json" },
7
- body: JSON.stringify({
8
- manifest_id: manifestId,
9
- field_name: fieldName,
10
- plaintext_b64: plaintext.toBase64()
11
- })
12
- });
13
- if (!encRes.ok) throw new Error(`TEE encrypt failed: ${encRes.status}`);
14
- const { ciphertext_b64, ciphertext_hash } = await encRes.json();
15
- const ciphertext = Uint8Array.fromBase64(ciphertext_b64);
16
- const uploadRes = await fetch(`${storage.workerUrl}/upload`, {
17
- method: "POST",
18
- headers: {
19
- "Authorization": `Bearer ${storage.authToken}`,
20
- "Content-Type": storage.contentType
21
- },
22
- body: ciphertext
23
- });
24
- if (!uploadRes.ok) throw new Error(`upload failed: ${uploadRes.status}`);
25
- const { objectKey } = await uploadRes.json();
26
- return {
27
- "@type": "handle",
28
- uri: objectKey,
29
- workerUrl: storage.workerUrl,
30
- encryption: {
31
- gadget,
32
- ciphertextHash: ciphertext_hash
33
- }
34
- };
35
- }
36
-
37
- //#endregion
38
- export { encryptAndUpload };