@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,128 +0,0 @@
1
- //#region src/roles/schema/validate.ts
2
- const BUILT_INS = new Set([
3
- "string",
4
- "number",
5
- "boolean",
6
- "bytes",
7
- "handle",
8
- "array",
9
- "object",
10
- "encrypted"
11
- ]);
12
- /** Accept either the explicit document shape or a bare flat field map. */
13
- function normalize(schema) {
14
- if ("fields" in schema && typeof schema.fields === "object") return schema;
15
- return { fields: schema };
16
- }
17
- function validate(data, schema) {
18
- const doc = normalize(schema);
19
- const errors = [];
20
- for (const [field, def] of Object.entries(doc.fields)) errors.push(...validateValue(data[field], def, doc, field));
21
- return errors;
22
- }
23
- function validateValue(value, def, doc, path) {
24
- const rawType = def["@type"];
25
- const nullable = rawType.endsWith("| null");
26
- const baseType = nullable ? rawType.replace("| null", "").trim() : rawType;
27
- if (value === void 0 || value === null) return nullable ? [] : [`${path}: missing required field`];
28
- const errors = [];
29
- if (BUILT_INS.has(baseType)) errors.push(...validateBuiltIn(value, baseType, def, doc, path));
30
- else {
31
- const customType = doc.types?.[baseType];
32
- if (!customType) {
33
- errors.push(`${path}: unknown @type "${rawType}"`);
34
- return errors;
35
- }
36
- errors.push(...validateCustomType(value, customType, doc, path));
37
- }
38
- if (def.constraints) errors.push(...applyConstraints(value, def.constraints, doc, path));
39
- return errors;
40
- }
41
- function validateBuiltIn(value, baseType, def, doc, path) {
42
- const errors = [];
43
- switch (baseType) {
44
- case "string":
45
- if (typeof value !== "string") errors.push(`${path}: must be a string, got ${typeof value}`);
46
- break;
47
- case "number":
48
- if (typeof value !== "number") errors.push(`${path}: must be a number, got ${typeof value}`);
49
- break;
50
- case "boolean":
51
- if (typeof value !== "boolean") errors.push(`${path}: must be a boolean, got ${typeof value}`);
52
- break;
53
- case "bytes":
54
- if (!(value instanceof Uint8Array) && !ArrayBuffer.isView(value)) errors.push(`${path}: must be bytes (Uint8Array)`);
55
- break;
56
- case "handle":
57
- if (typeof value?.uri !== "string") errors.push(`${path}: is a handle — expected { uri: string }`);
58
- break;
59
- case "array": {
60
- if (!Array.isArray(value)) {
61
- errors.push(`${path}: must be an array, got ${typeof value}`);
62
- break;
63
- }
64
- const items = def.items;
65
- if (items) value.forEach((item, i) => errors.push(...validateValue(item, items, doc, `${path}[${i}]`)));
66
- break;
67
- }
68
- case "object": {
69
- if (typeof value !== "object" || value === null) {
70
- errors.push(`${path}: must be an object, got ${typeof value}`);
71
- break;
72
- }
73
- const items = def.items;
74
- if (items) {
75
- const obj = value;
76
- for (const [k, sub] of Object.entries(items)) errors.push(...validateValue(obj[k], sub, doc, `${path}.${k}`));
77
- }
78
- break;
79
- }
80
- case "encrypted": break;
81
- }
82
- return errors;
83
- }
84
- function validateCustomType(value, type, doc, path) {
85
- if (typeof value !== "object" || value === null) return [`${path}: expected object for custom type`];
86
- const obj = value;
87
- const errors = [];
88
- for (const [k, subDef] of Object.entries(type.shape)) errors.push(...validateValue(obj[k], subDef, doc, `${path}.${k}`));
89
- if (type.constraints) errors.push(...applyConstraints(value, type.constraints, doc, path));
90
- return errors;
91
- }
92
- function applyConstraints(value, constraints, doc, path) {
93
- const errors = [];
94
- for (const c of constraints) {
95
- const err = applyOne(value, c, doc, path);
96
- if (err) errors.push(err);
97
- }
98
- return errors;
99
- }
100
- function applyOne(value, c, doc, path) {
101
- switch (c.kind) {
102
- case "regex":
103
- if (typeof value !== "string") return `${path}: regex constraint requires a string`;
104
- return new RegExp(c.pattern).test(value) ? null : `${path}: must match /${c.pattern}/`;
105
- case "enum": return c.values.includes(value) ? null : `${path}: must be one of ${JSON.stringify(c.values)}`;
106
- case "range":
107
- if (typeof value !== "number") return `${path}: range constraint requires a number`;
108
- if (c.min !== void 0 && (c.exclusive ? value <= c.min : value < c.min)) return `${path}: must be ${c.exclusive ? ">" : ">="} ${c.min}`;
109
- if (c.max !== void 0 && (c.exclusive ? value >= c.max : value > c.max)) return `${path}: must be ${c.exclusive ? "<" : "<="} ${c.max}`;
110
- return null;
111
- case "length": {
112
- const len = typeof value === "string" ? value.length : Array.isArray(value) ? value.length : value instanceof Uint8Array ? value.length : -1;
113
- if (len < 0) return `${path}: length constraint requires a string, array, or bytes`;
114
- if (c.min !== void 0 && len < c.min) return `${path}: length must be >= ${c.min}`;
115
- if (c.max !== void 0 && len > c.max) return `${path}: length must be <= ${c.max}`;
116
- return null;
117
- }
118
- case "ref": {
119
- const target = doc.types?.[c.type];
120
- if (!target) return `${path}: ref constraint references unknown type "${c.type}"`;
121
- const subErrors = validateCustomType(value, target, doc, path);
122
- return subErrors.length === 0 ? null : subErrors.join("\n");
123
- }
124
- }
125
- }
126
-
127
- //#endregion
128
- export { applyConstraints, normalize, validate };
@@ -1,296 +0,0 @@
1
- import { TestBed } from "./testbed.js";
2
- import { arbitrumSepolia } from "viem/chains";
3
- import { createWalletClient, http } from "viem";
4
- import { privateKeyToAccount } from "viem/accounts";
5
- import { program } from "commander";
6
- import streamArray from "stream-json/streamers/stream-array.js";
7
- import { createReadStream, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
8
- import { join, resolve } from "node:path";
9
- import { open } from "lmdb";
10
-
11
- //#region src/test/publish_mb_bundle.ts
12
- /**
13
- * Publish MusicBrainz dump data to Fangorn as a v3 bundle.
14
- *
15
- * This script registers the Track + TrackTaxonomy node schemas and the
16
- * hasTaxonomy bundle schema (all idempotent — safe to re-run), then publishes
17
- * the JSON chunk files produced by `quickbeam data mb` as a sequence of
18
- * ManifestPublished events consumable by `quickbeam build --bundle`.
19
- *
20
- * ─── SETUP ───────────────────────────────────────────────────────────────────
21
- * This file must be placed alongside setup-embeddings-testdata.ts in the
22
- * fangorn-sdk repo (src/publish_mb_bundle.ts) to resolve its imports.
23
- *
24
- * Run from the fangorn-sdk root:
25
- * pnpm dotenvx run -f .env -- tsx src/test/publish_mb_bundle.ts \
26
- * --tracks /path/to/volume_1_tracks.json \
27
- * --taxonomies /path/to/volume_1_taxonomies.json \
28
- * --edges /path/to/volume_1_edges.json \
29
- * --dataset ds.mb.v1
30
- *
31
- * Optional flags:
32
- * --batch-size <n> Nodes per publishBundle call (default 2000)
33
- * --bundle-name <name> Override bundle schema name (default fangorn.mb.bundle.v1)
34
- * --track-schema <name> Override Track schema name
35
- * --taxonomy-schema <name> Override TrackTaxonomy schema name
36
- * ─────────────────────────────────────────────────────────────────────────────
37
- */
38
- const SK = process.env.DELEGATOR_ETH_PRIVATE_KEY;
39
- const RPC_URL = process.env.RPC_URL ?? process.env.CHAIN_RPC_URL ?? "https://sepolia-rollup.arbitrum.io/rpc";
40
- const WORKER_URL = process.env.WORKER_URL ?? "http://localhost:8787";
41
- const SETTLEMENT_REGISTRY_ADDRESS = process.env.SETTLEMENT_REGISTRY_ADDRESS;
42
- const DATA_SOURCE_REGISTRY_ADDRESS = process.env.DATA_SOURCE_REGISTRY_ADDRESS;
43
- const SCHEMA_REGISTRY_ADDRESS = process.env.SCHEMA_REGISTRY_ADDRESS;
44
- const USDC_ADDRESS = process.env.USDC_ADDRESS ?? process.env.USDC_CONTRACT_ADDRESS ?? "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d";
45
- const USDC_DOMAIN = "USD Coin";
46
- const CHAIN = arbitrumSepolia;
47
- const TRACK_SCHEMA = {
48
- schemaVersion: { "@type": "number" },
49
- trackId: { "@type": "string" },
50
- isrcCode: { "@type": "string | null" },
51
- title: { "@type": "string" },
52
- byArtist: { "@type": "string" },
53
- albumName: { "@type": "string | null" },
54
- datePublished: { "@type": "string | null" },
55
- durationMs: { "@type": "number | null" },
56
- contributors: {
57
- "@type": "array",
58
- items: {
59
- role: { "@type": "string | null" },
60
- name: { "@type": "string | null" },
61
- id: { "@type": "string | null" }
62
- }
63
- }
64
- };
65
- const TAXONOMY_SCHEMA = {
66
- schemaVersion: { "@type": "number" },
67
- trackId: { "@type": "string" },
68
- genres: {
69
- "@type": "array",
70
- items: { "@type": "string" }
71
- },
72
- moods: {
73
- "@type": "array",
74
- items: { "@type": "string" }
75
- },
76
- themes: {
77
- "@type": "array",
78
- items: { "@type": "string" }
79
- },
80
- contexts: {
81
- "@type": "array",
82
- items: { "@type": "string" }
83
- }
84
- };
85
- /**
86
- * Stream the elements of a top-level JSON array file one at a time. Avoids
87
- * readFileSync()+JSON.parse(), which materializes the whole file as a single
88
- * string (>512MB hits V8's ERR_STRING_TOO_LONG) plus a full object-graph copy.
89
- */
90
- async function* streamJsonArray(path) {
91
- const pipeline = createReadStream(path).pipe(streamArray.withParserAsStream());
92
- for await (const { value } of pipeline) yield value;
93
- }
94
- /**
95
- * Stream a JSON-array file into an LMDB sub-database in committed batches, so the
96
- * full index lives on disk (memory-mapped) instead of the JS heap. `keyFn`
97
- * derives each record's key; `seq` is a per-call running counter for composite keys.
98
- * Returns the number of records written.
99
- */
100
- async function bulkLoad(db, source, keyFn) {
101
- const BATCH = 2e4;
102
- let buf = [];
103
- let n = 0;
104
- const commit = () => {
105
- const pending = buf;
106
- buf = [];
107
- db.transactionSync(() => {
108
- for (const [k, v] of pending) db.putSync(k, v);
109
- });
110
- };
111
- for await (const item of source) {
112
- buf.push([keyFn(item, n), item]);
113
- n++;
114
- if (buf.length >= BATCH) commit();
115
- }
116
- if (buf.length) commit();
117
- return n;
118
- }
119
- /** Strip undefined values; null is kept so nullable schema fields validate correctly. */
120
- function cleanFields(raw) {
121
- const out = {};
122
- for (const [k, v] of Object.entries(raw)) if (v !== void 0) out[k] = v;
123
- return out;
124
- }
125
- async function withRetry(label, maxAttempts, fn) {
126
- for (let attempt = 1; attempt <= maxAttempts; attempt++) try {
127
- return await fn();
128
- } catch (err) {
129
- if (attempt === maxAttempts) throw err;
130
- const delayMs = 2e3 * attempt;
131
- console.warn(` [retry] ${label} failed (attempt ${attempt.toString()}/${maxAttempts.toString()}), retrying in ${(delayMs / 1e3).toString()}s: ${err.message}`);
132
- await new Promise((r) => setTimeout(r, delayMs));
133
- }
134
- throw new Error("unreachable");
135
- }
136
- function loadLedger(path) {
137
- if (!existsSync(path)) return null;
138
- try {
139
- return JSON.parse(readFileSync(path, "utf8"));
140
- } catch {
141
- return null;
142
- }
143
- }
144
- function saveLedger(path, ledger) {
145
- mkdirSync("tmp", { recursive: true });
146
- writeFileSync(path, JSON.stringify(ledger, null, 2));
147
- }
148
- program.requiredOption("--tracks <path>", "volume_N_tracks.json from quickbeam data mb").requiredOption("--taxonomies <path>", "volume_N_taxonomies.json").requiredOption("--edges <path>", "volume_N_edges.json").requiredOption("--dataset <name>", "Base dataset name, e.g. ds.mb.v1").option("--batch-size <n>", "Track nodes per publishBundle call", "2000").option("--bundle-name <name>", "Bundle schema name", "fangorn.mb.bundle.v1").option("--bundle-schema-id <hex>", "Reuse an existing bundle schema ID and skip registration").option("--track-schema <name>", "Track node schema name", "sond3r.track.invariants.v1").option("--taxonomy-schema <name>", "TrackTaxonomy node schema name", "sond3r.track.taxonomy.v1").option("--ledger <path>", "Ledger file path (default: tmp/mb-publish-<dataset>.json)").option("--index-dir <path>", "Directory for the temporary on-disk LMDB index — MUST be on real disk, not tmpfs/RAM", "tmp").option("--max-retries <n>", "Retry attempts per batch on transient failures", "5").parse();
149
- const opts = program.opts();
150
- function requireEnv() {
151
- const missing = [];
152
- if (SK === "0x") missing.push("DELEGATOR_ETH_PRIVATE_KEY");
153
- if (DATA_SOURCE_REGISTRY_ADDRESS === "0x") missing.push("DATA_SOURCE_REGISTRY_ADDRESS");
154
- if (SCHEMA_REGISTRY_ADDRESS === "0x") missing.push("SCHEMA_REGISTRY_ADDRESS");
155
- if (!process.env.PINATA_JWT) missing.push("PINATA_JWT");
156
- if (missing.length) throw new Error(`Missing env vars: ${missing.join(", ")}`);
157
- }
158
- async function main() {
159
- requireEnv();
160
- const batchSize = parseInt(opts.batchSize, 10);
161
- const maxRetries = parseInt(opts.maxRetries, 10);
162
- const testbed = TestBed.init(createWalletClient({
163
- account: privateKeyToAccount(SK),
164
- chain: CHAIN,
165
- transport: http(RPC_URL)
166
- }), DATA_SOURCE_REGISTRY_ADDRESS, SCHEMA_REGISTRY_ADDRESS, SETTLEMENT_REGISTRY_ADDRESS, USDC_ADDRESS, USDC_DOMAIN, RPC_URL, "arbitrumSepolia", CHAIN.id, WORKER_URL);
167
- console.log("[publish] registering node schemas...");
168
- await testbed.registerSchema(opts.trackSchema, TRACK_SCHEMA);
169
- await testbed.registerSchema(opts.taxonomySchema, TAXONOMY_SCHEMA);
170
- let bundleSchemaId;
171
- if (opts.bundleSchemaId) {
172
- bundleSchemaId = opts.bundleSchemaId;
173
- console.log(`[publish] reusing bundle schema id: ${bundleSchemaId}`);
174
- } else {
175
- console.log("[publish] registering bundle shape...");
176
- const bundle = {
177
- nodes: {
178
- Track: opts.trackSchema,
179
- TrackTaxonomy: opts.taxonomySchema
180
- },
181
- edges: [{
182
- rel: "hasTaxonomy",
183
- from: "Track",
184
- to: "TrackTaxonomy",
185
- min: 1,
186
- max: 1
187
- }]
188
- };
189
- bundleSchemaId = await testbed.registerBundle(opts.bundleName, bundle);
190
- console.log(`[publish] bundle schema id: ${bundleSchemaId}`);
191
- }
192
- const ledgerPath = opts.ledger ?? `tmp/mb-publish-${opts.dataset.replace(/[^a-z0-9._-]/gi, "_")}.json`;
193
- const indexBase = resolve(opts.indexDir);
194
- mkdirSync(indexBase, { recursive: true });
195
- const indexDir = mkdtempSync(join(indexBase, "mb-index-"));
196
- console.log(`[publish] LMDB index dir: ${indexDir}`);
197
- const indexEnv = open({
198
- path: indexDir,
199
- compression: false,
200
- noSync: true,
201
- maxDbs: 2
202
- });
203
- const taxoDb = indexEnv.openDB({ name: "taxo" });
204
- const edgeDb = indexEnv.openDB({ name: "edge" });
205
- try {
206
- console.log("[publish] indexing taxonomies + edges (on-disk LMDB)...");
207
- const taxoCount = await bulkLoad(taxoDb, streamJsonArray(opts.taxonomies), (t) => t.name);
208
- const edgeCount = await bulkLoad(edgeDb, streamJsonArray(opts.edges), (e, seq) => [e.from, seq]);
209
- console.log(`[publish] ${taxoCount.toString()} taxonomies, ${edgeCount.toString()} edges indexed → ${indexDir}`);
210
- const ledger = loadLedger(ledgerPath) ?? {
211
- bundleName: opts.bundleName,
212
- bundleSchemaId,
213
- batches: []
214
- };
215
- ledger.batches.map((b) => b.batchIndex).sort((a, b) => a - b).forEach((idx, i) => {
216
- if (idx !== i) throw new Error(`Ledger batch indices are not a contiguous 0..N prefix (gap near index ${idx.toString()}); offset-based resume would be unsafe. Inspect ${ledgerPath}.`);
217
- });
218
- const tracksDone = ledger.batches.reduce((sum, b) => sum + b.trackCount, 0);
219
- let nextBatchIdx = ledger.batches.length;
220
- const firstNewIdx = nextBatchIdx;
221
- if (tracksDone > 0) console.log(`[publish] resuming: ${tracksDone.toString()} tracks already published across ${nextBatchIdx.toString()} batches — skipping those`);
222
- console.log(`[publish] publishing remaining tracks in batches of up to ${batchSize.toString()}`);
223
- let seen = 0;
224
- let trackTotal = 0;
225
- let batchTracks = [];
226
- const flushBatch = async () => {
227
- const tracks = batchTracks;
228
- batchTracks = [];
229
- if (tracks.length === 0) return;
230
- const thisIdx = nextBatchIdx++;
231
- const batchDataset = `${opts.dataset}.batch${thisIdx.toString()}`;
232
- const batchNodes = [];
233
- const batchEdges = [];
234
- for (const track of tracks) {
235
- batchNodes.push({
236
- id: track.name,
237
- type: "Track",
238
- fields: cleanFields(track.fields)
239
- });
240
- const taxo = taxoDb.get(track.name);
241
- if (taxo) batchNodes.push({
242
- id: `taxonomy:${taxo.name}`,
243
- type: "TrackTaxonomy",
244
- fields: cleanFields(taxo.fields)
245
- });
246
- for (const { value } of edgeDb.getRange({
247
- start: [track.name],
248
- end: [`${track.name}\x00`]
249
- })) batchEdges.push(value);
250
- }
251
- console.log(`[publish] batch ${thisIdx.toString()}: ${tracks.length.toString()} tracks → ${batchDataset}`);
252
- const manifestUri = await withRetry(`batch ${thisIdx.toString()}`, maxRetries, () => testbed.publishBundle(opts.bundleName, batchNodes, batchEdges, batchDataset));
253
- ledger.batches.push({
254
- batchIndex: thisIdx,
255
- dataset: batchDataset,
256
- manifestUri,
257
- trackCount: tracks.length,
258
- publishedAt: (/* @__PURE__ */ new Date()).toISOString()
259
- });
260
- saveLedger(ledgerPath, ledger);
261
- console.log(` ✓ manifest: ${manifestUri}`);
262
- };
263
- for await (const track of streamJsonArray(opts.tracks)) {
264
- seen++;
265
- if (seen <= tracksDone) continue;
266
- batchTracks.push(track);
267
- trackTotal++;
268
- if (batchTracks.length >= batchSize) await flushBatch();
269
- }
270
- await flushBatch();
271
- console.log(`[publish] ${trackTotal.toString()} new tracks across ${(nextBatchIdx - firstNewIdx).toString()} new batches`);
272
- console.log("\n✅ All batches published.\n");
273
- console.log(` bundle name : ${opts.bundleName}`);
274
- console.log(` bundle id : ${bundleSchemaId}`);
275
- console.log(` batches : ${ledger.batches.length.toString()}`);
276
- console.log(` ledger : ${ledgerPath}`);
277
- console.log("\nBuild embeddings with:\n");
278
- console.log(` quickbeam build \\`);
279
- console.log(` --bundle "${opts.bundleName}=${bundleSchemaId}" \\`);
280
- console.log(` --root-type Track \\`);
281
- console.log(` --reset\n`);
282
- } finally {
283
- await indexEnv.close();
284
- rmSync(indexDir, {
285
- recursive: true,
286
- force: true
287
- });
288
- }
289
- }
290
- main().catch((err) => {
291
- console.error("\n[publish] failed:", err);
292
- process.exit(1);
293
- });
294
-
295
- //#endregion
296
- export { };
File without changes