@typicalday/firegraph 0.7.1 → 0.8.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.
@@ -0,0 +1,1653 @@
1
+ // src/internal/constants.ts
2
+ var NODE_RELATION = "is";
3
+ var DEFAULT_QUERY_LIMIT = 500;
4
+ var BUILTIN_FIELDS = /* @__PURE__ */ new Set([
5
+ "aType",
6
+ "aUid",
7
+ "axbType",
8
+ "bType",
9
+ "bUid",
10
+ "createdAt",
11
+ "updatedAt"
12
+ ]);
13
+ var SHARD_SEPARATOR = ":";
14
+
15
+ // src/docid.ts
16
+ import { createHash } from "crypto";
17
+ function computeNodeDocId(uid) {
18
+ return uid;
19
+ }
20
+ function computeEdgeDocId(aUid, axbType, bUid) {
21
+ const composite = `${aUid}${SHARD_SEPARATOR}${axbType}${SHARD_SEPARATOR}${bUid}`;
22
+ const hash = createHash("sha256").update(composite).digest("hex");
23
+ const shard = hash[0];
24
+ return `${shard}${SHARD_SEPARATOR}${aUid}${SHARD_SEPARATOR}${axbType}${SHARD_SEPARATOR}${bUid}`;
25
+ }
26
+
27
+ // src/errors.ts
28
+ var FiregraphError = class extends Error {
29
+ constructor(message, code) {
30
+ super(message);
31
+ this.code = code;
32
+ this.name = "FiregraphError";
33
+ }
34
+ };
35
+ var NodeNotFoundError = class extends FiregraphError {
36
+ constructor(uid) {
37
+ super(`Node not found: ${uid}`, "NODE_NOT_FOUND");
38
+ this.name = "NodeNotFoundError";
39
+ }
40
+ };
41
+ var EdgeNotFoundError = class extends FiregraphError {
42
+ constructor(aUid, axbType, bUid) {
43
+ super(`Edge not found: ${aUid} -[${axbType}]-> ${bUid}`, "EDGE_NOT_FOUND");
44
+ this.name = "EdgeNotFoundError";
45
+ }
46
+ };
47
+ var ValidationError = class extends FiregraphError {
48
+ constructor(message, details) {
49
+ super(message, "VALIDATION_ERROR");
50
+ this.details = details;
51
+ this.name = "ValidationError";
52
+ }
53
+ };
54
+ var RegistryViolationError = class extends FiregraphError {
55
+ constructor(aType, axbType, bType) {
56
+ super(
57
+ `Unregistered triple: (${aType}) -[${axbType}]-> (${bType})`,
58
+ "REGISTRY_VIOLATION"
59
+ );
60
+ this.name = "RegistryViolationError";
61
+ }
62
+ };
63
+ var InvalidQueryError = class extends FiregraphError {
64
+ constructor(message) {
65
+ super(message, "INVALID_QUERY");
66
+ this.name = "InvalidQueryError";
67
+ }
68
+ };
69
+ var TraversalError = class extends FiregraphError {
70
+ constructor(message) {
71
+ super(message, "TRAVERSAL_ERROR");
72
+ this.name = "TraversalError";
73
+ }
74
+ };
75
+ var DynamicRegistryError = class extends FiregraphError {
76
+ constructor(message) {
77
+ super(message, "DYNAMIC_REGISTRY_ERROR");
78
+ this.name = "DynamicRegistryError";
79
+ }
80
+ };
81
+ var QuerySafetyError = class extends FiregraphError {
82
+ constructor(message) {
83
+ super(message, "QUERY_SAFETY");
84
+ this.name = "QuerySafetyError";
85
+ }
86
+ };
87
+ var RegistryScopeError = class extends FiregraphError {
88
+ constructor(aType, axbType, bType, scopePath, allowedIn) {
89
+ super(
90
+ `Type (${aType}) -[${axbType}]-> (${bType}) is not allowed at scope "${scopePath || "root"}". Allowed in: [${allowedIn.join(", ")}]`,
91
+ "REGISTRY_SCOPE"
92
+ );
93
+ this.name = "RegistryScopeError";
94
+ }
95
+ };
96
+ var MigrationError = class extends FiregraphError {
97
+ constructor(message) {
98
+ super(message, "MIGRATION_ERROR");
99
+ this.name = "MigrationError";
100
+ }
101
+ };
102
+
103
+ // src/json-schema.ts
104
+ import Ajv from "ajv";
105
+ import addFormats from "ajv-formats";
106
+ var ajv = new Ajv({ allErrors: true, strict: false });
107
+ addFormats(ajv);
108
+ function compileSchema(schema, label) {
109
+ const validate = ajv.compile(schema);
110
+ return (data) => {
111
+ if (!validate(data)) {
112
+ const errors = validate.errors ?? [];
113
+ const messages = errors.map((err) => `${err.instancePath || "/"}${err.message ? ": " + err.message : ""}`).join("; ");
114
+ throw new ValidationError(
115
+ `Data validation failed${label ? " for " + label : ""}: ${messages}`,
116
+ errors
117
+ );
118
+ }
119
+ };
120
+ }
121
+ function jsonSchemaToFieldMeta(schema) {
122
+ if (!schema || schema.type !== "object" || !schema.properties) return [];
123
+ const requiredSet = new Set(
124
+ Array.isArray(schema.required) ? schema.required : []
125
+ );
126
+ return Object.entries(schema.properties).map(
127
+ ([name, prop]) => propertyToFieldMeta(name, prop, requiredSet.has(name))
128
+ );
129
+ }
130
+ function propertyToFieldMeta(name, prop, required) {
131
+ if (!prop) return { name, type: "unknown", required };
132
+ if (Array.isArray(prop.enum)) {
133
+ return {
134
+ name,
135
+ type: "enum",
136
+ required,
137
+ enumValues: prop.enum,
138
+ description: prop.description
139
+ };
140
+ }
141
+ if (Array.isArray(prop.oneOf) || Array.isArray(prop.anyOf)) {
142
+ const variants = prop.oneOf ?? prop.anyOf;
143
+ const nonNull = variants.filter((v) => v.type !== "null");
144
+ if (nonNull.length === 1) {
145
+ return propertyToFieldMeta(name, nonNull[0], false);
146
+ }
147
+ return { name, type: "unknown", required, description: prop.description };
148
+ }
149
+ const type = prop.type;
150
+ if (type === "string") {
151
+ return {
152
+ name,
153
+ type: "string",
154
+ required,
155
+ minLength: prop.minLength,
156
+ maxLength: prop.maxLength,
157
+ pattern: prop.pattern,
158
+ description: prop.description
159
+ };
160
+ }
161
+ if (type === "number" || type === "integer") {
162
+ return {
163
+ name,
164
+ type: "number",
165
+ required,
166
+ min: prop.minimum,
167
+ max: prop.maximum,
168
+ isInt: type === "integer" ? true : void 0,
169
+ description: prop.description
170
+ };
171
+ }
172
+ if (type === "boolean") {
173
+ return { name, type: "boolean", required, description: prop.description };
174
+ }
175
+ if (type === "array") {
176
+ const itemMeta = prop.items ? propertyToFieldMeta("item", prop.items, true) : void 0;
177
+ return {
178
+ name,
179
+ type: "array",
180
+ required,
181
+ itemMeta,
182
+ description: prop.description
183
+ };
184
+ }
185
+ if (type === "object") {
186
+ return {
187
+ name,
188
+ type: "object",
189
+ required,
190
+ fields: jsonSchemaToFieldMeta(prop),
191
+ description: prop.description
192
+ };
193
+ }
194
+ return { name, type: "unknown", required, description: prop.description };
195
+ }
196
+
197
+ // src/migration.ts
198
+ async function applyMigrationChain(data, currentVersion, targetVersion, migrations) {
199
+ const sorted = [...migrations].sort((a, b) => a.fromVersion - b.fromVersion);
200
+ let result = { ...data };
201
+ let version = currentVersion;
202
+ for (const step of sorted) {
203
+ if (step.fromVersion === version) {
204
+ try {
205
+ result = await step.up(result);
206
+ } catch (err) {
207
+ if (err instanceof MigrationError) throw err;
208
+ throw new MigrationError(
209
+ `Migration from v${step.fromVersion} to v${step.toVersion} failed: ${err.message}`
210
+ );
211
+ }
212
+ if (!result || typeof result !== "object") {
213
+ throw new MigrationError(
214
+ `Migration from v${step.fromVersion} to v${step.toVersion} returned invalid data (expected object)`
215
+ );
216
+ }
217
+ version = step.toVersion;
218
+ }
219
+ }
220
+ if (version !== targetVersion) {
221
+ throw new MigrationError(
222
+ `Incomplete migration chain: reached v${version} but target is v${targetVersion}`
223
+ );
224
+ }
225
+ return result;
226
+ }
227
+ function validateMigrationChain(migrations, label) {
228
+ if (migrations.length === 0) return;
229
+ const seen = /* @__PURE__ */ new Set();
230
+ for (const step of migrations) {
231
+ if (step.toVersion <= step.fromVersion) {
232
+ throw new MigrationError(
233
+ `${label}: migration step has toVersion (${step.toVersion}) <= fromVersion (${step.fromVersion})`
234
+ );
235
+ }
236
+ if (seen.has(step.fromVersion)) {
237
+ throw new MigrationError(
238
+ `${label}: duplicate migration step for fromVersion ${step.fromVersion}`
239
+ );
240
+ }
241
+ seen.add(step.fromVersion);
242
+ }
243
+ const sorted = [...migrations].sort((a, b) => a.fromVersion - b.fromVersion);
244
+ const targetVersion = Math.max(...migrations.map((m) => m.toVersion));
245
+ let version = 0;
246
+ for (const step of sorted) {
247
+ if (step.fromVersion === version) {
248
+ version = step.toVersion;
249
+ } else if (step.fromVersion > version) {
250
+ throw new MigrationError(
251
+ `${label}: migration chain has a gap \u2014 no step covers v${version} \u2192 v${step.fromVersion}`
252
+ );
253
+ }
254
+ }
255
+ if (version !== targetVersion) {
256
+ throw new MigrationError(
257
+ `${label}: migration chain does not reach v${targetVersion} (stuck at v${version})`
258
+ );
259
+ }
260
+ }
261
+ async function migrateRecord(record, registry, globalWriteBack = "off") {
262
+ const entry = registry.lookup(record.aType, record.axbType, record.bType);
263
+ if (!entry?.migrations?.length || !entry.schemaVersion) {
264
+ return { record, migrated: false, writeBack: "off" };
265
+ }
266
+ const currentVersion = record.v ?? 0;
267
+ if (currentVersion >= entry.schemaVersion) {
268
+ return { record, migrated: false, writeBack: "off" };
269
+ }
270
+ const migratedData = await applyMigrationChain(
271
+ record.data,
272
+ currentVersion,
273
+ entry.schemaVersion,
274
+ entry.migrations
275
+ );
276
+ const writeBack = entry.migrationWriteBack ?? globalWriteBack ?? "off";
277
+ return {
278
+ record: { ...record, data: migratedData, v: entry.schemaVersion },
279
+ migrated: true,
280
+ writeBack
281
+ };
282
+ }
283
+ async function migrateRecords(records, registry, globalWriteBack = "off") {
284
+ return Promise.all(
285
+ records.map((r) => migrateRecord(r, registry, globalWriteBack))
286
+ );
287
+ }
288
+
289
+ // src/scope.ts
290
+ function matchScope(scopePath, pattern) {
291
+ if (pattern === "root") return scopePath === "";
292
+ if (pattern === "**") return true;
293
+ const pathSegments = scopePath === "" ? [] : scopePath.split("/");
294
+ const patternSegments = pattern.split("/");
295
+ return matchSegments(pathSegments, 0, patternSegments, 0);
296
+ }
297
+ function matchScopeAny(scopePath, patterns) {
298
+ if (!patterns || patterns.length === 0) return true;
299
+ return patterns.some((p) => matchScope(scopePath, p));
300
+ }
301
+ function matchSegments(path, pi, pattern, qi) {
302
+ if (pi === path.length && qi === pattern.length) return true;
303
+ if (qi === pattern.length) return false;
304
+ const seg = pattern[qi];
305
+ if (seg === "**") {
306
+ if (qi === pattern.length - 1) return true;
307
+ for (let skip = 0; skip <= path.length - pi; skip++) {
308
+ if (matchSegments(path, pi + skip, pattern, qi + 1)) return true;
309
+ }
310
+ return false;
311
+ }
312
+ if (pi === path.length) return false;
313
+ if (seg === "*") {
314
+ return matchSegments(path, pi + 1, pattern, qi + 1);
315
+ }
316
+ if (path[pi] === seg) {
317
+ return matchSegments(path, pi + 1, pattern, qi + 1);
318
+ }
319
+ return false;
320
+ }
321
+
322
+ // src/registry.ts
323
+ function tripleKey(aType, axbType, bType) {
324
+ return `${aType}:${axbType}:${bType}`;
325
+ }
326
+ function tripleKeyFor(e) {
327
+ return tripleKey(e.aType, e.axbType, e.bType);
328
+ }
329
+ function createRegistry(input) {
330
+ const map = /* @__PURE__ */ new Map();
331
+ let entries;
332
+ if (Array.isArray(input)) {
333
+ entries = input;
334
+ } else {
335
+ entries = discoveryToEntries(input);
336
+ }
337
+ const entryList = Object.freeze([...entries]);
338
+ for (const entry of entries) {
339
+ if (entry.targetGraph && entry.targetGraph.includes("/")) {
340
+ throw new ValidationError(
341
+ `Entry (${entry.aType}) -[${entry.axbType}]-> (${entry.bType}) has invalid targetGraph "${entry.targetGraph}" \u2014 must be a single segment (no "/")`
342
+ );
343
+ }
344
+ if (entry.migrations?.length) {
345
+ const label = `Entry (${entry.aType}) -[${entry.axbType}]-> (${entry.bType})`;
346
+ validateMigrationChain(entry.migrations, label);
347
+ entry.schemaVersion = Math.max(...entry.migrations.map((m) => m.toVersion));
348
+ } else {
349
+ entry.schemaVersion = void 0;
350
+ }
351
+ const key = tripleKey(entry.aType, entry.axbType, entry.bType);
352
+ const validator = entry.jsonSchema ? compileSchema(entry.jsonSchema, `(${entry.aType}) -[${entry.axbType}]-> (${entry.bType})`) : void 0;
353
+ map.set(key, { entry, validate: validator });
354
+ }
355
+ const axbIndex = /* @__PURE__ */ new Map();
356
+ const axbBuild = /* @__PURE__ */ new Map();
357
+ for (const entry of entries) {
358
+ const existing = axbBuild.get(entry.axbType);
359
+ if (existing) {
360
+ existing.push(entry);
361
+ } else {
362
+ axbBuild.set(entry.axbType, [entry]);
363
+ }
364
+ }
365
+ for (const [key, arr] of axbBuild) {
366
+ axbIndex.set(key, Object.freeze(arr));
367
+ }
368
+ return {
369
+ lookup(aType, axbType, bType) {
370
+ return map.get(tripleKey(aType, axbType, bType))?.entry;
371
+ },
372
+ lookupByAxbType(axbType) {
373
+ return axbIndex.get(axbType) ?? [];
374
+ },
375
+ validate(aType, axbType, bType, data, scopePath) {
376
+ const rec = map.get(tripleKey(aType, axbType, bType));
377
+ if (!rec) {
378
+ throw new RegistryViolationError(aType, axbType, bType);
379
+ }
380
+ if (scopePath !== void 0 && rec.entry.allowedIn && rec.entry.allowedIn.length > 0) {
381
+ if (!matchScopeAny(scopePath, rec.entry.allowedIn)) {
382
+ throw new RegistryScopeError(aType, axbType, bType, scopePath, rec.entry.allowedIn);
383
+ }
384
+ }
385
+ if (rec.validate) {
386
+ try {
387
+ rec.validate(data);
388
+ } catch (err) {
389
+ if (err instanceof ValidationError) throw err;
390
+ throw new ValidationError(
391
+ `Data validation failed for (${aType}) -[${axbType}]-> (${bType})`,
392
+ err
393
+ );
394
+ }
395
+ }
396
+ },
397
+ entries() {
398
+ return entryList;
399
+ }
400
+ };
401
+ }
402
+ function createMergedRegistry(base, extension) {
403
+ const baseKeys = new Set(base.entries().map(tripleKeyFor));
404
+ return {
405
+ lookup(aType, axbType, bType) {
406
+ return base.lookup(aType, axbType, bType) ?? extension.lookup(aType, axbType, bType);
407
+ },
408
+ lookupByAxbType(axbType) {
409
+ const baseResults = base.lookupByAxbType(axbType);
410
+ const extResults = extension.lookupByAxbType(axbType);
411
+ if (extResults.length === 0) return baseResults;
412
+ if (baseResults.length === 0) return extResults;
413
+ const seen = new Set(baseResults.map(tripleKeyFor));
414
+ const merged = [...baseResults];
415
+ for (const entry of extResults) {
416
+ if (!seen.has(tripleKeyFor(entry))) {
417
+ merged.push(entry);
418
+ }
419
+ }
420
+ return Object.freeze(merged);
421
+ },
422
+ validate(aType, axbType, bType, data, scopePath) {
423
+ if (baseKeys.has(tripleKey(aType, axbType, bType))) {
424
+ return base.validate(aType, axbType, bType, data, scopePath);
425
+ }
426
+ return extension.validate(aType, axbType, bType, data, scopePath);
427
+ },
428
+ entries() {
429
+ const extEntries = extension.entries();
430
+ if (extEntries.length === 0) return base.entries();
431
+ const merged = [...base.entries()];
432
+ for (const entry of extEntries) {
433
+ if (!baseKeys.has(tripleKeyFor(entry))) {
434
+ merged.push(entry);
435
+ }
436
+ }
437
+ return Object.freeze(merged);
438
+ }
439
+ };
440
+ }
441
+ function discoveryToEntries(discovery) {
442
+ const entries = [];
443
+ for (const [name, entity] of discovery.nodes) {
444
+ entries.push({
445
+ aType: name,
446
+ axbType: NODE_RELATION,
447
+ bType: name,
448
+ jsonSchema: entity.schema,
449
+ description: entity.description,
450
+ titleField: entity.titleField,
451
+ subtitleField: entity.subtitleField,
452
+ allowedIn: entity.allowedIn,
453
+ migrations: entity.migrations,
454
+ migrationWriteBack: entity.migrationWriteBack
455
+ });
456
+ }
457
+ for (const [axbType, entity] of discovery.edges) {
458
+ const topology = entity.topology;
459
+ if (!topology) continue;
460
+ const fromTypes = Array.isArray(topology.from) ? topology.from : [topology.from];
461
+ const toTypes = Array.isArray(topology.to) ? topology.to : [topology.to];
462
+ const resolvedTargetGraph = entity.targetGraph ?? topology.targetGraph;
463
+ if (resolvedTargetGraph && resolvedTargetGraph.includes("/")) {
464
+ throw new ValidationError(
465
+ `Edge "${axbType}" has invalid targetGraph "${resolvedTargetGraph}" \u2014 must be a single segment (no "/")`
466
+ );
467
+ }
468
+ for (const aType of fromTypes) {
469
+ for (const bType of toTypes) {
470
+ entries.push({
471
+ aType,
472
+ axbType,
473
+ bType,
474
+ jsonSchema: entity.schema,
475
+ description: entity.description,
476
+ inverseLabel: topology.inverseLabel,
477
+ titleField: entity.titleField,
478
+ subtitleField: entity.subtitleField,
479
+ allowedIn: entity.allowedIn,
480
+ targetGraph: resolvedTargetGraph,
481
+ migrations: entity.migrations,
482
+ migrationWriteBack: entity.migrationWriteBack
483
+ });
484
+ }
485
+ }
486
+ }
487
+ return entries;
488
+ }
489
+
490
+ // src/sandbox.ts
491
+ import { createHash as createHash2 } from "crypto";
492
+ var _worker = null;
493
+ var _requestId = 0;
494
+ var _pending = /* @__PURE__ */ new Map();
495
+ var WORKER_SOURCE = [
496
+ `'use strict';`,
497
+ `var _wt = require('node:worker_threads');`,
498
+ `var _mod = require('node:module');`,
499
+ `var _crypto = require('node:crypto');`,
500
+ `var parentPort = _wt.parentPort;`,
501
+ `var workerData = _wt.workerData;`,
502
+ ``,
503
+ `// Load SES using the parent module's resolution context`,
504
+ `var esmRequire = _mod.createRequire(workerData.parentUrl);`,
505
+ `esmRequire('ses');`,
506
+ ``,
507
+ `lockdown({`,
508
+ ` errorTaming: 'unsafe',`,
509
+ ` consoleTaming: 'unsafe',`,
510
+ ` evalTaming: 'safe-eval',`,
511
+ ` overrideTaming: 'moderate',`,
512
+ ` stackFiltering: 'verbose'`,
513
+ `});`,
514
+ ``,
515
+ `// Defense-in-depth: verify lockdown() actually hardened JSON.`,
516
+ `if (!Object.isFrozen(JSON)) {`,
517
+ ` throw new Error('SES lockdown failed: JSON is not frozen');`,
518
+ `}`,
519
+ ``,
520
+ `var cache = new Map();`,
521
+ ``,
522
+ `function hashSource(s) {`,
523
+ ` return _crypto.createHash('sha256').update(s).digest('hex');`,
524
+ `}`,
525
+ ``,
526
+ `function buildWrapper(source) {`,
527
+ ` return '(function() {' +`,
528
+ ` ' var fn = (' + source + ');\\n' +`,
529
+ ` ' if (typeof fn !== "function") return null;\\n' +`,
530
+ ` ' return function(jsonIn) {\\n' +`,
531
+ ` ' var data = JSON.parse(jsonIn);\\n' +`,
532
+ ` ' var result = fn(data);\\n' +`,
533
+ ` ' if (result !== null && typeof result === "object" && typeof result.then === "function") {\\n' +`,
534
+ ` ' return result.then(function(r) { return JSON.stringify(r); });\\n' +`,
535
+ ` ' }\\n' +`,
536
+ ` ' return JSON.stringify(result);\\n' +`,
537
+ ` ' };\\n' +`,
538
+ ` '})()';`,
539
+ `}`,
540
+ ``,
541
+ `function compileSource(source) {`,
542
+ ` var key = hashSource(source);`,
543
+ ` var cached = cache.get(key);`,
544
+ ` if (cached) return cached;`,
545
+ ``,
546
+ ` var compartmentFn;`,
547
+ ` try {`,
548
+ ` var c = new Compartment({ JSON: JSON });`,
549
+ ` compartmentFn = c.evaluate(buildWrapper(source));`,
550
+ ` } catch (err) {`,
551
+ ` throw new Error('Failed to compile migration source: ' + (err.message || String(err)));`,
552
+ ` }`,
553
+ ``,
554
+ ` if (typeof compartmentFn !== 'function') {`,
555
+ ` throw new Error('Migration source did not produce a function: ' + source.slice(0, 80));`,
556
+ ` }`,
557
+ ``,
558
+ ` cache.set(key, compartmentFn);`,
559
+ ` return compartmentFn;`,
560
+ `}`,
561
+ ``,
562
+ `parentPort.on('message', function(msg) {`,
563
+ ` var id = msg.id;`,
564
+ ` try {`,
565
+ ` if (msg.type === 'compile') {`,
566
+ ` compileSource(msg.source);`,
567
+ ` parentPort.postMessage({ id: id, type: 'compiled' });`,
568
+ ` return;`,
569
+ ` }`,
570
+ ` if (msg.type === 'execute') {`,
571
+ ` var fn = compileSource(msg.source);`,
572
+ ` var raw;`,
573
+ ` try {`,
574
+ ` raw = fn(msg.jsonData);`,
575
+ ` } catch (err) {`,
576
+ ` parentPort.postMessage({ id: id, type: 'error', message: 'Migration function threw: ' + (err.message || String(err)) });`,
577
+ ` return;`,
578
+ ` }`,
579
+ ` if (raw !== null && typeof raw === 'object' && typeof raw.then === 'function') {`,
580
+ ` raw.then(`,
581
+ ` function(jsonResult) {`,
582
+ ` if (jsonResult === undefined || jsonResult === null) {`,
583
+ ` parentPort.postMessage({ id: id, type: 'error', message: 'Migration returned a non-JSON-serializable value' });`,
584
+ ` } else {`,
585
+ ` parentPort.postMessage({ id: id, type: 'result', jsonResult: jsonResult });`,
586
+ ` }`,
587
+ ` },`,
588
+ ` function(err) {`,
589
+ ` parentPort.postMessage({ id: id, type: 'error', message: 'Async migration function threw: ' + (err.message || String(err)) });`,
590
+ ` }`,
591
+ ` );`,
592
+ ` return;`,
593
+ ` }`,
594
+ ` if (raw === undefined || raw === null) {`,
595
+ ` parentPort.postMessage({ id: id, type: 'error', message: 'Migration returned a non-JSON-serializable value' });`,
596
+ ` } else {`,
597
+ ` parentPort.postMessage({ id: id, type: 'result', jsonResult: raw });`,
598
+ ` }`,
599
+ ` }`,
600
+ ` } catch (err) {`,
601
+ ` parentPort.postMessage({ id: id, type: 'error', message: err.message || String(err) });`,
602
+ ` }`,
603
+ `});`
604
+ ].join("\n");
605
+ var _WorkerCtor = null;
606
+ async function loadWorkerCtor() {
607
+ if (_WorkerCtor) return _WorkerCtor;
608
+ const wt = await import("worker_threads");
609
+ _WorkerCtor = wt.Worker;
610
+ return _WorkerCtor;
611
+ }
612
+ async function ensureWorker() {
613
+ if (_worker) return _worker;
614
+ const Ctor = await loadWorkerCtor();
615
+ _worker = new Ctor(WORKER_SOURCE, {
616
+ eval: true,
617
+ workerData: { parentUrl: import.meta.url }
618
+ });
619
+ _worker.unref();
620
+ _worker.on("message", (msg) => {
621
+ if (msg.id === void 0) return;
622
+ const pending = _pending.get(msg.id);
623
+ if (!pending) return;
624
+ _pending.delete(msg.id);
625
+ if (msg.type === "error") {
626
+ pending.reject(new MigrationError(msg.message ?? "Unknown sandbox error"));
627
+ } else {
628
+ pending.resolve(msg);
629
+ }
630
+ });
631
+ _worker.on("error", (err) => {
632
+ for (const [, p] of _pending) {
633
+ p.reject(new MigrationError(`Sandbox worker error: ${err.message}`));
634
+ }
635
+ _pending.clear();
636
+ _worker = null;
637
+ });
638
+ _worker.on("exit", (code) => {
639
+ if (_pending.size > 0) {
640
+ for (const [, p] of _pending) {
641
+ p.reject(new MigrationError(`Sandbox worker exited with code ${code}`));
642
+ }
643
+ _pending.clear();
644
+ }
645
+ _worker = null;
646
+ });
647
+ return _worker;
648
+ }
649
+ async function sendToWorker(msg) {
650
+ const worker = await ensureWorker();
651
+ if (_requestId >= Number.MAX_SAFE_INTEGER) _requestId = 0;
652
+ const id = ++_requestId;
653
+ return new Promise((resolve, reject) => {
654
+ _pending.set(id, { resolve, reject });
655
+ worker.postMessage({ ...msg, id });
656
+ });
657
+ }
658
+ var compiledCache = /* @__PURE__ */ new WeakMap();
659
+ function getExecutorCache(executor) {
660
+ let cache = compiledCache.get(executor);
661
+ if (!cache) {
662
+ cache = /* @__PURE__ */ new Map();
663
+ compiledCache.set(executor, cache);
664
+ }
665
+ return cache;
666
+ }
667
+ function hashSource(source) {
668
+ return createHash2("sha256").update(source).digest("hex");
669
+ }
670
+ var _serializationModule = null;
671
+ async function loadSerialization() {
672
+ if (_serializationModule) return _serializationModule;
673
+ _serializationModule = await import("./serialization-C6JNNOCS.js");
674
+ return _serializationModule;
675
+ }
676
+ function defaultExecutor(source) {
677
+ return (async (data) => {
678
+ const { serializeFirestoreTypes, deserializeFirestoreTypes } = await loadSerialization();
679
+ const jsonData = JSON.stringify(serializeFirestoreTypes(data));
680
+ const response = await sendToWorker({ type: "execute", source, jsonData });
681
+ if (response.jsonResult === void 0 || response.jsonResult === null) {
682
+ throw new MigrationError("Migration returned a non-JSON-serializable value");
683
+ }
684
+ try {
685
+ return deserializeFirestoreTypes(JSON.parse(response.jsonResult));
686
+ } catch {
687
+ throw new MigrationError("Migration returned a non-JSON-serializable value");
688
+ }
689
+ });
690
+ }
691
+ async function precompileSource(source, executor) {
692
+ if (executor && executor !== defaultExecutor) {
693
+ try {
694
+ executor(source);
695
+ } catch (err) {
696
+ if (err instanceof MigrationError) throw err;
697
+ throw new MigrationError(`Failed to compile migration source: ${err.message}`);
698
+ }
699
+ return;
700
+ }
701
+ await sendToWorker({ type: "compile", source });
702
+ }
703
+ function compileMigrationFn(source, executor = defaultExecutor) {
704
+ const cache = getExecutorCache(executor);
705
+ const key = hashSource(source);
706
+ const cached = cache.get(key);
707
+ if (cached) return cached;
708
+ try {
709
+ const fn = executor(source);
710
+ cache.set(key, fn);
711
+ return fn;
712
+ } catch (err) {
713
+ if (err instanceof MigrationError) throw err;
714
+ throw new MigrationError(`Failed to compile migration source: ${err.message}`);
715
+ }
716
+ }
717
+ function compileMigrations(stored, executor) {
718
+ return stored.map((step) => ({
719
+ fromVersion: step.fromVersion,
720
+ toVersion: step.toVersion,
721
+ up: compileMigrationFn(step.up, executor)
722
+ }));
723
+ }
724
+ async function destroySandboxWorker() {
725
+ if (!_worker) return;
726
+ const w = _worker;
727
+ _worker = null;
728
+ for (const [, p] of _pending) {
729
+ p.reject(new MigrationError("Sandbox worker terminated"));
730
+ }
731
+ _pending.clear();
732
+ await w.terminate();
733
+ }
734
+
735
+ // src/dynamic-registry.ts
736
+ import { createHash as createHash3 } from "crypto";
737
+ var META_NODE_TYPE = "nodeType";
738
+ var META_EDGE_TYPE = "edgeType";
739
+ var STORED_MIGRATION_STEP_SCHEMA = {
740
+ type: "object",
741
+ required: ["fromVersion", "toVersion", "up"],
742
+ properties: {
743
+ fromVersion: { type: "integer", minimum: 0 },
744
+ toVersion: { type: "integer", minimum: 1 },
745
+ up: { type: "string", minLength: 1 }
746
+ },
747
+ additionalProperties: false
748
+ };
749
+ var NODE_TYPE_SCHEMA = {
750
+ type: "object",
751
+ required: ["name", "jsonSchema"],
752
+ properties: {
753
+ name: { type: "string", minLength: 1 },
754
+ jsonSchema: { type: "object" },
755
+ description: { type: "string" },
756
+ titleField: { type: "string" },
757
+ subtitleField: { type: "string" },
758
+ viewTemplate: { type: "string" },
759
+ viewCss: { type: "string" },
760
+ allowedIn: { type: "array", items: { type: "string", minLength: 1 } },
761
+ schemaVersion: { type: "integer", minimum: 0 },
762
+ migrations: { type: "array", items: STORED_MIGRATION_STEP_SCHEMA },
763
+ migrationWriteBack: { type: "string", enum: ["off", "eager", "background"] }
764
+ },
765
+ additionalProperties: false
766
+ };
767
+ var EDGE_TYPE_SCHEMA = {
768
+ type: "object",
769
+ required: ["name", "from", "to"],
770
+ properties: {
771
+ name: { type: "string", minLength: 1 },
772
+ from: {
773
+ oneOf: [
774
+ { type: "string", minLength: 1 },
775
+ { type: "array", items: { type: "string", minLength: 1 }, minItems: 1 }
776
+ ]
777
+ },
778
+ to: {
779
+ oneOf: [
780
+ { type: "string", minLength: 1 },
781
+ { type: "array", items: { type: "string", minLength: 1 }, minItems: 1 }
782
+ ]
783
+ },
784
+ jsonSchema: { type: "object" },
785
+ inverseLabel: { type: "string" },
786
+ description: { type: "string" },
787
+ titleField: { type: "string" },
788
+ subtitleField: { type: "string" },
789
+ viewTemplate: { type: "string" },
790
+ viewCss: { type: "string" },
791
+ allowedIn: { type: "array", items: { type: "string", minLength: 1 } },
792
+ targetGraph: { type: "string", minLength: 1, pattern: "^[^/]+$" },
793
+ schemaVersion: { type: "integer", minimum: 0 },
794
+ migrations: { type: "array", items: STORED_MIGRATION_STEP_SCHEMA },
795
+ migrationWriteBack: { type: "string", enum: ["off", "eager", "background"] }
796
+ },
797
+ additionalProperties: false
798
+ };
799
+ var BOOTSTRAP_ENTRIES = [
800
+ {
801
+ aType: META_NODE_TYPE,
802
+ axbType: NODE_RELATION,
803
+ bType: META_NODE_TYPE,
804
+ jsonSchema: NODE_TYPE_SCHEMA,
805
+ description: "Meta-type: defines a node type"
806
+ },
807
+ {
808
+ aType: META_EDGE_TYPE,
809
+ axbType: NODE_RELATION,
810
+ bType: META_EDGE_TYPE,
811
+ jsonSchema: EDGE_TYPE_SCHEMA,
812
+ description: "Meta-type: defines an edge type"
813
+ }
814
+ ];
815
+ function createBootstrapRegistry() {
816
+ return createRegistry([...BOOTSTRAP_ENTRIES]);
817
+ }
818
+ function generateDeterministicUid(metaType, name) {
819
+ const hash = createHash3("sha256").update(`${metaType}:${name}`).digest("base64url");
820
+ return hash.slice(0, 21);
821
+ }
822
+ async function createRegistryFromGraph(reader, executor) {
823
+ const [nodeTypes, edgeTypes] = await Promise.all([
824
+ reader.findNodes({ aType: META_NODE_TYPE }),
825
+ reader.findNodes({ aType: META_EDGE_TYPE })
826
+ ]);
827
+ const entries = [...BOOTSTRAP_ENTRIES];
828
+ const prevalidations = [];
829
+ for (const record of nodeTypes) {
830
+ const data = record.data;
831
+ if (data.migrations) {
832
+ for (const m of data.migrations) {
833
+ prevalidations.push(precompileSource(m.up, executor));
834
+ }
835
+ }
836
+ }
837
+ for (const record of edgeTypes) {
838
+ const data = record.data;
839
+ if (data.migrations) {
840
+ for (const m of data.migrations) {
841
+ prevalidations.push(precompileSource(m.up, executor));
842
+ }
843
+ }
844
+ }
845
+ await Promise.all(prevalidations);
846
+ for (const record of nodeTypes) {
847
+ const data = record.data;
848
+ entries.push({
849
+ aType: data.name,
850
+ axbType: NODE_RELATION,
851
+ bType: data.name,
852
+ jsonSchema: data.jsonSchema,
853
+ description: data.description,
854
+ titleField: data.titleField,
855
+ subtitleField: data.subtitleField,
856
+ allowedIn: data.allowedIn,
857
+ migrations: data.migrations ? compileMigrations(data.migrations, executor) : void 0,
858
+ migrationWriteBack: data.migrationWriteBack
859
+ });
860
+ }
861
+ for (const record of edgeTypes) {
862
+ const data = record.data;
863
+ const fromTypes = Array.isArray(data.from) ? data.from : [data.from];
864
+ const toTypes = Array.isArray(data.to) ? data.to : [data.to];
865
+ const compiledMigrations = data.migrations ? compileMigrations(data.migrations, executor) : void 0;
866
+ for (const aType of fromTypes) {
867
+ for (const bType of toTypes) {
868
+ entries.push({
869
+ aType,
870
+ axbType: data.name,
871
+ bType,
872
+ jsonSchema: data.jsonSchema,
873
+ description: data.description,
874
+ inverseLabel: data.inverseLabel,
875
+ titleField: data.titleField,
876
+ subtitleField: data.subtitleField,
877
+ allowedIn: data.allowedIn,
878
+ targetGraph: data.targetGraph,
879
+ migrations: compiledMigrations,
880
+ migrationWriteBack: data.migrationWriteBack
881
+ });
882
+ }
883
+ }
884
+ }
885
+ return createRegistry(entries);
886
+ }
887
+
888
+ // src/query.ts
889
+ function buildEdgeQueryPlan(params) {
890
+ const { aType, aUid, axbType, bType, bUid, limit, orderBy } = params;
891
+ if (aUid && axbType && bUid && !params.where?.length) {
892
+ return { strategy: "get", docId: computeEdgeDocId(aUid, axbType, bUid) };
893
+ }
894
+ const filters = [];
895
+ if (aType) filters.push({ field: "aType", op: "==", value: aType });
896
+ if (aUid) filters.push({ field: "aUid", op: "==", value: aUid });
897
+ if (axbType) filters.push({ field: "axbType", op: "==", value: axbType });
898
+ if (bType) filters.push({ field: "bType", op: "==", value: bType });
899
+ if (bUid) filters.push({ field: "bUid", op: "==", value: bUid });
900
+ if (params.where) {
901
+ for (const clause of params.where) {
902
+ const field = BUILTIN_FIELDS.has(clause.field) ? clause.field : clause.field.startsWith("data.") ? clause.field : `data.${clause.field}`;
903
+ filters.push({ field, op: clause.op, value: clause.value });
904
+ }
905
+ }
906
+ if (filters.length === 0) {
907
+ throw new InvalidQueryError("findEdges requires at least one filter parameter");
908
+ }
909
+ const effectiveLimit = limit === void 0 ? DEFAULT_QUERY_LIMIT : limit || void 0;
910
+ return { strategy: "query", filters, options: { limit: effectiveLimit, orderBy } };
911
+ }
912
+ function buildNodeQueryPlan(params) {
913
+ const { aType, limit, orderBy } = params;
914
+ const filters = [
915
+ { field: "aType", op: "==", value: aType },
916
+ { field: "axbType", op: "==", value: NODE_RELATION }
917
+ ];
918
+ if (params.where) {
919
+ for (const clause of params.where) {
920
+ const field = BUILTIN_FIELDS.has(clause.field) ? clause.field : clause.field.startsWith("data.") ? clause.field : `data.${clause.field}`;
921
+ filters.push({ field, op: clause.op, value: clause.value });
922
+ }
923
+ }
924
+ const effectiveLimit = limit === void 0 ? DEFAULT_QUERY_LIMIT : limit || void 0;
925
+ return { strategy: "query", filters, options: { limit: effectiveLimit, orderBy } };
926
+ }
927
+
928
+ // src/query-safety.ts
929
+ var SAFE_INDEX_PATTERNS = [
930
+ /* @__PURE__ */ new Set(["aUid", "axbType"]),
931
+ /* @__PURE__ */ new Set(["axbType", "bUid"]),
932
+ /* @__PURE__ */ new Set(["aType", "axbType"]),
933
+ /* @__PURE__ */ new Set(["axbType", "bType"])
934
+ ];
935
+ function analyzeQuerySafety(filters) {
936
+ const builtinFieldsPresent = /* @__PURE__ */ new Set();
937
+ let hasDataFilters = false;
938
+ for (const f of filters) {
939
+ if (BUILTIN_FIELDS.has(f.field)) {
940
+ builtinFieldsPresent.add(f.field);
941
+ } else {
942
+ hasDataFilters = true;
943
+ }
944
+ }
945
+ for (const pattern of SAFE_INDEX_PATTERNS) {
946
+ let matched = true;
947
+ for (const field of pattern) {
948
+ if (!builtinFieldsPresent.has(field)) {
949
+ matched = false;
950
+ break;
951
+ }
952
+ }
953
+ if (matched) {
954
+ return { safe: true };
955
+ }
956
+ }
957
+ const presentFields = [...builtinFieldsPresent];
958
+ if (presentFields.length === 0 && hasDataFilters) {
959
+ return {
960
+ safe: false,
961
+ reason: "Query filters only use data.* fields with no builtin field constraints. This requires a full collection scan. Add aType, aUid, axbType, bType, or bUid filters, or set allowCollectionScan: true."
962
+ };
963
+ }
964
+ if (hasDataFilters) {
965
+ return {
966
+ safe: false,
967
+ reason: `Query filters on [${presentFields.join(", ")}] do not match any indexed pattern. data.* filters without an indexed base require a full collection scan. Safe patterns: (aUid + axbType), (axbType + bUid), (aType + axbType), (axbType + bType). Set allowCollectionScan: true to override.`
968
+ };
969
+ }
970
+ return {
971
+ safe: false,
972
+ reason: `Query filters on [${presentFields.join(", ")}] do not match any indexed pattern. This may cause a full collection scan on Firestore Enterprise. Safe patterns: (aUid + axbType), (axbType + bUid), (aType + axbType), (axbType + bType). Set allowCollectionScan: true to override.`
973
+ };
974
+ }
975
+
976
+ // src/batch.ts
977
+ function buildWritableNodeRecord(aType, uid, data) {
978
+ return { aType, aUid: uid, axbType: NODE_RELATION, bType: aType, bUid: uid, data };
979
+ }
980
+ function buildWritableEdgeRecord(aType, aUid, axbType, bType, bUid, data) {
981
+ return { aType, aUid, axbType, bType, bUid, data };
982
+ }
983
+ var GraphBatchImpl = class {
984
+ constructor(backend, registry, scopePath = "") {
985
+ this.backend = backend;
986
+ this.registry = registry;
987
+ this.scopePath = scopePath;
988
+ }
989
+ async putNode(aType, uid, data) {
990
+ if (this.registry) {
991
+ this.registry.validate(aType, NODE_RELATION, aType, data, this.scopePath);
992
+ }
993
+ const docId = computeNodeDocId(uid);
994
+ const record = buildWritableNodeRecord(aType, uid, data);
995
+ if (this.registry) {
996
+ const entry = this.registry.lookup(aType, NODE_RELATION, aType);
997
+ if (entry?.schemaVersion && entry.schemaVersion > 0) {
998
+ record.v = entry.schemaVersion;
999
+ }
1000
+ }
1001
+ this.backend.setDoc(docId, record);
1002
+ }
1003
+ async putEdge(aType, aUid, axbType, bType, bUid, data) {
1004
+ if (this.registry) {
1005
+ this.registry.validate(aType, axbType, bType, data, this.scopePath);
1006
+ }
1007
+ const docId = computeEdgeDocId(aUid, axbType, bUid);
1008
+ const record = buildWritableEdgeRecord(aType, aUid, axbType, bType, bUid, data);
1009
+ if (this.registry) {
1010
+ const entry = this.registry.lookup(aType, axbType, bType);
1011
+ if (entry?.schemaVersion && entry.schemaVersion > 0) {
1012
+ record.v = entry.schemaVersion;
1013
+ }
1014
+ }
1015
+ this.backend.setDoc(docId, record);
1016
+ }
1017
+ async updateNode(uid, data) {
1018
+ const docId = computeNodeDocId(uid);
1019
+ this.backend.updateDoc(docId, { dataFields: data });
1020
+ }
1021
+ async removeNode(uid) {
1022
+ const docId = computeNodeDocId(uid);
1023
+ this.backend.deleteDoc(docId);
1024
+ }
1025
+ async removeEdge(aUid, axbType, bUid) {
1026
+ const docId = computeEdgeDocId(aUid, axbType, bUid);
1027
+ this.backend.deleteDoc(docId);
1028
+ }
1029
+ async commit() {
1030
+ await this.backend.commit();
1031
+ }
1032
+ };
1033
+
1034
+ // src/transaction.ts
1035
+ function buildWritableNodeRecord2(aType, uid, data) {
1036
+ return { aType, aUid: uid, axbType: NODE_RELATION, bType: aType, bUid: uid, data };
1037
+ }
1038
+ function buildWritableEdgeRecord2(aType, aUid, axbType, bType, bUid, data) {
1039
+ return { aType, aUid, axbType, bType, bUid, data };
1040
+ }
1041
+ var GraphTransactionImpl = class {
1042
+ constructor(backend, registry, scanProtection = "error", scopePath = "", globalWriteBack = "off") {
1043
+ this.backend = backend;
1044
+ this.registry = registry;
1045
+ this.scanProtection = scanProtection;
1046
+ this.scopePath = scopePath;
1047
+ this.globalWriteBack = globalWriteBack;
1048
+ }
1049
+ async getNode(uid) {
1050
+ const docId = computeNodeDocId(uid);
1051
+ const record = await this.backend.getDoc(docId);
1052
+ if (!record || !this.registry) return record;
1053
+ const result = await migrateRecord(record, this.registry, this.globalWriteBack);
1054
+ if (result.migrated && result.writeBack !== "off") {
1055
+ await this.backend.updateDoc(docId, {
1056
+ replaceData: result.record.data,
1057
+ v: result.record.v
1058
+ });
1059
+ }
1060
+ return result.record;
1061
+ }
1062
+ async getEdge(aUid, axbType, bUid) {
1063
+ const docId = computeEdgeDocId(aUid, axbType, bUid);
1064
+ const record = await this.backend.getDoc(docId);
1065
+ if (!record || !this.registry) return record;
1066
+ const result = await migrateRecord(record, this.registry, this.globalWriteBack);
1067
+ if (result.migrated && result.writeBack !== "off") {
1068
+ await this.backend.updateDoc(docId, {
1069
+ replaceData: result.record.data,
1070
+ v: result.record.v
1071
+ });
1072
+ }
1073
+ return result.record;
1074
+ }
1075
+ async edgeExists(aUid, axbType, bUid) {
1076
+ const docId = computeEdgeDocId(aUid, axbType, bUid);
1077
+ const record = await this.backend.getDoc(docId);
1078
+ return record !== null;
1079
+ }
1080
+ checkQuerySafety(filters, allowCollectionScan) {
1081
+ if (allowCollectionScan || this.scanProtection === "off") return;
1082
+ const result = analyzeQuerySafety(filters);
1083
+ if (result.safe) return;
1084
+ if (this.scanProtection === "error") {
1085
+ throw new QuerySafetyError(result.reason);
1086
+ }
1087
+ console.warn(`[firegraph] Query safety warning: ${result.reason}`);
1088
+ }
1089
+ async findEdges(params) {
1090
+ const plan = buildEdgeQueryPlan(params);
1091
+ let records;
1092
+ if (plan.strategy === "get") {
1093
+ const record = await this.backend.getDoc(plan.docId);
1094
+ records = record ? [record] : [];
1095
+ } else {
1096
+ this.checkQuerySafety(plan.filters, params.allowCollectionScan);
1097
+ records = await this.backend.query(plan.filters, plan.options);
1098
+ }
1099
+ return this.applyMigrations(records);
1100
+ }
1101
+ async findNodes(params) {
1102
+ const plan = buildNodeQueryPlan(params);
1103
+ let records;
1104
+ if (plan.strategy === "get") {
1105
+ const record = await this.backend.getDoc(plan.docId);
1106
+ records = record ? [record] : [];
1107
+ } else {
1108
+ this.checkQuerySafety(plan.filters, params.allowCollectionScan);
1109
+ records = await this.backend.query(plan.filters, plan.options);
1110
+ }
1111
+ return this.applyMigrations(records);
1112
+ }
1113
+ async applyMigrations(records) {
1114
+ if (!this.registry || records.length === 0) return records;
1115
+ const results = await migrateRecords(records, this.registry, this.globalWriteBack);
1116
+ for (const result of results) {
1117
+ if (result.migrated && result.writeBack !== "off") {
1118
+ const docId = result.record.axbType === NODE_RELATION ? computeNodeDocId(result.record.aUid) : computeEdgeDocId(result.record.aUid, result.record.axbType, result.record.bUid);
1119
+ await this.backend.updateDoc(docId, {
1120
+ replaceData: result.record.data,
1121
+ v: result.record.v
1122
+ });
1123
+ }
1124
+ }
1125
+ return results.map((r) => r.record);
1126
+ }
1127
+ async putNode(aType, uid, data) {
1128
+ if (this.registry) {
1129
+ this.registry.validate(aType, NODE_RELATION, aType, data, this.scopePath);
1130
+ }
1131
+ const docId = computeNodeDocId(uid);
1132
+ const record = buildWritableNodeRecord2(aType, uid, data);
1133
+ if (this.registry) {
1134
+ const entry = this.registry.lookup(aType, NODE_RELATION, aType);
1135
+ if (entry?.schemaVersion && entry.schemaVersion > 0) {
1136
+ record.v = entry.schemaVersion;
1137
+ }
1138
+ }
1139
+ await this.backend.setDoc(docId, record);
1140
+ }
1141
+ async putEdge(aType, aUid, axbType, bType, bUid, data) {
1142
+ if (this.registry) {
1143
+ this.registry.validate(aType, axbType, bType, data, this.scopePath);
1144
+ }
1145
+ const docId = computeEdgeDocId(aUid, axbType, bUid);
1146
+ const record = buildWritableEdgeRecord2(aType, aUid, axbType, bType, bUid, data);
1147
+ if (this.registry) {
1148
+ const entry = this.registry.lookup(aType, axbType, bType);
1149
+ if (entry?.schemaVersion && entry.schemaVersion > 0) {
1150
+ record.v = entry.schemaVersion;
1151
+ }
1152
+ }
1153
+ await this.backend.setDoc(docId, record);
1154
+ }
1155
+ async updateNode(uid, data) {
1156
+ const docId = computeNodeDocId(uid);
1157
+ await this.backend.updateDoc(docId, { dataFields: data });
1158
+ }
1159
+ async removeNode(uid) {
1160
+ const docId = computeNodeDocId(uid);
1161
+ await this.backend.deleteDoc(docId);
1162
+ }
1163
+ async removeEdge(aUid, axbType, bUid) {
1164
+ const docId = computeEdgeDocId(aUid, axbType, bUid);
1165
+ await this.backend.deleteDoc(docId);
1166
+ }
1167
+ };
1168
+
1169
+ // src/client.ts
1170
+ var RESERVED_TYPE_NAMES = /* @__PURE__ */ new Set([META_NODE_TYPE, META_EDGE_TYPE]);
1171
+ function buildWritableNodeRecord3(aType, uid, data) {
1172
+ return { aType, aUid: uid, axbType: NODE_RELATION, bType: aType, bUid: uid, data };
1173
+ }
1174
+ function buildWritableEdgeRecord3(aType, aUid, axbType, bType, bUid, data) {
1175
+ return { aType, aUid, axbType, bType, bUid, data };
1176
+ }
1177
+ var GraphClientImpl = class _GraphClientImpl {
1178
+ constructor(backend, options, metaBackend) {
1179
+ this.backend = backend;
1180
+ this.globalWriteBack = options?.migrationWriteBack ?? "off";
1181
+ this.migrationSandbox = options?.migrationSandbox;
1182
+ if (options?.registryMode) {
1183
+ this.dynamicConfig = options.registryMode;
1184
+ this.bootstrapRegistry = createBootstrapRegistry();
1185
+ if (options.registry) {
1186
+ this.staticRegistry = options.registry;
1187
+ }
1188
+ this.metaBackend = metaBackend;
1189
+ } else {
1190
+ this.staticRegistry = options?.registry;
1191
+ }
1192
+ this.scanProtection = options?.scanProtection ?? "error";
1193
+ }
1194
+ scanProtection;
1195
+ // Static mode
1196
+ staticRegistry;
1197
+ // Dynamic mode
1198
+ dynamicConfig;
1199
+ bootstrapRegistry;
1200
+ dynamicRegistry;
1201
+ metaBackend;
1202
+ // Migration settings
1203
+ globalWriteBack;
1204
+ migrationSandbox;
1205
+ // ---------------------------------------------------------------------------
1206
+ // Backend access (exposed for traversal helpers and subgraph cloning)
1207
+ // ---------------------------------------------------------------------------
1208
+ /** @internal */
1209
+ getBackend() {
1210
+ return this.backend;
1211
+ }
1212
+ // ---------------------------------------------------------------------------
1213
+ // Registry routing
1214
+ // ---------------------------------------------------------------------------
1215
+ getRegistryForType(aType) {
1216
+ if (!this.dynamicConfig) return this.staticRegistry;
1217
+ if (aType === META_NODE_TYPE || aType === META_EDGE_TYPE) {
1218
+ return this.bootstrapRegistry;
1219
+ }
1220
+ return this.dynamicRegistry ?? this.staticRegistry ?? this.bootstrapRegistry;
1221
+ }
1222
+ getBackendForType(aType) {
1223
+ if (this.metaBackend && (aType === META_NODE_TYPE || aType === META_EDGE_TYPE)) {
1224
+ return this.metaBackend;
1225
+ }
1226
+ return this.backend;
1227
+ }
1228
+ getCombinedRegistry() {
1229
+ if (!this.dynamicConfig) return this.staticRegistry;
1230
+ return this.dynamicRegistry ?? this.staticRegistry ?? this.bootstrapRegistry;
1231
+ }
1232
+ // ---------------------------------------------------------------------------
1233
+ // Query safety
1234
+ // ---------------------------------------------------------------------------
1235
+ checkQuerySafety(filters, allowCollectionScan) {
1236
+ if (allowCollectionScan || this.scanProtection === "off") return;
1237
+ const result = analyzeQuerySafety(filters);
1238
+ if (result.safe) return;
1239
+ if (this.scanProtection === "error") {
1240
+ throw new QuerySafetyError(result.reason);
1241
+ }
1242
+ console.warn(`[firegraph] Query safety warning: ${result.reason}`);
1243
+ }
1244
+ // ---------------------------------------------------------------------------
1245
+ // Migration helpers
1246
+ // ---------------------------------------------------------------------------
1247
+ async applyMigration(record, docId) {
1248
+ const registry = this.getCombinedRegistry();
1249
+ if (!registry) return record;
1250
+ const result = await migrateRecord(record, registry, this.globalWriteBack);
1251
+ if (result.migrated) {
1252
+ this.handleWriteBack(result, docId);
1253
+ }
1254
+ return result.record;
1255
+ }
1256
+ async applyMigrations(records) {
1257
+ const registry = this.getCombinedRegistry();
1258
+ if (!registry || records.length === 0) return records;
1259
+ const results = await migrateRecords(records, registry, this.globalWriteBack);
1260
+ for (const result of results) {
1261
+ if (result.migrated) {
1262
+ const docId = result.record.axbType === NODE_RELATION ? computeNodeDocId(result.record.aUid) : computeEdgeDocId(result.record.aUid, result.record.axbType, result.record.bUid);
1263
+ this.handleWriteBack(result, docId);
1264
+ }
1265
+ }
1266
+ return results.map((r) => r.record);
1267
+ }
1268
+ /**
1269
+ * Fire-and-forget write-back for a migrated record. Both `'eager'` and
1270
+ * `'background'` are non-blocking; the difference is the log level on
1271
+ * failure. For synchronous write-back, use a transaction — see
1272
+ * `GraphTransactionImpl`.
1273
+ */
1274
+ handleWriteBack(result, docId) {
1275
+ if (result.writeBack === "off") return;
1276
+ const doWriteBack = async () => {
1277
+ try {
1278
+ await this.backend.updateDoc(docId, {
1279
+ replaceData: result.record.data,
1280
+ v: result.record.v
1281
+ });
1282
+ } catch (err) {
1283
+ const msg = `[firegraph] Migration write-back failed for ${docId}: ${err.message}`;
1284
+ if (result.writeBack === "eager") {
1285
+ console.error(msg);
1286
+ } else {
1287
+ console.warn(msg);
1288
+ }
1289
+ }
1290
+ };
1291
+ void doWriteBack();
1292
+ }
1293
+ // ---------------------------------------------------------------------------
1294
+ // GraphReader
1295
+ // ---------------------------------------------------------------------------
1296
+ async getNode(uid) {
1297
+ const docId = computeNodeDocId(uid);
1298
+ const record = await this.backend.getDoc(docId);
1299
+ if (!record) return null;
1300
+ return this.applyMigration(record, docId);
1301
+ }
1302
+ async getEdge(aUid, axbType, bUid) {
1303
+ const docId = computeEdgeDocId(aUid, axbType, bUid);
1304
+ const record = await this.backend.getDoc(docId);
1305
+ if (!record) return null;
1306
+ return this.applyMigration(record, docId);
1307
+ }
1308
+ async edgeExists(aUid, axbType, bUid) {
1309
+ const docId = computeEdgeDocId(aUid, axbType, bUid);
1310
+ const record = await this.backend.getDoc(docId);
1311
+ return record !== null;
1312
+ }
1313
+ async findEdges(params) {
1314
+ const plan = buildEdgeQueryPlan(params);
1315
+ let records;
1316
+ if (plan.strategy === "get") {
1317
+ const record = await this.backend.getDoc(plan.docId);
1318
+ records = record ? [record] : [];
1319
+ } else {
1320
+ this.checkQuerySafety(plan.filters, params.allowCollectionScan);
1321
+ records = await this.backend.query(plan.filters, plan.options);
1322
+ }
1323
+ return this.applyMigrations(records);
1324
+ }
1325
+ async findNodes(params) {
1326
+ const plan = buildNodeQueryPlan(params);
1327
+ let records;
1328
+ if (plan.strategy === "get") {
1329
+ const record = await this.backend.getDoc(plan.docId);
1330
+ records = record ? [record] : [];
1331
+ } else {
1332
+ this.checkQuerySafety(plan.filters, params.allowCollectionScan);
1333
+ records = await this.backend.query(plan.filters, plan.options);
1334
+ }
1335
+ return this.applyMigrations(records);
1336
+ }
1337
+ // ---------------------------------------------------------------------------
1338
+ // GraphWriter
1339
+ // ---------------------------------------------------------------------------
1340
+ async putNode(aType, uid, data) {
1341
+ const registry = this.getRegistryForType(aType);
1342
+ if (registry) {
1343
+ registry.validate(aType, NODE_RELATION, aType, data, this.backend.scopePath);
1344
+ }
1345
+ const backend = this.getBackendForType(aType);
1346
+ const docId = computeNodeDocId(uid);
1347
+ const record = buildWritableNodeRecord3(aType, uid, data);
1348
+ if (registry) {
1349
+ const entry = registry.lookup(aType, NODE_RELATION, aType);
1350
+ if (entry?.schemaVersion && entry.schemaVersion > 0) {
1351
+ record.v = entry.schemaVersion;
1352
+ }
1353
+ }
1354
+ await backend.setDoc(docId, record);
1355
+ }
1356
+ async putEdge(aType, aUid, axbType, bType, bUid, data) {
1357
+ const registry = this.getRegistryForType(aType);
1358
+ if (registry) {
1359
+ registry.validate(aType, axbType, bType, data, this.backend.scopePath);
1360
+ }
1361
+ const backend = this.getBackendForType(aType);
1362
+ const docId = computeEdgeDocId(aUid, axbType, bUid);
1363
+ const record = buildWritableEdgeRecord3(aType, aUid, axbType, bType, bUid, data);
1364
+ if (registry) {
1365
+ const entry = registry.lookup(aType, axbType, bType);
1366
+ if (entry?.schemaVersion && entry.schemaVersion > 0) {
1367
+ record.v = entry.schemaVersion;
1368
+ }
1369
+ }
1370
+ await backend.setDoc(docId, record);
1371
+ }
1372
+ async updateNode(uid, data) {
1373
+ const docId = computeNodeDocId(uid);
1374
+ await this.backend.updateDoc(docId, { dataFields: data });
1375
+ }
1376
+ async removeNode(uid) {
1377
+ const docId = computeNodeDocId(uid);
1378
+ await this.backend.deleteDoc(docId);
1379
+ }
1380
+ async removeEdge(aUid, axbType, bUid) {
1381
+ const docId = computeEdgeDocId(aUid, axbType, bUid);
1382
+ await this.backend.deleteDoc(docId);
1383
+ }
1384
+ // ---------------------------------------------------------------------------
1385
+ // Transactions & Batches
1386
+ // ---------------------------------------------------------------------------
1387
+ async runTransaction(fn) {
1388
+ return this.backend.runTransaction(async (txBackend) => {
1389
+ const graphTx = new GraphTransactionImpl(
1390
+ txBackend,
1391
+ this.getCombinedRegistry(),
1392
+ this.scanProtection,
1393
+ this.backend.scopePath,
1394
+ this.globalWriteBack
1395
+ );
1396
+ return fn(graphTx);
1397
+ });
1398
+ }
1399
+ batch() {
1400
+ return new GraphBatchImpl(
1401
+ this.backend.createBatch(),
1402
+ this.getCombinedRegistry(),
1403
+ this.backend.scopePath
1404
+ );
1405
+ }
1406
+ // ---------------------------------------------------------------------------
1407
+ // Subgraph
1408
+ // ---------------------------------------------------------------------------
1409
+ subgraph(parentNodeUid, name = "graph") {
1410
+ if (!parentNodeUid || parentNodeUid.includes("/")) {
1411
+ throw new FiregraphError(
1412
+ `Invalid parentNodeUid for subgraph: "${parentNodeUid}". Must be a non-empty string without "/".`,
1413
+ "INVALID_SUBGRAPH"
1414
+ );
1415
+ }
1416
+ if (name.includes("/")) {
1417
+ throw new FiregraphError(
1418
+ `Subgraph name must not contain "/": got "${name}". Use chained .subgraph() calls for nested subgraphs.`,
1419
+ "INVALID_SUBGRAPH"
1420
+ );
1421
+ }
1422
+ const childBackend = this.backend.subgraph(parentNodeUid, name);
1423
+ return new _GraphClientImpl(
1424
+ childBackend,
1425
+ {
1426
+ registry: this.getCombinedRegistry(),
1427
+ scanProtection: this.scanProtection,
1428
+ migrationWriteBack: this.globalWriteBack,
1429
+ migrationSandbox: this.migrationSandbox
1430
+ }
1431
+ // Subgraphs do not have meta-backends; meta lives only at the root.
1432
+ );
1433
+ }
1434
+ // ---------------------------------------------------------------------------
1435
+ // Collection group query
1436
+ // ---------------------------------------------------------------------------
1437
+ async findEdgesGlobal(params, collectionName) {
1438
+ if (!this.backend.findEdgesGlobal) {
1439
+ throw new FiregraphError(
1440
+ "findEdgesGlobal() is not supported by the current storage backend.",
1441
+ "UNSUPPORTED_OPERATION"
1442
+ );
1443
+ }
1444
+ const plan = buildEdgeQueryPlan(params);
1445
+ if (plan.strategy === "get") {
1446
+ throw new FiregraphError(
1447
+ "findEdgesGlobal() requires a query, not a direct document lookup. Omit one of aUid/axbType/bUid to force a query strategy.",
1448
+ "INVALID_QUERY"
1449
+ );
1450
+ }
1451
+ this.checkQuerySafety(plan.filters, params.allowCollectionScan);
1452
+ const records = await this.backend.findEdgesGlobal(params, collectionName);
1453
+ return this.applyMigrations(records);
1454
+ }
1455
+ // ---------------------------------------------------------------------------
1456
+ // Bulk operations
1457
+ // ---------------------------------------------------------------------------
1458
+ async removeNodeCascade(uid, options) {
1459
+ return this.backend.removeNodeCascade(uid, this, options);
1460
+ }
1461
+ async bulkRemoveEdges(params, options) {
1462
+ return this.backend.bulkRemoveEdges(params, this, options);
1463
+ }
1464
+ // ---------------------------------------------------------------------------
1465
+ // Dynamic registry methods
1466
+ // ---------------------------------------------------------------------------
1467
+ async defineNodeType(name, jsonSchema, description, options) {
1468
+ if (!this.dynamicConfig) {
1469
+ throw new DynamicRegistryError(
1470
+ 'defineNodeType() is only available in dynamic registry mode. Pass registryMode: { mode: "dynamic" } to createGraphClient().'
1471
+ );
1472
+ }
1473
+ if (RESERVED_TYPE_NAMES.has(name)) {
1474
+ throw new DynamicRegistryError(
1475
+ `Cannot define type "${name}": this name is reserved for the meta-registry.`
1476
+ );
1477
+ }
1478
+ if (this.staticRegistry?.lookup(name, NODE_RELATION, name)) {
1479
+ throw new DynamicRegistryError(
1480
+ `Cannot define node type "${name}": already defined in the static registry.`
1481
+ );
1482
+ }
1483
+ const uid = generateDeterministicUid(META_NODE_TYPE, name);
1484
+ const data = { name, jsonSchema };
1485
+ if (description !== void 0) data.description = description;
1486
+ if (options?.titleField !== void 0) data.titleField = options.titleField;
1487
+ if (options?.subtitleField !== void 0) data.subtitleField = options.subtitleField;
1488
+ if (options?.viewTemplate !== void 0) data.viewTemplate = options.viewTemplate;
1489
+ if (options?.viewCss !== void 0) data.viewCss = options.viewCss;
1490
+ if (options?.allowedIn !== void 0) data.allowedIn = options.allowedIn;
1491
+ if (options?.migrationWriteBack !== void 0)
1492
+ data.migrationWriteBack = options.migrationWriteBack;
1493
+ if (options?.migrations !== void 0) {
1494
+ data.migrations = await this.serializeMigrations(options.migrations);
1495
+ }
1496
+ await this.putNode(META_NODE_TYPE, uid, data);
1497
+ }
1498
+ async defineEdgeType(name, topology, jsonSchema, description, options) {
1499
+ if (!this.dynamicConfig) {
1500
+ throw new DynamicRegistryError(
1501
+ 'defineEdgeType() is only available in dynamic registry mode. Pass registryMode: { mode: "dynamic" } to createGraphClient().'
1502
+ );
1503
+ }
1504
+ if (RESERVED_TYPE_NAMES.has(name)) {
1505
+ throw new DynamicRegistryError(
1506
+ `Cannot define type "${name}": this name is reserved for the meta-registry.`
1507
+ );
1508
+ }
1509
+ if (this.staticRegistry) {
1510
+ const fromTypes = Array.isArray(topology.from) ? topology.from : [topology.from];
1511
+ const toTypes = Array.isArray(topology.to) ? topology.to : [topology.to];
1512
+ for (const aType of fromTypes) {
1513
+ for (const bType of toTypes) {
1514
+ if (this.staticRegistry.lookup(aType, name, bType)) {
1515
+ throw new DynamicRegistryError(
1516
+ `Cannot define edge type "${name}" for (${aType}) -> (${bType}): already defined in the static registry.`
1517
+ );
1518
+ }
1519
+ }
1520
+ }
1521
+ }
1522
+ const uid = generateDeterministicUid(META_EDGE_TYPE, name);
1523
+ const data = {
1524
+ name,
1525
+ from: topology.from,
1526
+ to: topology.to
1527
+ };
1528
+ if (jsonSchema !== void 0) data.jsonSchema = jsonSchema;
1529
+ if (topology.inverseLabel !== void 0) data.inverseLabel = topology.inverseLabel;
1530
+ if (topology.targetGraph !== void 0) data.targetGraph = topology.targetGraph;
1531
+ if (description !== void 0) data.description = description;
1532
+ if (options?.titleField !== void 0) data.titleField = options.titleField;
1533
+ if (options?.subtitleField !== void 0) data.subtitleField = options.subtitleField;
1534
+ if (options?.viewTemplate !== void 0) data.viewTemplate = options.viewTemplate;
1535
+ if (options?.viewCss !== void 0) data.viewCss = options.viewCss;
1536
+ if (options?.allowedIn !== void 0) data.allowedIn = options.allowedIn;
1537
+ if (options?.migrationWriteBack !== void 0)
1538
+ data.migrationWriteBack = options.migrationWriteBack;
1539
+ if (options?.migrations !== void 0) {
1540
+ data.migrations = await this.serializeMigrations(options.migrations);
1541
+ }
1542
+ await this.putNode(META_EDGE_TYPE, uid, data);
1543
+ }
1544
+ async reloadRegistry() {
1545
+ if (!this.dynamicConfig) {
1546
+ throw new DynamicRegistryError(
1547
+ 'reloadRegistry() is only available in dynamic registry mode. Pass registryMode: { mode: "dynamic" } to createGraphClient().'
1548
+ );
1549
+ }
1550
+ const reader = this.createMetaReader();
1551
+ const dynamicOnly = await createRegistryFromGraph(reader, this.migrationSandbox);
1552
+ if (this.staticRegistry) {
1553
+ this.dynamicRegistry = createMergedRegistry(this.staticRegistry, dynamicOnly);
1554
+ } else {
1555
+ this.dynamicRegistry = dynamicOnly;
1556
+ }
1557
+ }
1558
+ async serializeMigrations(migrations) {
1559
+ const result = migrations.map((m) => {
1560
+ const source = typeof m.up === "function" ? m.up.toString() : m.up;
1561
+ return { fromVersion: m.fromVersion, toVersion: m.toVersion, up: source };
1562
+ });
1563
+ await Promise.all(result.map((m) => precompileSource(m.up, this.migrationSandbox)));
1564
+ return result;
1565
+ }
1566
+ /**
1567
+ * Build a `GraphReader` over the meta-backend. If meta lives in the same
1568
+ * collection as the main backend, `this` is returned directly.
1569
+ */
1570
+ createMetaReader() {
1571
+ if (!this.metaBackend) return this;
1572
+ const backend = this.metaBackend;
1573
+ const executeMetaQuery = (filters, options) => backend.query(filters, options);
1574
+ return {
1575
+ async getNode(uid) {
1576
+ return backend.getDoc(computeNodeDocId(uid));
1577
+ },
1578
+ async getEdge(aUid, axbType, bUid) {
1579
+ return backend.getDoc(computeEdgeDocId(aUid, axbType, bUid));
1580
+ },
1581
+ async edgeExists(aUid, axbType, bUid) {
1582
+ const record = await backend.getDoc(computeEdgeDocId(aUid, axbType, bUid));
1583
+ return record !== null;
1584
+ },
1585
+ async findEdges(params) {
1586
+ const plan = buildEdgeQueryPlan(params);
1587
+ if (plan.strategy === "get") {
1588
+ const record = await backend.getDoc(plan.docId);
1589
+ return record ? [record] : [];
1590
+ }
1591
+ return executeMetaQuery(plan.filters, plan.options);
1592
+ },
1593
+ async findNodes(params) {
1594
+ const plan = buildNodeQueryPlan(params);
1595
+ if (plan.strategy === "get") {
1596
+ const record = await backend.getDoc(plan.docId);
1597
+ return record ? [record] : [];
1598
+ }
1599
+ return executeMetaQuery(plan.filters, plan.options);
1600
+ }
1601
+ };
1602
+ }
1603
+ };
1604
+ function createGraphClientFromBackend(backend, options, metaBackend) {
1605
+ return new GraphClientImpl(backend, options, metaBackend);
1606
+ }
1607
+
1608
+ export {
1609
+ NODE_RELATION,
1610
+ DEFAULT_QUERY_LIMIT,
1611
+ computeNodeDocId,
1612
+ computeEdgeDocId,
1613
+ FiregraphError,
1614
+ NodeNotFoundError,
1615
+ EdgeNotFoundError,
1616
+ ValidationError,
1617
+ RegistryViolationError,
1618
+ InvalidQueryError,
1619
+ TraversalError,
1620
+ DynamicRegistryError,
1621
+ QuerySafetyError,
1622
+ RegistryScopeError,
1623
+ MigrationError,
1624
+ compileSchema,
1625
+ jsonSchemaToFieldMeta,
1626
+ applyMigrationChain,
1627
+ validateMigrationChain,
1628
+ migrateRecord,
1629
+ migrateRecords,
1630
+ matchScope,
1631
+ matchScopeAny,
1632
+ createRegistry,
1633
+ createMergedRegistry,
1634
+ defaultExecutor,
1635
+ precompileSource,
1636
+ compileMigrationFn,
1637
+ compileMigrations,
1638
+ destroySandboxWorker,
1639
+ META_NODE_TYPE,
1640
+ META_EDGE_TYPE,
1641
+ NODE_TYPE_SCHEMA,
1642
+ EDGE_TYPE_SCHEMA,
1643
+ BOOTSTRAP_ENTRIES,
1644
+ createBootstrapRegistry,
1645
+ generateDeterministicUid,
1646
+ createRegistryFromGraph,
1647
+ buildEdgeQueryPlan,
1648
+ buildNodeQueryPlan,
1649
+ analyzeQuerySafety,
1650
+ GraphClientImpl,
1651
+ createGraphClientFromBackend
1652
+ };
1653
+ //# sourceMappingURL=chunk-YUXOALMR.js.map