@duraxis/core 0.2.2 → 0.3.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.
package/dist/index.cjs CHANGED
@@ -39,6 +39,10 @@ var StorageKeyManager = class {
39
39
  (0, _duraxis_storage.assertStorageKey)(key);
40
40
  if (key == "__duraxis" || key.startsWith("__duraxis/")) throw new Error("Reserved Duraxis logical key namespace");
41
41
  }
42
+ validatePrimaryKey(key) {
43
+ if (/^__duraxis\/metadata\/[a-z][a-z0-9-]{0,63}$/.test(key)) return;
44
+ this.validateLogicalKey(key);
45
+ }
42
46
  objectKey(data) {
43
47
  return `${this.objectPrefix}${(0, node_crypto.randomUUID)()}-${sha256(data)}`;
44
48
  }
@@ -444,24 +448,6 @@ async function readCommitRecord(storage, keys, key) {
444
448
  if (keys.commitKey(record.transactionId, object.data) != key) throw new Error("Commit record identity mismatch");
445
449
  return record;
446
450
  }
447
- // src/errors/transaction-conflict.error.ts
448
- var TransactionConflictError = class extends Error {
449
- message;
450
- constructor(message = "Transaction conflict: snapshot is stale") {
451
- super(message);
452
- this.message = message;
453
- this.name = "TransactionConflictError";
454
- }
455
- };
456
- // src/errors/commit-outcome-unknown.error.ts
457
- var CommitOutcomeUnknownError = class extends Error {
458
- transactionId;
459
- constructor(transactionId, cause) {
460
- super(`Commit outcome is unknown for transaction ${transactionId}` + (cause instanceof Error ? `: ${cause.message}` : ""), { cause });
461
- this.name = "CommitOutcomeUnknownError";
462
- this.transactionId = transactionId;
463
- }
464
- };
465
451
  // src/indexes/bptree/bptree-codec.ts
466
452
  var encoder$3 = new TextEncoder();
467
453
  var decoder$3 = new TextDecoder("utf-8", { fatal: true });
@@ -1060,7 +1046,7 @@ var PrimaryIndex = class {
1060
1046
  this.tree = new BPlusTree(nodes);
1061
1047
  }
