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