1062
1048
  async getReference(manifest, logicalKey) {
1063
- this.keys.validateLogicalKey(logicalKey);
1049
+ this.keys.validatePrimaryKey(logicalKey);
1064
1050
  const value = await this.tree.get(manifest.primaryRoot, encoder$2.encode(logicalKey));
1065
1051
  if (value == null) return null;
1066
1052
  const ref = decoder$2.decode(value);
@@ -1070,7 +1056,7 @@ var PrimaryIndex = class {
1070
1056
  async prepare(root, changes) {
1071
1057
  const operations = [];
1072
1058
  for (const [logicalKey, physicalRef] of changes) {
1073
- this.keys.validateLogicalKey(logicalKey);
1059
+ this.keys.validatePrimaryKey(logicalKey);
1074
1060
  if (physicalRef == null) operations.push({
1075
1061
  type: "delete",
1076
1062
  key: encoder$2.encode(logicalKey)
@@ -1101,7 +1087,7 @@ var PrimaryIndex = class {
1101
1087
  for await (const entry of this.tree.scan(root, options)) {
1102
1088
  const key = decoder$2.decode(entry.key);
1103
1089
  const ref = decoder$2.decode(entry.value);
1104
- this.keys.validateLogicalKey(key);
1090
+ this.keys.validatePrimaryKey(key);
1105
1091
  this.keys.validateObjectKey(ref);
1106
1092
  yield {
1107
1093
  key,
@@ -1110,6 +1096,46 @@ var PrimaryIndex = class {
1110
1096
  }
1111
1097
  }
1112
1098
  };
1099
+ // src/indexes/bptree/bptree-node-cache.ts
1100
+ /** Query-scoped LRU for already integrity-checked immutable nodes. */
1101
+ var BPlusTreeNodeCache = class {
1102
+ source;
1103
+ capacity;
1104
+ entries = /* @__PURE__ */ new Map();
1105
+ hits = 0;
1106
+ misses = 0;
1107
+ constructor(source, capacity = 256) {
1108
+ this.source = source;
1109
+ this.capacity = capacity;
1110
+ if (!Number.isSafeInteger(capacity) || capacity < 1 || capacity > 65536) throw new Error("Invalid B+tree node cache capacity");
1111
+ }
1112
+ async read(ref) {
1113
+ const cached = this.entries.get(ref);
1114
+ if (cached) {
1115
+ this.hits++;
1116
+ this.entries.delete(ref);
1117
+ this.entries.set(ref, cached);
1118
+ return cached;
1119
+ }
1120
+ this.misses++;
1121
+ const node = await this.source.read(ref);
1122
+ this.entries.set(ref, node);
1123
+ if (this.entries.size > this.capacity) this.entries.delete(this.entries.keys().next().value);
1124
+ return node;
1125
+ }
1126
+ write(node) {
1127
+ return this.source.write(node);
1128
+ }
1129
+ clear() {
1130
+ this.entries.clear();
1131
+ }
1132
+ getMetrics() {
1133
+ return {
1134
+ hits: this.hits,
1135
+ misses: this.misses
1136
+ };
1137
+ }
1138
+ };
1113
1139
  // src/indexes/index-key.ts
1114
1140
  var MASK = 18446744073709551615n;
1115
1141
  var SIGN = 9223372036854775808n;
@@ -1348,7 +1374,7 @@ var SecondaryIndexManager = class {
1348
1374
  const id = indexId(collectionName, index.name);
1349
1375
  declared.add(id);
1350
1376
  const oldIndex = previousSchema?.indexes.find((item) => item.name == index.name);
1351
- if (!(oldIndex != null && JSON.stringify(indexFields(oldIndex)) == JSON.stringify(indexFields(index)) && oldIndex.unique == index.unique)) {
1377
+ if (!(oldIndex != null && JSON.stringify(indexFields(oldIndex)) == JSON.stringify(indexFields(index)) && oldIndex.unique == index.unique && indexFields(index).every((part) => JSON.stringify(fieldDefinition(previousSchema, part.field)) == JSON.stringify(fieldDefinition(schema, part.field))))) {
1352
1378
  roots.set(id, await this.rebuild(collectionName, schema, index, nextPrimaryRoot));
1353
1379
  continue;
1354
1380
  }
@@ -1420,7 +1446,12 @@ var SecondaryIndexManager = class {
1420
1446
  operations = [];
1421
1447
  }
1422
1448
  };
1423
- for await (const entry of this.primary.scanReferences(primaryRoot)) {
1449
+ const prefix = encoder.encode(`${RECORD_PREFIX}${collection}/`);
1450
+ const end = prefixSuccessor(prefix);
1451
+ for await (const entry of this.primary.scanReferences(primaryRoot, {
1452
+ gte: prefix,
1453
+ ...end == null ? {} : { lt: end }
1454
+ })) {
1424
1455
  const parsed = parseRecordKey(entry.key);
1425
1456
  if (parsed == null || parsed.collection != collection) continue;
1426
1457
  const values = valuesFor(schema, index, decodeDocument(await this.primary.readObject(entry.ref)));
@@ -1453,7 +1484,6 @@ var SecondaryIndexManager = class {
1453
1484
  root: manifest.indexRoots.get(id)
1454
1485
  };
1455
1486
  }
1456
- /** Ordered, incremental access that never materializes the ID set. */
1457
1487
  async *scanIds(manifest, collection, indexName, options = {}) {
1458
1488
  const { index, root } = this.resolve(manifest, collection, indexName);
1459
1489
  const limit = options.limit ?? Number.MAX_SAFE_INTEGER;
@@ -1481,329 +1511,77 @@ var SecondaryIndexManager = class {
1481
1511
  return ids;
1482
1512
  }
1483
1513
  };
1484
- // src/relations/foreign-key-manager.ts
1485
- var MAX_CASCADE_OPERATIONS = 1e5;
1486
- var ForeignKeyManager = class {
1487
- #primary;
1488
- #secondary;
1489
- constructor(storage, keys = new StorageKeyManager()) {
1490
- this.#primary = new PrimaryIndex(storage, keys);
1491
- this.#secondary = new SecondaryIndexManager(storage, keys);
1514
+ // src/query/context/query-context.ts
1515
+ function cloneWrites(source) {
1516
+ const result = /* @__PURE__ */ new Map();
1517
+ for (const [key, write] of source ?? []) result.set(key, write.type == "delete" ? { type: "delete" } : {
1518
+ type: "put",
1519
+ data: new Uint8Array(write.data)
1520
+ });
1521
+ return result;
1522
+ }
1523
+ var QueryContext = class {
1524
+ snapshot;
1525
+ options;
1526
+ primary;
1527
+ secondary;
1528
+ nodeCache;
1529
+ writes;
1530
+ controller = new AbortController();
1531
+ startedAt = performance.now();
1532
+ active = true;
1533
+ iterators = 0;
1534
+ metrics = {
1535
+ storageReads: 0,
1536
+ storageWrites: 0,
1537
+ nodesVisited: 0,
1538
+ entriesExamined: 0,
1539
+ recordsExamined: 0,
1540
+ recordsReturned: 0,
1541
+ cacheHits: 0,
1542
+ cacheMisses: 0,
1543
+ durationMs: 0
1544
+ };
1545
+ catalog;
1546
+ constructor(storage, snapshot, keys, options = {}) {
1547
+ this.snapshot = snapshot;
1548
+ this.options = options;
1549
+ this.nodeCache = new BPlusTreeNodeCache(new BPlusTreeNodeStore(storage, keys));
1550
+ this.primary = new PrimaryIndex(storage, keys, this.nodeCache);
1551
+ this.secondary = new SecondaryIndexManager(storage, keys, this.nodeCache);
1552
+ this.writes = cloneWrites(options.writes);
1553
+ this.catalog = new Map(options.catalog ?? snapshot.manifest.catalog);
1492
1554
  }
1493
- async prepare(snapshot, sourceWrites, sourceCatalog) {
1494
- const catalog = this.validateCatalog(sourceCatalog);
1495
- const writes = new Map(sourceWrites);
1496
- const incoming = this.incoming(catalog);
1497
- const queue = [];
1498
- const visited = /* @__PURE__ */ new Set();
1499
- for (const [key, operation] of writes) {
1500
- const parsed = parseRecordKey(key);
1501
- if (parsed && operation.type == "delete") queue.push(parsed);
1502
- }
1503
- for (let offset = 0; offset < queue.length; offset++) {
1504
- if (visited.size > MAX_CASCADE_OPERATIONS) throw new Error("Foreign-key cascade operation limit exceeded");
1505
- const parent = queue[offset];
1506
- const parentKey = recordKey(parent.collection, parent.id);
1507
- if (visited.has(parentKey)) continue;
1508
- visited.add(parentKey);
1509
- for (const relation of incoming.get(parent.collection) ?? []) {
1510
- const childIds = await this.childIds(snapshot, writes, relation, parent.id);
1511
- for (const childId of childIds) {
1512
- const childKey = recordKey(relation.collection, childId);
1513
- const document = await this.finalDocument(snapshot, writes, relation.collection, childId);
1514
- if (!document || document[relation.foreignKey.field] !== parent.id) continue;
1515
- switch (relation.foreignKey.onDelete) {
1516
- case "RESTRICT": throw new ReferencedRecordRestrictedError(relation.collection, relation.foreignKey.name, `${parent.collection}/${parent.id}`);
1517
- case "CASCADE":
1518
- writes.set(childKey, { type: "delete" });
1519
- queue.push({
1520
- collection: relation.collection,
1521
- id: childId
1522
- });
1523
- break;
1524
- case "SET_NULL": {
1525
- const next = {
1526
- ...document,
1527
- [relation.foreignKey.field]: null
1528
- };
1529
- writes.set(childKey, {
1530
- type: "put",
1531
- data: encodeDocument(validateDocument(relation.schema, next))
1532
- });
1533
- break;
1534
- }
1535
- }
1536
- }
1537
- }
1538
- }
1539
- for (const [key, operation] of writes) {
1540
- const parsed = parseRecordKey(key);
1541
- if (!parsed || operation.type != "put") continue;
1542
- const schema = catalog.get(parsed.collection);
1543
- if (!schema) throw new InvalidForeignKeyDefinitionError(`Unknown collection: ${parsed.collection}`);
1544
- const document = decodeDocument(operation.data);
1545
- for (const foreignKey of schema.foreignKeys ?? []) {
1546
- const definition = fieldDefinition(schema, foreignKey.field);
1547
- const value = document[foreignKey.field];
1548
- if (value == null) {
1549
- if (value === null && definition.nullable) continue;
1550
- if (value === void 0 && !definition.required) continue;
1551
- throw new ReferencedRecordNotFoundError(parsed.collection, foreignKey.name, String(value));
1552
- }
1553
- if (typeof value != "string" || !await this.finalRecordExists(snapshot, writes, foreignKey.references.collection, value)) throw new ReferencedRecordNotFoundError(parsed.collection, foreignKey.name, `${foreignKey.references.collection}/${String(value)}`);
1554
- }
1555
- }
1556
- return writes;
1555
+ get generation() {
1556
+ return this.snapshot.manifest.transactionId || "initial";
1557
1557
  }
1558
- validateCatalog(source) {
1559
- const catalog = /* @__PURE__ */ new Map();
1560
- try {
1561
- for (const [name, definition] of source) catalog.set(name, normalizeCollection(definition));
1562
- } catch (cause) {
1563
- throw new InvalidForeignKeyDefinitionError(cause instanceof Error ? cause.message : "Invalid foreign key definition");
1564
- }
1565
- for (const [collection, schema] of catalog) for (const foreignKey of schema.foreignKeys ?? []) if (!catalog.has(foreignKey.references.collection)) throw new InvalidForeignKeyDefinitionError(`Foreign key ${collection}/${foreignKey.name} references unknown collection ${foreignKey.references.collection}`);
1566
- return catalog;
1558
+ get signal() {
1559
+ return this.controller.signal;
1567
1560
  }
1568
- incoming(catalog) {
1569
- const result = /* @__PURE__ */ new Map();
1570
- for (const [collection, schema] of catalog) for (const foreignKey of schema.foreignKeys ?? []) {
1571
- const index = schema.indexes.find((candidate) => {
1572
- const parts = indexFields(candidate);
1573
- return parts.length == 1 && parts[0].field == foreignKey.field;
1574
- });
1575
- if (!index) throw new InvalidForeignKeyDefinitionError(`Foreign key ${collection}/${foreignKey.name} has no supporting index`);
1576
- const values = result.get(foreignKey.references.collection) ?? [];
1577
- values.push({
1578
- collection,
1579
- schema,
1580
- foreignKey,
1581
- index: index.name
1582
- });
1583
- result.set(foreignKey.references.collection, values);
1584
- }
1585
- for (const values of result.values()) values.sort((left, right) => `${left.collection}/${left.foreignKey.name}`.localeCompare(`${right.collection}/${right.foreignKey.name}`));
1586
- return result;
1561
+ get isActive() {
1562
+ return this.active;
1587
1563
  }
1588
- async childIds(snapshot, writes, relation, parentId) {
1589
- const result = /* @__PURE__ */ new Set();
1590
- if (snapshot.manifest.catalog.get(relation.collection)?.indexes.some((index) => index.name == relation.index)) for await (const entry of this.#secondary.scanIds(snapshot.manifest, relation.collection, relation.index, { eq: parentId })) result.add(entry.id);
1591
- for (const [key, operation] of writes) {
1592
- const parsed = parseRecordKey(key);
1593
- if (!parsed || parsed.collection != relation.collection) continue;
1594
- if (operation.type == "delete") result.delete(parsed.id);
1595
- else if (decodeDocument(operation.data)[relation.foreignKey.field] === parentId) result.add(parsed.id);
1596
- else result.delete(parsed.id);
1597
- }
1598
- return result;
1564
+ close(reason = /* @__PURE__ */ new Error("Query context is closed")) {
1565
+ if (!this.active) return;
1566
+ this.active = false;
1567
+ const cache = this.nodeCache.getMetrics();
1568
+ this.metrics.cacheHits = cache.hits;
1569
+ this.metrics.cacheMisses = cache.misses;
1570
+ this.metrics.durationMs = performance.now() - this.startedAt;
1571
+ this.controller.abort(reason);
1572
+ this.nodeCache.clear();
1573
+ this.options.onClose?.();
1599
1574
  }
1600
- async finalRecordExists(snapshot, writes, collection, id) {
1601
- return await this.finalDocument(snapshot, writes, collection, id) != null;
1575
+ cancel(reason = /* @__PURE__ */ new Error("Query cancelled")) {
1576
+ this.close(reason);
1602
1577
  }
1603
- async finalDocument(snapshot, writes, collection, id) {
1604
- const key = recordKey(collection, id);
1605
- const pending = writes.get(key);
1606
- if (pending) return pending.type == "delete" ? null : decodeDocument(pending.data);
1607
- const stored = await this.#primary.read(snapshot.manifest, key);
1608
- return stored == null ? null : decodeDocument(stored);
1578
+ assertActive() {
1579
+ if (!this.active) throw this.controller.signal.reason ?? /* @__PURE__ */ new Error("Query context is closed");
1609
1580
  }
1610
- };
1611
- // src/commit/commit-coordinator.ts
1612
- var CommitCoordinator = class {
1613
- storage;
1614
- keys;
1615
- primary;
1616
- secondary;
1617
- foreignKeys;
1618
- constructor(storage, keys = new StorageKeyManager()) {
1619
- this.storage = storage;
1620
- this.keys = keys;
1621
- this.primary = new PrimaryIndex(storage, keys);
1622
- this.secondary = new SecondaryIndexManager(storage, keys);
1623
- this.foreignKeys = new ForeignKeyManager(storage, keys);
1624
- }
1625
- async commit(transaction) {
1626
- const prepared = transaction.prepareForCommit();
1627
- if (prepared.writes.size == 0 && prepared.schemaChanges.size == 0) {
1628
- transaction.markCommitted();
1629
- return;
1630
- }
1631
- const transactionId = (0, node_crypto.randomUUID)();
1632
- const catalog = new Map(prepared.snapshot.manifest.catalog);
1633
- for (const [name, schema] of prepared.schemaChanges) catalog.set(name, schema);
1634
- const writes = await this.foreignKeys.prepare(prepared.snapshot, prepared.writes, catalog);
1635
- const changes = /* @__PURE__ */ new Map();
1636
- for (const [key, operation] of writes) {
1637
- if (operation.type == "delete") {
1638
- changes.set(key, null);
1639
- continue;
1640
- }
1641
- const ref = this.keys.objectKey(operation.data);
1642
- if (!(await this.storage.put(ref, operation.data, { condition: { type: "if-absent" } })).success) throw new Error("Unexpected immutable object key collision");
1643
- changes.set(key, ref);
1644
- }
1645
- const primaryRoot = await this.primary.prepare(prepared.snapshot.manifest.primaryRoot, changes);
1646
- const indexRoots = await this.secondary.prepare(prepared.snapshot.manifest, primaryRoot, writes, catalog);
1647
- const commitBytes = encodeCommitRecord({
1648
- format: 1,
1649
- transactionId,
1650
- previous: prepared.snapshot.manifest.commitHead
1651
- });
1652
- const commitKey = this.keys.commitKey(transactionId, commitBytes);
1653
- if (!(await this.storage.put(commitKey, commitBytes, { condition: { type: "if-absent" } })).success) throw new Error("Unexpected commit record collision");
1654
- const manifestBytes = encodeManifest({
1655
- format: 1,
1656
- transactionId,
1657
- commitHead: commitKey,
1658
- primaryRoot,
1659
- indexRoots,
1660
- catalog
1661
- }, this.keys);
1662
- transaction.beginPublication();
1663
- let result;
1664
- try {
1665
- result = await this.storage.put(this.keys.manifestKey, manifestBytes, { condition: prepared.snapshot.storageVersion == null ? { type: "if-absent" } : {
1666
- type: "if-version",
1667
- version: prepared.snapshot.storageVersion
1668
- } });
1669
- } catch (cause) {
1670
- transaction.markUnknown();
1671
- throw new CommitOutcomeUnknownError(transactionId, cause);
1672
- }
1673
- if (!result.success) throw new TransactionConflictError();
1674
- transaction.markCommitted();
1675
- }
1676
- };
1677
- // src/snapshots/snapshot-reader.ts
1678
- var ManifestSnapshotReader = class {
1679
- snapshot;
1680
- primary;
1681
- constructor(storage, snapshot, keys) {
1682
- this.snapshot = snapshot;
1683
- this.primary = new PrimaryIndex(storage, keys);
1684
- }
1685
- async get(key) {
1686
- return this.primary.read(this.snapshot.manifest, key);
1687
- }
1688
- };
1689
- // src/errors/transaction-state.error.ts
1690
- var TransactionStateError = class extends Error {
1691
- constructor(message) {
1692
- super(message);
1693
- this.name = "TransactionStateError";
1694
- }
1695
- };
1696
- // src/indexes/bptree/bptree-node-cache.ts
1697
- /** Query-scoped LRU for already integrity-checked immutable nodes. */
1698
- var BPlusTreeNodeCache = class {
1699
- source;
1700
- capacity;
1701
- entries = /* @__PURE__ */ new Map();
1702
- hits = 0;
1703
- misses = 0;
1704
- constructor(source, capacity = 256) {
1705
- this.source = source;
1706
- this.capacity = capacity;
1707
- if (!Number.isSafeInteger(capacity) || capacity < 1 || capacity > 65536) throw new Error("Invalid B+tree node cache capacity");
1708
- }
1709
- async read(ref) {
1710
- const cached = this.entries.get(ref);
1711
- if (cached) {
1712
- this.hits++;
1713
- this.entries.delete(ref);
1714
- this.entries.set(ref, cached);
1715
- return cached;
1716
- }
1717
- this.misses++;
1718
- const node = await this.source.read(ref);
1719
- this.entries.set(ref, node);
1720
- if (this.entries.size > this.capacity) this.entries.delete(this.entries.keys().next().value);
1721
- return node;
1722
- }
1723
- write(node) {
1724
- return this.source.write(node);
1725
- }
1726
- clear() {
1727
- this.entries.clear();
1728
- }
1729
- getMetrics() {
1730
- return {
1731
- hits: this.hits,
1732
- misses: this.misses
1733
- };
1734
- }
1735
- };
1736
- // src/query/context/query-context.ts
1737
- function cloneWrites(source) {
1738
- const result = /* @__PURE__ */ new Map();
1739
- for (const [key, write] of source ?? []) result.set(key, write.type == "delete" ? { type: "delete" } : {
1740
- type: "put",
1741
- data: new Uint8Array(write.data)
1742
- });
1743
- return result;
1744
- }
1745
- var QueryContext = class {
1746
- snapshot;
1747
- options;
1748
- primary;
1749
- secondary;
1750
- nodeCache;
1751
- writes;
1752
- controller = new AbortController();
1753
- startedAt = performance.now();
1754
- active = true;
1755
- iterators = 0;
1756
- metrics = {
1757
- storageReads: 0,
1758
- storageWrites: 0,
1759
- nodesVisited: 0,
1760
- entriesExamined: 0,
1761
- recordsExamined: 0,
1762
- recordsReturned: 0,
1763
- cacheHits: 0,
1764
- cacheMisses: 0,
1765
- durationMs: 0
1766
- };
1767
- catalog;
1768
- constructor(storage, snapshot, keys, options = {}) {
1769
- this.snapshot = snapshot;
1770
- this.options = options;
1771
- this.nodeCache = new BPlusTreeNodeCache(new BPlusTreeNodeStore(storage, keys));
1772
- this.primary = new PrimaryIndex(storage, keys, this.nodeCache);
1773
- this.secondary = new SecondaryIndexManager(storage, keys, this.nodeCache);
1774
- this.writes = cloneWrites(options.writes);
1775
- this.catalog = new Map(options.catalog ?? snapshot.manifest.catalog);
1776
- }
1777
- get generation() {
1778
- return this.snapshot.manifest.transactionId || "initial";
1779
- }
1780
- get signal() {
1781
- return this.controller.signal;
1782
- }
1783
- get isActive() {
1784
- return this.active;
1785
- }
1786
- close(reason = /* @__PURE__ */ new Error("Query context is closed")) {
1787
- if (!this.active) return;
1788
- this.active = false;
1789
- const cache = this.nodeCache.getMetrics();
1790
- this.metrics.cacheHits = cache.hits;
1791
- this.metrics.cacheMisses = cache.misses;
1792
- this.metrics.durationMs = performance.now() - this.startedAt;
1793
- this.controller.abort(reason);
1794
- this.nodeCache.clear();
1795
- this.options.onClose?.();
1796
- }
1797
- cancel(reason = /* @__PURE__ */ new Error("Query cancelled")) {
1798
- this.close(reason);
1799
- }
1800
- assertActive() {
1801
- if (!this.active) throw this.controller.signal.reason ?? /* @__PURE__ */ new Error("Query context is closed");
1802
- }
1803
- begin() {
1804
- this.assertActive();
1805
- this.iterators++;
1806
- this.options.onIteratorStart?.();
1581
+ begin() {
1582
+ this.assertActive();
1583
+ this.iterators++;
1584
+ this.options.onIteratorStart?.();
1807
1585
  }
1808
1586
  end() {
1809
1587
  if (this.iterators > 0) this.iterators--;
@@ -1869,6 +1647,7 @@ var QueryContext = class {
1869
1647
  if (parsed && !pending.has(parsed.id)) break;
1870
1648
  next = await committed.next();
1871
1649
  }
1650
+ if (next.done && pendingIndex >= pendingRows.length) break;
1872
1651
  const staged = pendingRows[pendingIndex];
1873
1652
  const committedKey = next.done ? void 0 : new TextEncoder().encode(next.value.key);
1874
1653
  const usePending = staged != null && (committedKey == null || compareBytes(staged.key, committedKey) * (direction == "ASC" ? 1 : -1) <= 0);
@@ -1938,8 +1717,30 @@ var QueryContext = class {
1938
1717
  async *scanIndex(collection, indexName, options = {}) {
1939
1718
  this.begin();
1940
1719
  try {
1941
- this.schema(collection);
1942
- if (!this.snapshot.manifest.catalog.get(collection)?.indexes.some((index) => index.name == indexName)) throw new Error(`Index is not available in captured snapshot: ${collection}/${indexName}`);
1720
+ const schema = this.schema(collection);
1721
+ if (!schema.indexes.some((index) => index.name == indexName)) throw new Error(`Index is not available in captured snapshot: ${collection}/${indexName}`);
1722
+ const previous = this.snapshot.manifest.catalog.get(collection);
1723
+ if (JSON.stringify(previous) != JSON.stringify(schema)) {
1724
+ const index = schema.indexes.find((item) => item.name == indexName);
1725
+ if (!index) throw new Error(`Unknown index: ${collection}/${indexName}`);
1726
+ const parts = indexFields(index);
1727
+ const bounds = secondaryIndexBounds(index, options);
1728
+ const entries = [];
1729
+ for await (const row of this.scanCollection(collection, { signal: options.signal })) {
1730
+ const values = parts.map((part) => indexedValue(row.document, part.field, fieldDefinition(schema, part.field)));
1731
+ if (values.some((value) => value === void 0)) continue;
1732
+ const key = encodeSecondaryKey(values, index.unique ? void 0 : row.id, parts.map((part) => part.order));
1733
+ if ((bounds.gt == null || compareBytes(key, bounds.gt) > 0) && (bounds.gte == null || compareBytes(key, bounds.gte) >= 0) && (bounds.lt == null || compareBytes(key, bounds.lt) < 0) && (bounds.lte == null || compareBytes(key, bounds.lte) <= 0)) entries.push({
1734
+ key,
1735
+ row
1736
+ });
1737
+ }
1738
+ const limit = options.limit ?? Number.MAX_SAFE_INTEGER;
1739
+ if (!Number.isSafeInteger(limit) || limit < 0) throw new Error("Invalid query limit");
1740
+ entries.sort((a, b) => compareBytes(a.key, b.key) * (options.direction == "DESC" ? -1 : 1));
1741
+ for (const entry of entries.slice(0, limit)) yield entry.row;
1742
+ return;
1743
+ }
1943
1744
  const limit = options.limit ?? Number.MAX_SAFE_INTEGER;
1944
1745
  if (!Number.isSafeInteger(limit) || limit < 0) throw new Error("Invalid query limit");
1945
1746
  if (limit == 0) return;
@@ -1960,6 +1761,7 @@ var QueryContext = class {
1960
1761
  if (options.signal?.aborted) throw options.signal.reason ?? /* @__PURE__ */ new Error("Query cancelled");
1961
1762
  this.assertActive();
1962
1763
  while (!next.done && pending.has(next.value.id)) next = await committed.next();
1764
+ if (next.done && stagedIndex >= staged.length) break;
1963
1765
  const pendingEntry = staged[stagedIndex];
1964
1766
  const usePending = pendingEntry != null && (next.done || compareBytes(pendingEntry.key, next.value.key) * (direction == "ASC" ? 1 : -1) <= 0);
1965
1767
  let row;
@@ -1988,6 +1790,272 @@ var QueryContext = class {
1988
1790
  }
1989
1791
  }
1990
1792
  };
1793
+ // src/errors/transaction-conflict.error.ts
1794
+ var TransactionConflictError = class extends Error {
1795
+ message;
1796
+ constructor(message = "Transaction conflict: snapshot is stale") {
1797
+ super(message);
1798
+ this.message = message;
1799
+ this.name = "TransactionConflictError";
1800
+ }
1801
+ };
1802
+ // src/errors/commit-outcome-unknown.error.ts
1803
+ var CommitOutcomeUnknownError = class extends Error {
1804
+ transactionId;
1805
+ constructor(transactionId, cause) {
1806
+ super(`Commit outcome is unknown for transaction ${transactionId}` + (cause instanceof Error ? `: ${cause.message}` : ""), { cause });
1807
+ this.name = "CommitOutcomeUnknownError";
1808
+ this.transactionId = transactionId;
1809
+ }
1810
+ };
1811
+ // src/relations/foreign-key-manager.ts
1812
+ var MAX_CASCADE_OPERATIONS = 1e5;
1813
+ var ForeignKeyManager = class {
1814
+ #primary;
1815
+ #secondary;
1816
+ constructor(storage, keys = new StorageKeyManager()) {
1817
+ this.#primary = new PrimaryIndex(storage, keys);
1818
+ this.#secondary = new SecondaryIndexManager(storage, keys);
1819
+ }
1820
+ async prepare(snapshot, sourceWrites, sourceCatalog) {
1821
+ const catalog = this.validateCatalog(sourceCatalog);
1822
+ const writes = new Map(sourceWrites);
1823
+ const incoming = this.incoming(catalog);
1824
+ const queue = [];
1825
+ const visited = /* @__PURE__ */ new Set();
1826
+ for (const [key, operation] of writes) {
1827
+ const parsed = parseRecordKey(key);
1828
+ if (parsed && operation.type == "delete") queue.push(parsed);
1829
+ }
1830
+ for (let offset = 0; offset < queue.length; offset++) {
1831
+ if (visited.size > MAX_CASCADE_OPERATIONS) throw new Error("Foreign-key cascade operation limit exceeded");
1832
+ const parent = queue[offset];
1833
+ const parentKey = recordKey(parent.collection, parent.id);
1834
+ if (visited.has(parentKey)) continue;
1835
+ visited.add(parentKey);
1836
+ for (const relation of incoming.get(parent.collection) ?? []) {
1837
+ const childIds = await this.childIds(snapshot, writes, relation, parent.id);
1838
+ for (const childId of childIds) {
1839
+ const childKey = recordKey(relation.collection, childId);
1840
+ const document = await this.finalDocument(snapshot, writes, relation.collection, childId);
1841
+ if (!document || document[relation.foreignKey.field] !== parent.id) continue;
1842
+ switch (relation.foreignKey.onDelete) {
1843
+ case "RESTRICT": throw new ReferencedRecordRestrictedError(relation.collection, relation.foreignKey.name, `${parent.collection}/${parent.id}`);
1844
+ case "CASCADE":
1845
+ writes.set(childKey, { type: "delete" });
1846
+ queue.push({
1847
+ collection: relation.collection,
1848
+ id: childId
1849
+ });
1850
+ break;
1851
+ case "SET_NULL": {
1852
+ const next = {
1853
+ ...document,
1854
+ [relation.foreignKey.field]: null
1855
+ };
1856
+ writes.set(childKey, {
1857
+ type: "put",
1858
+ data: encodeDocument(validateDocument(relation.schema, next))
1859
+ });
1860
+ break;
1861
+ }
1862
+ }
1863
+ }
1864
+ }
1865
+ }
1866
+ for (const [key, operation] of writes) {
1867
+ const parsed = parseRecordKey(key);
1868
+ if (!parsed || operation.type != "put") continue;
1869
+ const schema = catalog.get(parsed.collection);
1870
+ if (!schema) throw new InvalidForeignKeyDefinitionError(`Unknown collection: ${parsed.collection}`);
1871
+ const document = decodeDocument(operation.data);
1872
+ for (const foreignKey of schema.foreignKeys ?? []) {
1873
+ const definition = fieldDefinition(schema, foreignKey.field);
1874
+ const value = document[foreignKey.field];
1875
+ if (value == null) {
1876
+ if (value === null && definition.nullable) continue;
1877
+ if (value === void 0 && !definition.required) continue;
1878
+ throw new ReferencedRecordNotFoundError(parsed.collection, foreignKey.name, String(value));
1879
+ }
1880
+ if (typeof value != "string" || !await this.finalRecordExists(snapshot, writes, foreignKey.references.collection, value)) throw new ReferencedRecordNotFoundError(parsed.collection, foreignKey.name, `${foreignKey.references.collection}/${String(value)}`);
1881
+ }
1882
+ }
1883
+ return writes;
1884
+ }
1885
+ validateCatalog(source) {
1886
+ const catalog = /* @__PURE__ */ new Map();
1887
+ try {
1888
+ for (const [name, definition] of source) catalog.set(name, normalizeCollection(definition));
1889
+ } catch (cause) {
1890
+ throw new InvalidForeignKeyDefinitionError(cause instanceof Error ? cause.message : "Invalid foreign key definition");
1891
+ }
1892
+ for (const [collection, schema] of catalog) for (const foreignKey of schema.foreignKeys ?? []) if (!catalog.has(foreignKey.references.collection)) throw new InvalidForeignKeyDefinitionError(`Foreign key ${collection}/${foreignKey.name} references unknown collection ${foreignKey.references.collection}`);
1893
+ return catalog;
1894
+ }
1895
+ incoming(catalog) {
1896
+ const result = /* @__PURE__ */ new Map();
1897
+ for (const [collection, schema] of catalog) for (const foreignKey of schema.foreignKeys ?? []) {
1898
+ const index = schema.indexes.find((candidate) => {
1899
+ const parts = indexFields(candidate);
1900
+ return parts.length == 1 && parts[0].field == foreignKey.field;
1901
+ });
1902
+ if (!index) throw new InvalidForeignKeyDefinitionError(`Foreign key ${collection}/${foreignKey.name} has no supporting index`);
1903
+ const values = result.get(foreignKey.references.collection) ?? [];
1904
+ values.push({
1905
+ collection,
1906
+ schema,
1907
+ foreignKey,
1908
+ index: index.name
1909
+ });
1910
+ result.set(foreignKey.references.collection, values);
1911
+ }
1912
+ for (const values of result.values()) values.sort((left, right) => `${left.collection}/${left.foreignKey.name}`.localeCompare(`${right.collection}/${right.foreignKey.name}`));
1913
+ return result;
1914
+ }
1915
+ async childIds(snapshot, writes, relation, parentId) {
1916
+ const result = /* @__PURE__ */ new Set();
1917
+ const previousIndex = snapshot.manifest.catalog.get(relation.collection)?.indexes.find((index) => index.name == relation.index);
1918
+ const compatible = previousIndex && indexFields(previousIndex).length == 1 && indexFields(previousIndex)[0].field == relation.foreignKey.field;
1919
+ if (compatible) for await (const entry of this.#secondary.scanIds(snapshot.manifest, relation.collection, relation.index, { eq: parentId })) result.add(entry.id);
1920
+ if (!compatible) {
1921
+ const prefix = new TextEncoder().encode(`${RECORD_PREFIX}${relation.collection}/`);
1922
+ const end = prefixSuccessor(prefix);
1923
+ for await (const entry of this.#primary.scanReferences(snapshot.manifest.primaryRoot, {
1924
+ gte: prefix,
1925
+ ...end ? { lt: end } : {}
1926
+ })) {
1927
+ const parsed = parseRecordKey(entry.key);
1928
+ if (decodeDocument(await this.#primary.readObject(entry.ref))[relation.foreignKey.field] === parentId) result.add(parsed.id);
1929
+ }
1930
+ }
1931
+ for (const [key, operation] of writes) {
1932
+ const parsed = parseRecordKey(key);
1933
+ if (!parsed || parsed.collection != relation.collection) continue;
1934
+ if (operation.type == "delete") result.delete(parsed.id);
1935
+ else if (decodeDocument(operation.data)[relation.foreignKey.field] === parentId) result.add(parsed.id);
1936
+ else result.delete(parsed.id);
1937
+ }
1938
+ return result;
1939
+ }
1940
+ async finalRecordExists(snapshot, writes, collection, id) {
1941
+ return await this.finalDocument(snapshot, writes, collection, id) != null;
1942
+ }
1943
+ async finalDocument(snapshot, writes, collection, id) {
1944
+ const key = recordKey(collection, id);
1945
+ const pending = writes.get(key);
1946
+ if (pending) return pending.type == "delete" ? null : decodeDocument(pending.data);
1947
+ const stored = await this.#primary.read(snapshot.manifest, key);
1948
+ return stored == null ? null : decodeDocument(stored);
1949
+ }
1950
+ };
1951
+ // src/commit/commit-coordinator.ts
1952
+ var CommitCoordinator = class {
1953
+ storage;
1954
+ keys;
1955
+ primary;
1956
+ secondary;
1957
+ foreignKeys;
1958
+ constructor(storage, keys = new StorageKeyManager()) {
1959
+ this.storage = storage;
1960
+ this.keys = keys;
1961
+ this.primary = new PrimaryIndex(storage, keys);
1962
+ this.secondary = new SecondaryIndexManager(storage, keys);
1963
+ this.foreignKeys = new ForeignKeyManager(storage, keys);
1964
+ }
1965
+ async commit(transaction) {
1966
+ const prepared = transaction.prepareForCommit();
1967
+ if (prepared.writes.size == 0 && prepared.schemaChanges.size == 0) {
1968
+ transaction.markCommitted();
1969
+ return;
1970
+ }
1971
+ const transactionId = (0, node_crypto.randomUUID)();
1972
+ const catalog = new Map(prepared.snapshot.manifest.catalog);
1973
+ const staged = new Map(prepared.writes);
1974
+ for (const [name, schema] of prepared.schemaChanges) {
1975
+ if (schema == null) catalog.delete(name);
1976
+ else catalog.set(name, schema);
1977
+ const previous = prepared.snapshot.manifest.catalog.get(name);
1978
+ if (!(schema == null || !previous || JSON.stringify(previous.fields) != JSON.stringify(schema.fields) || previous.allowAdditionalFields != schema.allowAdditionalFields || JSON.stringify(previous.foreignKeys) != JSON.stringify(schema.foreignKeys))) continue;
1979
+ const scanCatalog = new Map(catalog);
1980
+ if (schema == null) scanCatalog.set(name, prepared.snapshot.manifest.catalog.get(name) ?? {
1981
+ name,
1982
+ indexes: []
1983
+ });
1984
+ const context = new QueryContext(this.storage, prepared.snapshot, this.keys, {
1985
+ writes: staged,
1986
+ catalog: scanCatalog
1987
+ });
1988
+ try {
1989
+ for await (const row of context.scanCollection(name)) staged.set(recordKey(name, row.id), schema == null ? { type: "delete" } : {
1990
+ type: "put",
1991
+ data: encodeDocument(validateDocument(schema, row.document))
1992
+ });
1993
+ } finally {
1994
+ context.close();
1995
+ }
1996
+ }
1997
+ const writes = await this.foreignKeys.prepare(prepared.snapshot, staged, catalog);
1998
+ const changes = /* @__PURE__ */ new Map();
1999
+ for (const [key, operation] of writes) {
2000
+ if (operation.type == "delete") {
2001
+ changes.set(key, null);
2002
+ continue;
2003
+ }
2004
+ const ref = this.keys.objectKey(operation.data);
2005
+ if (!(await this.storage.put(ref, operation.data, { condition: { type: "if-absent" } })).success) throw new Error("Unexpected immutable object key collision");
2006
+ changes.set(key, ref);
2007
+ }
2008
+ const primaryRoot = await this.primary.prepare(prepared.snapshot.manifest.primaryRoot, changes);
2009
+ const indexRoots = await this.secondary.prepare(prepared.snapshot.manifest, primaryRoot, writes, catalog);
2010
+ const commitBytes = encodeCommitRecord({
2011
+ format: 1,
2012
+ transactionId,
2013
+ previous: prepared.snapshot.manifest.commitHead
2014
+ });
2015
+ const commitKey = this.keys.commitKey(transactionId, commitBytes);
2016
+ if (!(await this.storage.put(commitKey, commitBytes, { condition: { type: "if-absent" } })).success) throw new Error("Unexpected commit record collision");
2017
+ const manifestBytes = encodeManifest({
2018
+ format: 1,
2019
+ transactionId,
2020
+ commitHead: commitKey,
2021
+ primaryRoot,
2022
+ indexRoots,
2023
+ catalog
2024
+ }, this.keys);
2025
+ transaction.beginPublication();
2026
+ let result;
2027
+ try {
2028
+ result = await this.storage.put(this.keys.manifestKey, manifestBytes, { condition: prepared.snapshot.storageVersion == null ? { type: "if-absent" } : {
2029
+ type: "if-version",
2030
+ version: prepared.snapshot.storageVersion
2031
+ } });
2032
+ } catch (cause) {
2033
+ transaction.markUnknown();
2034
+ throw new CommitOutcomeUnknownError(transactionId, cause);
2035
+ }
2036
+ if (!result.success) throw new TransactionConflictError();
2037
+ transaction.markCommitted();
2038
+ }
2039
+ };
2040
+ // src/snapshots/snapshot-reader.ts
2041
+ var ManifestSnapshotReader = class {
2042
+ snapshot;
2043
+ primary;
2044
+ constructor(storage, snapshot, keys) {
2045
+ this.snapshot = snapshot;
2046
+ this.primary = new PrimaryIndex(storage, keys);
2047
+ }
2048
+ async get(key) {
2049
+ return this.primary.read(this.snapshot.manifest, key);
2050
+ }
2051
+ };
2052
+ // src/errors/transaction-state.error.ts
2053
+ var TransactionStateError = class extends Error {
2054
+ constructor(message) {
2055
+ super(message);
2056
+ this.name = "TransactionStateError";
2057
+ }
2058
+ };
1991
2059
  // src/query/model/cursor.ts
1992
2060
  function canonical(value) {
1993
2061
  if (value instanceof Date) return JSON.stringify(value.toISOString());
@@ -3073,6 +3141,7 @@ var Transaction = class {
3073
3141
  defineCollection(definition) {
3074
3142
  this.assertActive();
3075
3143
  validateCollection(definition);
3144
+ if (this.schemas.get(definition.name) === null) throw new Error("Cannot recreate a dropped collection in the same transaction");
3076
3145
  if (this.collection(definition.name)) throw new Error(`Collection already exists: ${definition.name}`);
3077
3146
  this.schemas.set(definition.name, cloneSchema(definition));
3078
3147
  }
@@ -3081,11 +3150,58 @@ var Transaction = class {
3081
3150
  const names = /* @__PURE__ */ new Set();
3082
3151
  for (const definition of definitions) {
3083
3152
  validateCollection(definition);
3084
- if (names.has(definition.name) || this.collection(definition.name)) throw new Error(`Collection already exists: ${definition.name}`);
3153
+ if (names.has(definition.name) || this.schemas.has(definition.name) || this.collection(definition.name)) throw new Error(`Collection already exists: ${definition.name}`);
3085
3154
  names.add(definition.name);
3086
3155
  }
3087
3156
  for (const definition of definitions) this.schemas.set(definition.name, cloneSchema(definition));
3088
3157
  }
3158
+ getCollectionDefinitions() {
3159
+ this.assertActive();
3160
+ const catalog = new Map(this.capturedSnapshot.manifest.catalog);
3161
+ for (const [name, schema] of this.schemas) if (schema == null) catalog.delete(name);
3162
+ else catalog.set(name, schema);
3163
+ return [...catalog.values()].map(cloneSchema);
3164
+ }
3165
+ alterCollection(name, definition) {
3166
+ this.assertActive();
3167
+ this.requireCollection(name);
3168
+ if (name != definition.name) throw new Error("Collection replacement cannot rename a collection");
3169
+ this.schemas.set(name, cloneSchema(definition));
3170
+ }
3171
+ dropCollection(name) {
3172
+ this.assertActive();
3173
+ this.requireCollection(name);
3174
+ this.schemas.set(name, null);
3175
+ }
3176
+ async getMetadata(namespace) {
3177
+ this.assertActive();
3178
+ const key = this.metadataKey(namespace);
3179
+ this.pendingReads++;
3180
+ try {
3181
+ const pending = this.writes.get(key);
3182
+ const value = pending ? pending.type == "delete" ? null : pending.data : await this.reader.get(key);
3183
+ this.assertActive();
3184
+ return value == null ? null : new Uint8Array(value);
3185
+ } finally {
3186
+ this.releaseRead();
3187
+ }
3188
+ }
3189
+ putMetadata(namespace, data) {
3190
+ this.assertActive();
3191
+ this.stagePut(this.metadataKey(namespace), data);
3192
+ }
3193
+ metadataKey(namespace) {
3194
+ if (!/^[a-z][a-z0-9-]{0,63}$/.test(namespace)) throw new Error("Invalid metadata namespace");
3195
+ return `__duraxis/metadata/${namespace}`;
3196
+ }
3197
+ async *scanCollection(collection) {
3198
+ const context = this.createQueryContext();
3199
+ try {
3200
+ yield* context.scanCollection(collection);
3201
+ } finally {
3202
+ context.close();
3203
+ }
3204
+ }
3089
3205
  addIndex(collection, index) {
3090
3206
  this.assertActive();
3091
3207
  const current = this.requireCollection(collection);
@@ -3114,7 +3230,8 @@ var Transaction = class {
3114
3230
  createQueryContext() {
3115
3231
  this.assertActive();
3116
3232
  const catalog = new Map(this.capturedSnapshot.manifest.catalog);
3117
- for (const [name, schema] of this.schemas) catalog.set(name, cloneSchema(schema));
3233
+ for (const [name, schema] of this.schemas) if (schema == null) catalog.delete(name);
3234
+ else catalog.set(name, cloneSchema(schema));
3118
3235
  let context;
3119
3236
  context = new QueryContext(this.storage, cloneSnapshot(this.capturedSnapshot), this.keys, {
3120
3237
  writes: this.writes,
@@ -3187,7 +3304,7 @@ var Transaction = class {
3187
3304
  return {
3188
3305
  snapshot: cloneSnapshot(this.capturedSnapshot),
3189
3306
  writes,
3190
- schemaChanges: new Map([...this.schemas].map(([name, schema]) => [name, cloneSchema(schema)]))
3307
+ schemaChanges: new Map([...this.schemas].map(([name, schema]) => [name, schema == null ? null : cloneSchema(schema)]))
3191
3308
  };
3192
3309
  }
3193
3310
  async waitForReads() {
@@ -3245,7 +3362,7 @@ var Transaction = class {
3245
3362
  return value != null && typeof value.execute == "function";
3246
3363
  }
3247
3364
  collection(name) {
3248
- return this.schemas.get(name) ?? this.capturedSnapshot.manifest.catalog.get(name);
3365
+ return this.schemas.has(name) ? this.schemas.get(name) ?? void 0 : this.capturedSnapshot.manifest.catalog.get(name);
3249
3366
  }
3250
3367
  requireCollection(name) {
3251
3368
  const schema = this.collection(name);