@coasys/ad4m 0.13.1-staging.12 → 0.13.1-staging.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/lib/index.cjs +548 -477
  2. package/lib/index.js +548 -473
  3. package/lib/src/agent/AgentClient.d.ts +9 -8
  4. package/lib/src/agent/AgentClient.js +46 -67
  5. package/lib/src/cache/KeyedCache.d.ts +51 -0
  6. package/lib/src/cache/KeyedCache.js +142 -0
  7. package/lib/src/expression/ExpressionClient.d.ts +14 -3
  8. package/lib/src/expression/ExpressionClient.js +49 -111
  9. package/lib/src/generated/api/AISessionMessage.d.ts +4 -3
  10. package/lib/src/generated/api/AiEndpoint.d.ts +3 -2
  11. package/lib/src/generated/api/ExpressionLookupError.d.ts +7 -0
  12. package/lib/src/generated/api/ExpressionLookupError.js +2 -0
  13. package/lib/src/generated/api/ExpressionManyEntry.d.ts +6 -0
  14. package/lib/src/generated/api/ExpressionManyEntry.js +1 -0
  15. package/lib/src/generated/api/FlowFiredEntry.d.ts +11 -0
  16. package/lib/src/generated/api/FlowFiredEntry.js +2 -0
  17. package/lib/src/generated/api/PerspectiveFlowFiredParams.d.ts +3 -3
  18. package/lib/src/generated/api/RpcMethods.d.ts +4 -2
  19. package/lib/src/model/Ad4mModel.d.ts +26 -2
  20. package/lib/src/model/Ad4mModel.js +125 -82
  21. package/lib/src/model/ModelQueryBuilder.d.ts +3 -0
  22. package/lib/src/model/ModelQueryBuilder.js +42 -14
  23. package/lib/src/model/index.d.ts +0 -1
  24. package/lib/src/model/index.js +0 -1
  25. package/lib/src/model/query-common.d.ts +8 -0
  26. package/lib/src/model/query-common.js +12 -0
  27. package/lib/src/model/types.d.ts +12 -3
  28. package/lib/src/perspectives/FlowModels.js +1 -1
  29. package/lib/src/perspectives/LiveQuery.d.ts +1 -1
  30. package/lib/src/perspectives/PerspectiveClient.d.ts +17 -6
  31. package/lib/src/perspectives/PerspectiveClient.js +83 -44
  32. package/lib/src/perspectives/PerspectiveProxy.d.ts +19 -10
  33. package/lib/src/perspectives/PerspectiveProxy.js +31 -69
  34. package/package.json +2 -2
  35. package/src/Ad4mClient.test.ts +17 -6
  36. package/src/agent/AgentClient.ts +46 -74
  37. package/src/cache/KeyedCache.test.ts +162 -0
  38. package/src/cache/KeyedCache.ts +179 -0
  39. package/src/cache/cache.test.ts +294 -71
  40. package/src/expression/ExpressionClient.ts +46 -131
  41. package/src/generated/api/AISessionMessage.ts +4 -3
  42. package/src/generated/api/AiEndpoint.ts +3 -2
  43. package/src/generated/api/ExpressionLookupError.ts +6 -0
  44. package/src/generated/api/ExpressionManyEntry.ts +8 -0
  45. package/src/generated/api/FlowFiredEntry.ts +11 -0
  46. package/src/generated/api/PerspectiveFlowFiredParams.ts +3 -3
  47. package/src/generated/api/RpcMethods.ts +4 -2
  48. package/src/model/Ad4mModel.test.ts +237 -43
  49. package/src/model/Ad4mModel.ts +132 -98
  50. package/src/model/ModelQueryBuilder.ts +41 -15
  51. package/src/model/count-result-type.test.ts +72 -0
  52. package/src/model/index.ts +0 -1
  53. package/src/model/query-common.ts +13 -0
  54. package/src/model/relation-filtering.test.ts +3 -5
  55. package/src/model/types.ts +9 -3
  56. package/src/model/write-round-trips.test.ts +30 -6
  57. package/src/perspectives/FlowModels.ts +1 -1
  58. package/src/perspectives/LiveQuery.ts +1 -1
  59. package/src/perspectives/PerspectiveClient.test.ts +287 -0
  60. package/src/perspectives/PerspectiveClient.ts +101 -66
  61. package/src/perspectives/PerspectiveProxy.test.ts +6 -14
  62. package/src/perspectives/PerspectiveProxy.ts +33 -67
  63. package/src/perspectives/TextContent.test.ts +0 -16
  64. package/src/perspectives/shacl-rpc.test.ts +1 -1
  65. package/lib/src/model/query-cache.d.ts +0 -30
  66. package/lib/src/model/query-cache.js +0 -66
  67. package/src/model/query-cache.test.ts +0 -54
  68. package/src/model/query-cache.ts +0 -79
package/lib/index.cjs CHANGED
@@ -1336,13 +1336,13 @@ function isBot(agent) {
1336
1336
  * never need try/catch around cache operations
1337
1337
  * - Tree-shakeable: import only what you need
1338
1338
  */
1339
- var __classPrivateFieldSet$e = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
1339
+ var __classPrivateFieldSet$f = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
1340
1340
  if (kind === "m") throw new TypeError("Private method is not writable");
1341
1341
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
1342
1342
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
1343
1343
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
1344
1344
  };
1345
- var __classPrivateFieldGet$e = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
1345
+ var __classPrivateFieldGet$f = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
1346
1346
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
1347
1347
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
1348
1348
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
@@ -1356,15 +1356,15 @@ class IDBCache {
1356
1356
  _IDBCache_storeName.set(this, void 0);
1357
1357
  _IDBCache_dbPromise.set(this, null);
1358
1358
  _IDBCache_version.set(this, 1);
1359
- __classPrivateFieldSet$e(this, _IDBCache_dbName, dbName, "f");
1360
- __classPrivateFieldSet$e(this, _IDBCache_storeName, storeName, "f");
1359
+ __classPrivateFieldSet$f(this, _IDBCache_dbName, dbName, "f");
1360
+ __classPrivateFieldSet$f(this, _IDBCache_storeName, storeName, "f");
1361
1361
  }
1362
1362
  async get(key) {
1363
1363
  try {
1364
- const db = await __classPrivateFieldGet$e(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
1364
+ const db = await __classPrivateFieldGet$f(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
1365
1365
  return new Promise((resolve) => {
1366
- const tx = db.transaction(__classPrivateFieldGet$e(this, _IDBCache_storeName, "f"), 'readonly');
1367
- const store = tx.objectStore(__classPrivateFieldGet$e(this, _IDBCache_storeName, "f"));
1366
+ const tx = db.transaction(__classPrivateFieldGet$f(this, _IDBCache_storeName, "f"), 'readonly');
1367
+ const store = tx.objectStore(__classPrivateFieldGet$f(this, _IDBCache_storeName, "f"));
1368
1368
  const req = store.get(key);
1369
1369
  req.onsuccess = () => resolve(req.result ?? undefined);
1370
1370
  req.onerror = () => resolve(undefined);
@@ -1376,10 +1376,10 @@ class IDBCache {
1376
1376
  }
1377
1377
  async put(key, value) {
1378
1378
  try {
1379
- const db = await __classPrivateFieldGet$e(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
1379
+ const db = await __classPrivateFieldGet$f(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
1380
1380
  return new Promise((resolve) => {
1381
- const tx = db.transaction(__classPrivateFieldGet$e(this, _IDBCache_storeName, "f"), 'readwrite');
1382
- const store = tx.objectStore(__classPrivateFieldGet$e(this, _IDBCache_storeName, "f"));
1381
+ const tx = db.transaction(__classPrivateFieldGet$f(this, _IDBCache_storeName, "f"), 'readwrite');
1382
+ const store = tx.objectStore(__classPrivateFieldGet$f(this, _IDBCache_storeName, "f"));
1383
1383
  store.put(value, key);
1384
1384
  tx.oncomplete = () => resolve();
1385
1385
  tx.onerror = () => resolve(); // fire-and-forget
@@ -1391,10 +1391,10 @@ class IDBCache {
1391
1391
  }
1392
1392
  async delete(key) {
1393
1393
  try {
1394
- const db = await __classPrivateFieldGet$e(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
1394
+ const db = await __classPrivateFieldGet$f(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
1395
1395
  return new Promise((resolve) => {
1396
- const tx = db.transaction(__classPrivateFieldGet$e(this, _IDBCache_storeName, "f"), 'readwrite');
1397
- const store = tx.objectStore(__classPrivateFieldGet$e(this, _IDBCache_storeName, "f"));
1396
+ const tx = db.transaction(__classPrivateFieldGet$f(this, _IDBCache_storeName, "f"), 'readwrite');
1397
+ const store = tx.objectStore(__classPrivateFieldGet$f(this, _IDBCache_storeName, "f"));
1398
1398
  store.delete(key);
1399
1399
  tx.oncomplete = () => resolve();
1400
1400
  tx.onerror = () => resolve();
@@ -1406,10 +1406,10 @@ class IDBCache {
1406
1406
  }
1407
1407
  async clear() {
1408
1408
  try {
1409
- const db = await __classPrivateFieldGet$e(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
1409
+ const db = await __classPrivateFieldGet$f(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
1410
1410
  return new Promise((resolve) => {
1411
- const tx = db.transaction(__classPrivateFieldGet$e(this, _IDBCache_storeName, "f"), 'readwrite');
1412
- const store = tx.objectStore(__classPrivateFieldGet$e(this, _IDBCache_storeName, "f"));
1411
+ const tx = db.transaction(__classPrivateFieldGet$f(this, _IDBCache_storeName, "f"), 'readwrite');
1412
+ const store = tx.objectStore(__classPrivateFieldGet$f(this, _IDBCache_storeName, "f"));
1413
1413
  store.clear();
1414
1414
  tx.oncomplete = () => resolve();
1415
1415
  tx.onerror = () => resolve();
@@ -1421,10 +1421,10 @@ class IDBCache {
1421
1421
  }
1422
1422
  }
1423
1423
  _IDBCache_dbName = new WeakMap(), _IDBCache_storeName = new WeakMap(), _IDBCache_dbPromise = new WeakMap(), _IDBCache_version = new WeakMap(), _IDBCache_instances = new WeakSet(), _IDBCache_open = function _IDBCache_open() {
1424
- if (!__classPrivateFieldGet$e(this, _IDBCache_dbPromise, "f")) {
1425
- __classPrivateFieldSet$e(this, _IDBCache_dbPromise, new Promise((resolve, reject) => {
1426
- const storeName = __classPrivateFieldGet$e(this, _IDBCache_storeName, "f");
1427
- const req = indexedDB.open(__classPrivateFieldGet$e(this, _IDBCache_dbName, "f"), __classPrivateFieldGet$e(this, _IDBCache_version, "f"));
1424
+ if (!__classPrivateFieldGet$f(this, _IDBCache_dbPromise, "f")) {
1425
+ __classPrivateFieldSet$f(this, _IDBCache_dbPromise, new Promise((resolve, reject) => {
1426
+ const storeName = __classPrivateFieldGet$f(this, _IDBCache_storeName, "f");
1427
+ const req = indexedDB.open(__classPrivateFieldGet$f(this, _IDBCache_dbName, "f"), __classPrivateFieldGet$f(this, _IDBCache_version, "f"));
1428
1428
  req.onupgradeneeded = () => {
1429
1429
  const db = req.result;
1430
1430
  if (!db.objectStoreNames.contains(storeName)) {
@@ -1435,7 +1435,7 @@ _IDBCache_dbName = new WeakMap(), _IDBCache_storeName = new WeakMap(), _IDBCache
1435
1435
  req.onerror = () => reject(req.error);
1436
1436
  }), "f");
1437
1437
  }
1438
- return __classPrivateFieldGet$e(this, _IDBCache_dbPromise, "f");
1438
+ return __classPrivateFieldGet$f(this, _IDBCache_dbPromise, "f");
1439
1439
  };
1440
1440
  // ── NullCache (no-op fallback for Node.js) ───────────────────────────
1441
1441
  class NullCache {
@@ -1463,6 +1463,149 @@ function createPersistentCache(dbName, storeName) {
1463
1463
  return new NullCache();
1464
1464
  }
1465
1465
 
1466
+ var __classPrivateFieldSet$e = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
1467
+ if (kind === "m") throw new TypeError("Private method is not writable");
1468
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
1469
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
1470
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
1471
+ };
1472
+ var __classPrivateFieldGet$e = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
1473
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
1474
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
1475
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
1476
+ };
1477
+ var _KeyedCache_instances, _KeyedCache_opts, _KeyedCache_values, _KeyedCache_bytes, _KeyedCache_pending, _KeyedCache_batch, _KeyedCache_read, _KeyedCache_enqueue, _KeyedCache_loadOne, _KeyedCache_loadBatch, _KeyedCache_stored, _KeyedCache_remember, _KeyedCache_forget;
1478
+ /**
1479
+ * Keyed read cache shared by profile and expression lookups. Concurrent reads
1480
+ * of one key share one request; misses of one tick go out in one `loadMany`
1481
+ * call, except a `get()` miss when the options have `load`. A `null` (not
1482
+ * found) is returned but not kept.
1483
+ */
1484
+ class KeyedCache {
1485
+ constructor(opts) {
1486
+ _KeyedCache_instances.add(this);
1487
+ _KeyedCache_opts.set(this, void 0);
1488
+ _KeyedCache_values.set(this, new Map());
1489
+ _KeyedCache_bytes.set(this, 0);
1490
+ _KeyedCache_pending.set(this, new Map());
1491
+ _KeyedCache_batch.set(this, null);
1492
+ __classPrivateFieldSet$e(this, _KeyedCache_opts, opts, "f");
1493
+ }
1494
+ get(key) {
1495
+ const load = __classPrivateFieldGet$e(this, _KeyedCache_opts, "f").load;
1496
+ return __classPrivateFieldGet$e(this, _KeyedCache_instances, "m", _KeyedCache_read).call(this, key, load ? k => __classPrivateFieldGet$e(this, _KeyedCache_instances, "m", _KeyedCache_loadOne).call(this, k, load) : k => __classPrivateFieldGet$e(this, _KeyedCache_instances, "m", _KeyedCache_enqueue).call(this, k));
1497
+ }
1498
+ getMany(keys) {
1499
+ return Promise.all(keys.map(key => __classPrivateFieldGet$e(this, _KeyedCache_instances, "m", _KeyedCache_read).call(this, key, k => __classPrivateFieldGet$e(this, _KeyedCache_instances, "m", _KeyedCache_enqueue).call(this, k))));
1500
+ }
1501
+ /** Stores a value known to be current; a read in flight for the key is not kept. */
1502
+ set(key, value) {
1503
+ __classPrivateFieldGet$e(this, _KeyedCache_pending, "f").delete(key);
1504
+ __classPrivateFieldGet$e(this, _KeyedCache_instances, "m", _KeyedCache_remember).call(this, key, value, true);
1505
+ }
1506
+ /** Forgets a key in memory and in the persistent store. */
1507
+ delete(key) {
1508
+ __classPrivateFieldGet$e(this, _KeyedCache_pending, "f").delete(key);
1509
+ __classPrivateFieldGet$e(this, _KeyedCache_instances, "m", _KeyedCache_forget).call(this, key);
1510
+ __classPrivateFieldGet$e(this, _KeyedCache_opts, "f").persistent?.delete(key); // fire-and-forget
1511
+ }
1512
+ /** Forgets every key in memory, and in the persistent store when `persistent` is set. */
1513
+ clear(persistent = false) {
1514
+ __classPrivateFieldGet$e(this, _KeyedCache_pending, "f").clear();
1515
+ __classPrivateFieldGet$e(this, _KeyedCache_values, "f").clear();
1516
+ __classPrivateFieldSet$e(this, _KeyedCache_bytes, 0, "f");
1517
+ if (persistent)
1518
+ __classPrivateFieldGet$e(this, _KeyedCache_opts, "f").persistent?.clear(); // fire-and-forget
1519
+ }
1520
+ }
1521
+ _KeyedCache_opts = new WeakMap(), _KeyedCache_values = new WeakMap(), _KeyedCache_bytes = new WeakMap(), _KeyedCache_pending = new WeakMap(), _KeyedCache_batch = new WeakMap(), _KeyedCache_instances = new WeakSet(), _KeyedCache_read = function _KeyedCache_read(key, fetch) {
1522
+ const hit = __classPrivateFieldGet$e(this, _KeyedCache_values, "f").get(key);
1523
+ if (hit && Date.now() - hit.ts < (__classPrivateFieldGet$e(this, _KeyedCache_opts, "f").maxAgeMs?.(key) ?? Infinity))
1524
+ return Promise.resolve(hit.value);
1525
+ const inFlight = __classPrivateFieldGet$e(this, _KeyedCache_pending, "f").get(key);
1526
+ if (inFlight)
1527
+ return inFlight;
1528
+ const loading = fetch(key);
1529
+ const promise = loading.then(({ value, stored }) => {
1530
+ // A set(), delete() or clear() since the read started wins over its result.
1531
+ if (__classPrivateFieldGet$e(this, _KeyedCache_pending, "f").get(key) === promise) {
1532
+ __classPrivateFieldGet$e(this, _KeyedCache_pending, "f").delete(key);
1533
+ if (value !== null)
1534
+ __classPrivateFieldGet$e(this, _KeyedCache_instances, "m", _KeyedCache_remember).call(this, key, value, !stored);
1535
+ }
1536
+ return value;
1537
+ }, (error) => {
1538
+ if (__classPrivateFieldGet$e(this, _KeyedCache_pending, "f").get(key) === promise)
1539
+ __classPrivateFieldGet$e(this, _KeyedCache_pending, "f").delete(key);
1540
+ throw error;
1541
+ });
1542
+ __classPrivateFieldGet$e(this, _KeyedCache_pending, "f").set(key, promise);
1543
+ return promise;
1544
+ }, _KeyedCache_enqueue = function _KeyedCache_enqueue(key) {
1545
+ if (!__classPrivateFieldGet$e(this, _KeyedCache_batch, "f")) {
1546
+ const keys = [];
1547
+ const done = Promise.resolve().then(() => {
1548
+ __classPrivateFieldSet$e(this, _KeyedCache_batch, null, "f");
1549
+ return __classPrivateFieldGet$e(this, _KeyedCache_instances, "m", _KeyedCache_loadBatch).call(this, keys);
1550
+ });
1551
+ __classPrivateFieldSet$e(this, _KeyedCache_batch, { keys, done }, "f");
1552
+ }
1553
+ __classPrivateFieldGet$e(this, _KeyedCache_batch, "f").keys.push(key);
1554
+ return __classPrivateFieldGet$e(this, _KeyedCache_batch, "f").done.then(loaded => {
1555
+ const entry = loaded.get(key);
1556
+ if (entry.value instanceof Error)
1557
+ throw entry.value;
1558
+ return entry;
1559
+ });
1560
+ }, _KeyedCache_loadOne = async function _KeyedCache_loadOne(key, load) {
1561
+ return (await __classPrivateFieldGet$e(this, _KeyedCache_instances, "m", _KeyedCache_stored).call(this, key)) ?? { value: await load(key), stored: false };
1562
+ }, _KeyedCache_loadBatch = async function _KeyedCache_loadBatch(keys) {
1563
+ const loaded = new Map();
1564
+ const stored = await Promise.all(keys.map(key => __classPrivateFieldGet$e(this, _KeyedCache_instances, "m", _KeyedCache_stored).call(this, key)));
1565
+ const misses = keys.filter((key, i) => {
1566
+ if (stored[i])
1567
+ loaded.set(key, stored[i]);
1568
+ return !stored[i];
1569
+ });
1570
+ const size = __classPrivateFieldGet$e(this, _KeyedCache_opts, "f").maxBatch ?? Infinity;
1571
+ const chunks = [];
1572
+ for (let i = 0; i < misses.length; i += size)
1573
+ chunks.push(misses.slice(i, i + size));
1574
+ await Promise.all(chunks.map(async (chunk) => {
1575
+ const values = await __classPrivateFieldGet$e(this, _KeyedCache_opts, "f").loadMany(chunk);
1576
+ chunk.forEach((key, i) => loaded.set(key, { value: values[i] ?? null, stored: false }));
1577
+ }));
1578
+ return loaded;
1579
+ }, _KeyedCache_stored = async function _KeyedCache_stored(key) {
1580
+ const entry = await __classPrivateFieldGet$e(this, _KeyedCache_opts, "f").persistent?.get(key);
1581
+ // An entry without `value` was written in an older format: a miss.
1582
+ if (entry?.value == null || !(Date.now() - (entry.ts ?? 0) < (__classPrivateFieldGet$e(this, _KeyedCache_opts, "f").persistentMaxAgeMs?.() ?? Infinity)))
1583
+ return null;
1584
+ return { value: entry.value, stored: true };
1585
+ }, _KeyedCache_remember = function _KeyedCache_remember(key, value, persist) {
1586
+ const limits = __classPrivateFieldGet$e(this, _KeyedCache_opts, "f").limits?.();
1587
+ const size = limits ? JSON.stringify(value).length : 0;
1588
+ __classPrivateFieldGet$e(this, _KeyedCache_instances, "m", _KeyedCache_forget).call(this, key);
1589
+ if (limits) {
1590
+ for (const oldest of __classPrivateFieldGet$e(this, _KeyedCache_values, "f").keys()) {
1591
+ if (__classPrivateFieldGet$e(this, _KeyedCache_values, "f").size < limits.entries && __classPrivateFieldGet$e(this, _KeyedCache_bytes, "f") + size <= limits.bytes)
1592
+ break;
1593
+ __classPrivateFieldGet$e(this, _KeyedCache_instances, "m", _KeyedCache_forget).call(this, oldest);
1594
+ }
1595
+ }
1596
+ const ts = Date.now();
1597
+ __classPrivateFieldGet$e(this, _KeyedCache_values, "f").set(key, { value, ts, size });
1598
+ __classPrivateFieldSet$e(this, _KeyedCache_bytes, __classPrivateFieldGet$e(this, _KeyedCache_bytes, "f") + size, "f");
1599
+ if (persist)
1600
+ __classPrivateFieldGet$e(this, _KeyedCache_opts, "f").persistent?.put(key, { value, ts }); // fire-and-forget
1601
+ }, _KeyedCache_forget = function _KeyedCache_forget(key) {
1602
+ const entry = __classPrivateFieldGet$e(this, _KeyedCache_values, "f").get(key);
1603
+ if (!entry)
1604
+ return;
1605
+ __classPrivateFieldSet$e(this, _KeyedCache_bytes, __classPrivateFieldGet$e(this, _KeyedCache_bytes, "f") - entry.size, "f");
1606
+ __classPrivateFieldGet$e(this, _KeyedCache_values, "f").delete(key);
1607
+ };
1608
+
1466
1609
  var __classPrivateFieldSet$d = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
1467
1610
  if (kind === "m") throw new TypeError("Private method is not writable");
1468
1611
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
@@ -1474,36 +1617,32 @@ var __classPrivateFieldGet$d = (undefined && undefined.__classPrivateFieldGet) |
1474
1617
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
1475
1618
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
1476
1619
  };
1477
- var _AgentClient_instances, _AgentClient_apiClient, _AgentClient_memCache, _AgentClient_persistent, _AgentClient_selfDid, _AgentClient_cacheAgent, _AgentClient_signLinks, _AgentClient_listen, _AgentClient_onAgentUpdated;
1620
+ var _AgentClient_instances, _AgentClient_apiClient, _AgentClient_agents, _AgentClient_loadAgents, _AgentClient_cacheAgent, _AgentClient_signLinks, _AgentClient_listen, _AgentClient_onAgentUpdated;
1478
1621
  function toAgent(data) {
1479
1622
  return data ? Agent.fromWire(data) : null;
1480
1623
  }
1624
+ /** Most DIDs the executor takes in one `agent.byDIDs` call. */
1625
+ const MAX_DIDS_PER_CALL = 200;
1481
1626
  class AgentClient {
1482
1627
  constructor(baseUrl, token, sharedApiClient) {
1483
1628
  _AgentClient_instances.add(this);
1484
1629
  _AgentClient_apiClient.set(this, void 0);
1485
- // ── byDID cache ────────────────────────────────────────────────────
1486
- // L1: in-memory promise cache with timestamps for TTL
1487
- _AgentClient_memCache.set(this, new Map());
1488
- // L2: persistent cache (IndexedDB in browser, NullCache in Node)
1489
- // Entries are wrapped with a timestamp so the TTL can be enforced across restarts.
1490
- _AgentClient_persistent.set(this, void 0);
1491
- // Self-DID for event-driven invalidation (no TTL for own profile)
1492
- _AgentClient_selfDid.set(this, null);
1630
+ // byDID cache: concurrent misses go out in one `agent.byDIDs` call.
1631
+ _AgentClient_agents.set(this, void 0);
1493
1632
  _AgentClient_onAgentUpdated.set(this, (event) => {
1494
1633
  __classPrivateFieldGet$d(this, _AgentClient_instances, "m", _AgentClient_cacheAgent).call(this, Agent.fromWire(event.agent));
1495
1634
  });
1496
1635
  __classPrivateFieldSet$d(this, _AgentClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), "f");
1497
- __classPrivateFieldSet$d(this, _AgentClient_persistent, createPersistentCache('ad4m-agent-cache', 'agents'), "f");
1636
+ __classPrivateFieldSet$d(this, _AgentClient_agents, new KeyedCache({
1637
+ loadMany: (dids) => __classPrivateFieldGet$d(this, _AgentClient_instances, "m", _AgentClient_loadAgents).call(this, dids),
1638
+ maxBatch: MAX_DIDS_PER_CALL,
1639
+ persistent: createPersistentCache('ad4m-agent-cache', 'agents'),
1640
+ maxAgeMs: () => AgentClient.REMOTE_AGENT_TTL_MS,
1641
+ persistentMaxAgeMs: () => AgentClient.REMOTE_AGENT_TTL_MS,
1642
+ }), "f");
1498
1643
  }
1499
1644
  async me() {
1500
- const agentObject = toAgent(await __classPrivateFieldGet$d(this, _AgentClient_apiClient, "f").call('agent.get', {}));
1501
- // Auto-set selfDid so event-driven cache invalidation works
1502
- // without requiring apps to call setSelfDid() manually
1503
- if (agentObject.did && !__classPrivateFieldGet$d(this, _AgentClient_selfDid, "f")) {
1504
- __classPrivateFieldSet$d(this, _AgentClient_selfDid, agentObject.did, "f");
1505
- }
1506
- return agentObject;
1645
+ return toAgent(await __classPrivateFieldGet$d(this, _AgentClient_apiClient, "f").call('agent.get', {}));
1507
1646
  }
1508
1647
  async status() {
1509
1648
  const agentStatus = await __classPrivateFieldGet$d(this, _AgentClient_apiClient, "f").call('agent.status', {});
@@ -1528,61 +1667,27 @@ class AgentClient {
1528
1667
  const result = await __classPrivateFieldGet$d(this, _AgentClient_apiClient, "f").call('agent.unlock', { passphrase, holochain }, options);
1529
1668
  return new AgentStatus(result);
1530
1669
  }
1531
- async byDID(did) {
1532
- // agent-updated events keep cached entries fresh (the self-DID entry has no TTL).
1533
- __classPrivateFieldGet$d(this, _AgentClient_instances, "m", _AgentClient_listen).call(this);
1534
- const now = Date.now();
1535
- const cached = __classPrivateFieldGet$d(this, _AgentClient_memCache, "f").get(did);
1536
- if (cached) {
1537
- const isSelf = did === __classPrivateFieldGet$d(this, _AgentClient_selfDid, "f");
1538
- // Self-DID: L1 always valid (event-driven invalidation)
1539
- // Remote DID: L1 valid within TTL
1540
- if (isSelf || (now - cached.ts) < AgentClient.REMOTE_AGENT_TTL_MS) {
1541
- return cached.promise;
1542
- }
1543
- }
1544
- // Deduplicate: store the promise immediately so concurrent calls share one RPC
1545
- const promise = (async () => {
1546
- // L2: check persistent cache before network
1547
- const entry = await __classPrivateFieldGet$d(this, _AgentClient_persistent, "f").get(did);
1548
- // entry.agent may be undefined for pre-TTL cache entries (migration) — treat as expired
1549
- if (entry?.agent && (now - (entry.ts ?? 0)) < AgentClient.REMOTE_AGENT_TTL_L2_MS) {
1550
- return entry.agent;
1551
- }
1552
- // L3: network fetch
1553
- const result = toAgent(await __classPrivateFieldGet$d(this, _AgentClient_apiClient, "f").call('agent.byDid', { did }));
1554
- __classPrivateFieldGet$d(this, _AgentClient_persistent, "f").put(did, { agent: result, ts: Date.now() }); // fire-and-forget write to L2
1555
- return result;
1556
- })();
1557
- __classPrivateFieldGet$d(this, _AgentClient_memCache, "f").set(did, { promise, ts: now });
1558
- // Clean up on failure so next call retries
1559
- promise.catch(() => {
1560
- if (__classPrivateFieldGet$d(this, _AgentClient_memCache, "f").get(did)?.promise === promise) {
1561
- __classPrivateFieldGet$d(this, _AgentClient_memCache, "f").delete(did);
1562
- }
1563
- });
1564
- return promise;
1565
- }
1566
1670
  /**
1567
- * Set the current agent's own DID.
1568
- * The self-DID receives event-driven invalidation and is never TTL-expired.
1671
+ * The agent with this DID, or `null` when it is unknown. Concurrent calls
1672
+ * for any DIDs share one `agent.byDIDs` request.
1569
1673
  */
1570
- setSelfDid(did) {
1571
- __classPrivateFieldSet$d(this, _AgentClient_selfDid, did, "f");
1674
+ async byDID(did) {
1675
+ // agent-updated events refresh cached entries before their TTL runs out.
1676
+ __classPrivateFieldGet$d(this, _AgentClient_instances, "m", _AgentClient_listen).call(this);
1677
+ return __classPrivateFieldGet$d(this, _AgentClient_agents, "f").get(did);
1572
1678
  }
1573
1679
  /**
1574
1680
  * Invalidate a specific DID's cache entry in both L1 and L2.
1575
1681
  */
1576
1682
  invalidateByDid(did) {
1577
- __classPrivateFieldGet$d(this, _AgentClient_memCache, "f").delete(did);
1578
- __classPrivateFieldGet$d(this, _AgentClient_persistent, "f").delete(did); // fire-and-forget
1683
+ __classPrivateFieldGet$d(this, _AgentClient_agents, "f").delete(did);
1579
1684
  }
1580
1685
  /**
1581
1686
  * Clear the entire L1 (memory) byDID cache.
1582
1687
  * L2 (IndexedDB) is preserved — agent data remains valid across sessions.
1583
1688
  */
1584
1689
  clearByDidCache() {
1585
- __classPrivateFieldGet$d(this, _AgentClient_memCache, "f").clear();
1690
+ __classPrivateFieldGet$d(this, _AgentClient_agents, "f").clear();
1586
1691
  }
1587
1692
  async updatePublicPerspective(perspective) {
1588
1693
  // Send only the signed fields: the public perspective carries no link status.
@@ -1714,11 +1819,25 @@ class AgentClient {
1714
1819
  return __classPrivateFieldGet$d(this, _AgentClient_apiClient, "f").call('hosting.requestPayment', { amountHOT });
1715
1820
  }
1716
1821
  }
1717
- _AgentClient_apiClient = new WeakMap(), _AgentClient_memCache = new WeakMap(), _AgentClient_persistent = new WeakMap(), _AgentClient_selfDid = new WeakMap(), _AgentClient_onAgentUpdated = new WeakMap(), _AgentClient_instances = new WeakSet(), _AgentClient_cacheAgent = function _AgentClient_cacheAgent(agent) {
1822
+ _AgentClient_apiClient = new WeakMap(), _AgentClient_agents = new WeakMap(), _AgentClient_onAgentUpdated = new WeakMap(), _AgentClient_instances = new WeakSet(), _AgentClient_loadAgents =
1823
+ /**
1824
+ * One `agent.byDIDs` call for the misses of one tick. The executor fails
1825
+ * that call when one DID's lookup fails (500), so the DIDs of a failed
1826
+ * batch are then read alone: each caller gets what a lone `byDID` gives.
1827
+ */
1828
+ async function _AgentClient_loadAgents(dids) {
1829
+ try {
1830
+ return (await __classPrivateFieldGet$d(this, _AgentClient_apiClient, "f").call('agent.byDIDs', { dids })).map(toAgent);
1831
+ }
1832
+ catch (error) {
1833
+ if (dids.length === 1 || !(error instanceof RpcError) || error.status !== 500)
1834
+ throw error;
1835
+ return Promise.all(dids.map(did => __classPrivateFieldGet$d(this, _AgentClient_apiClient, "f").call('agent.byDid', { did }).then(toAgent, (failure) => failure instanceof Error ? failure : new Error(String(failure)))));
1836
+ }
1837
+ }, _AgentClient_cacheAgent = function _AgentClient_cacheAgent(agent) {
1718
1838
  if (!agent.did)
1719
1839
  return;
1720
- __classPrivateFieldGet$d(this, _AgentClient_memCache, "f").set(agent.did, { promise: Promise.resolve(agent), ts: Date.now() });
1721
- __classPrivateFieldGet$d(this, _AgentClient_persistent, "f").put(agent.did, { agent, ts: Date.now() }); // fire-and-forget
1840
+ __classPrivateFieldGet$d(this, _AgentClient_agents, "f").set(agent.did, agent);
1722
1841
  __classPrivateFieldGet$d(this, _AgentClient_instances, "m", _AgentClient_listen).call(this);
1723
1842
  }, _AgentClient_signLinks =
1724
1843
  /** Has the executor sign `links` as this agent, in a throwaway perspective. */
@@ -1733,11 +1852,13 @@ async function _AgentClient_signLinks(links) {
1733
1852
  }, _AgentClient_listen = function _AgentClient_listen() {
1734
1853
  __classPrivateFieldGet$d(this, _AgentClient_apiClient, "f").on('agent-updated', __classPrivateFieldGet$d(this, _AgentClient_onAgentUpdated, "f"));
1735
1854
  };
1736
- /** TTL for remote (non-self) agent profiles in L1 cache (ms). */
1855
+ /**
1856
+ * TTL of every cached profile, the own one too, in memory and in the
1857
+ * persistent cache (ms). `agent-updated` only comes from this executor, so
1858
+ * a profile changed through another executor of the same agent shows up
1859
+ * when the entry expires.
1860
+ */
1737
1861
  AgentClient.REMOTE_AGENT_TTL_MS = 5 * 60000; // 5 minutes
1738
- /** TTL for remote agent profiles in the L2 (IndexedDB) cache (ms).
1739
- * After this window any restart triggers a fresh network fetch. */
1740
- AgentClient.REMOTE_AGENT_TTL_L2_MS = 5 * 60000; // 5 minutes
1741
1862
 
1742
1863
  var __classPrivateFieldSet$c = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
1743
1864
  if (kind === "m") throw new TypeError("Private method is not writable");
@@ -7647,73 +7768,6 @@ function BelongsToMany(first, second) {
7647
7768
  };
7648
7769
  }
7649
7770
 
7650
- /**
7651
- * Query Result TTL Cache
7652
- *
7653
- * Short-lived cache (200ms TTL) for SPARQL query results.
7654
- * Prevents redundant queries during rapid render cycles where
7655
- * multiple components issue the same query within milliseconds.
7656
- *
7657
- * Key: `perspectiveUUID + queryText`
7658
- */
7659
- const cache = new Map();
7660
- const DEFAULT_TTL_MS = 200;
7661
- function makeKey(perspectiveUUID, queryText) {
7662
- return `${perspectiveUUID}:${queryText}`;
7663
- }
7664
- /**
7665
- * Get a cached query result if it exists and hasn't expired.
7666
- */
7667
- function getCachedResult(perspectiveUUID, queryText) {
7668
- const key = makeKey(perspectiveUUID, queryText);
7669
- const entry = cache.get(key);
7670
- if (!entry)
7671
- return undefined;
7672
- if (Date.now() > entry.expiry) {
7673
- cache.delete(key);
7674
- return undefined;
7675
- }
7676
- return entry.result;
7677
- }
7678
- /**
7679
- * Store a query result in the cache with TTL.
7680
- */
7681
- function setCachedResult(perspectiveUUID, queryText, result, ttlMs = DEFAULT_TTL_MS) {
7682
- // Lazy eviction of expired entries
7683
- const now = Date.now();
7684
- for (const [key, entry] of cache) {
7685
- if (now > entry.expiry) {
7686
- cache.delete(key);
7687
- }
7688
- }
7689
- const cacheKey = makeKey(perspectiveUUID, queryText);
7690
- cache.set(cacheKey, { result, expiry: now + ttlMs });
7691
- }
7692
- /**
7693
- * Invalidate all cache entries for a given perspective.
7694
- * Called after write operations to ensure stale data isn't served.
7695
- */
7696
- function invalidatePerspectiveCache(perspectiveUUID) {
7697
- const prefix = perspectiveUUID + ':';
7698
- for (const [key] of cache) {
7699
- if (key.startsWith(prefix)) {
7700
- cache.delete(key);
7701
- }
7702
- }
7703
- }
7704
- /**
7705
- * Clear all cache entries (useful for testing).
7706
- */
7707
- function clearQueryCache() {
7708
- cache.clear();
7709
- }
7710
- /**
7711
- * Get the current size of the cache (useful for testing).
7712
- */
7713
- function queryCacheSize() {
7714
- return cache.size;
7715
- }
7716
-
7717
7771
  var __classPrivateFieldSet$8 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
7718
7772
  if (kind === "m") throw new TypeError("Private method is not writable");
7719
7773
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
@@ -9089,9 +9143,7 @@ class PerspectiveProxy {
9089
9143
  * @param batchId - Optional batch ID to group this operation with others
9090
9144
  */
9091
9145
  async executeAction(actions, expression, parameters, batchId) {
9092
- const result = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").executeCommands(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId);
9093
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
9094
- return result;
9146
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").executeCommands(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId);
9095
9147
  }
9096
9148
  /**
9097
9149
  * Retrieves links from the perspective that match the given query.
@@ -9319,12 +9371,15 @@ class PerspectiveProxy {
9319
9371
  return await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").flowStates(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, instances);
9320
9372
  }
9321
9373
  /**
9322
- * The proposals of `instance` whose votes settled an edge, as this
9323
- * agent's executor recorded them — the flow's history, sorted by URI.
9374
+ * For each of `instances`, in order, the proposals whose votes settled an
9375
+ * edge, as this agent's executor recorded them — the flow's history,
9376
+ * sorted by URI (`fired: []` when none). One call covers up to 200
9377
+ * instances (the executor refuses more with a 400); split a longer list
9378
+ * into batches of 200.
9324
9379
  * Replaces the `resolvedAs` property proposals used to carry.
9325
9380
  */
9326
- async flowFired(instance) {
9327
- return await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").flowFired(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, instance);
9381
+ async flowFired(instances) {
9382
+ return await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").flowFired(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, instances);
9328
9383
  }
9329
9384
  /**
9330
9385
  * Called whenever a flow instance on this perspective changes state on
@@ -9388,20 +9443,18 @@ class PerspectiveProxy {
9388
9443
  * keep its blocking thread busy until it completes; what's saved is the
9389
9444
  * serialise + network + client-deserialise tax on the result. Aborted
9390
9445
  * calls reject with `DOMException('Aborted', 'AbortError')` — match
9391
- * `fetch()` for handling. Cached results bypass the round-trip entirely
9392
- * and are returned synchronously, ignoring the signal.
9446
+ * `fetch()` for handling. A call with `options` makes its own RPC.
9447
+ *
9448
+ * **Sharing:** concurrent identical calls without `options` share one RPC;
9449
+ * each caller gets its own result object. Nothing is cached once the
9450
+ * call settles: use a live query for repeated reads of the same data.
9393
9451
  *
9394
9452
  * @param query - SPARQL query string (read-only operations only)
9395
9453
  * @param options - Optional call options (e.g. AbortSignal for cancellation)
9396
9454
  * @returns Query results as parsed JSON
9397
9455
  */
9398
9456
  async querySparql(query, options) {
9399
- const cached = getCachedResult(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, query);
9400
- if (cached !== undefined)
9401
- return cached;
9402
- const result = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").querySparql(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, query, options);
9403
- setCachedResult(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, query, result);
9404
- return result;
9457
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").querySparql(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, query, options);
9405
9458
  }
9406
9459
  /**
9407
9460
  * Execute a model query — the executor-side replacement for SPARQL query building + JS hydration.
@@ -9414,7 +9467,7 @@ class PerspectiveProxy {
9414
9467
  * query over their union, whose rows carry `__subjectClass` and
9415
9468
  * `__subjectClasses` (#1238)
9416
9469
  * @param queryJson - Structured query as JSON string
9417
- * @returns Object with `instances` array and `totalCount`
9470
+ * @returns Object with `instances` array, and `totalCount` when the query sets `count: true`
9418
9471
  */
9419
9472
  async modelQuery(className, queryJson, options) {
9420
9473
  return await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, options);
@@ -9508,9 +9561,7 @@ class PerspectiveProxy {
9508
9561
  * ```
9509
9562
  */
9510
9563
  async add(link, status = 'shared', batchId) {
9511
- const result = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").addLink(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
9512
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
9513
- return result;
9564
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").addLink(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
9514
9565
  }
9515
9566
  /**
9516
9567
  * Adds multiple links to the perspective in a single operation.
@@ -9522,9 +9573,7 @@ class PerspectiveProxy {
9522
9573
  * @returns Array of created LinkExpressions
9523
9574
  */
9524
9575
  async addLinks(links, status = 'shared', batchId) {
9525
- const result = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").addLinks(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, links, status, batchId);
9526
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
9527
- return result;
9576
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").addLinks(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, links, status, batchId);
9528
9577
  }
9529
9578
  /**
9530
9579
  * Removes multiple links from the perspective.
@@ -9534,9 +9583,7 @@ class PerspectiveProxy {
9534
9583
  * @returns Array of removed LinkExpressions
9535
9584
  */
9536
9585
  async removeLinks(links, batchId) {
9537
- const result = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").removeLinks(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, links, batchId);
9538
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
9539
- return result;
9586
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").removeLinks(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, links, batchId);
9540
9587
  }
9541
9588
  /**
9542
9589
  * Applies a set of link mutations (adds and removes) in a single operation.
@@ -9547,9 +9594,7 @@ class PerspectiveProxy {
9547
9594
  * @returns Object containing results of the mutations
9548
9595
  */
9549
9596
  async linkMutations(mutations, status = 'shared') {
9550
- const result = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").linkMutations(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, mutations, status);
9551
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
9552
- return result;
9597
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").linkMutations(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, mutations, status);
9553
9598
  }
9554
9599
  /**
9555
9600
  * Adds a pre-signed LinkExpression to the perspective.
@@ -9576,9 +9621,7 @@ class PerspectiveProxy {
9576
9621
  * @param batchId - Optional batch ID to group this operation with others
9577
9622
  */
9578
9623
  async update(oldLink, newLink, batchId) {
9579
- const result = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").updateLink(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, oldLink, newLink, batchId);
9580
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
9581
- return result;
9624
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").updateLink(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, oldLink, newLink, batchId);
9582
9625
  }
9583
9626
  /**
9584
9627
  * Removes a link from the perspective.
@@ -9624,9 +9667,7 @@ class PerspectiveProxy {
9624
9667
  else {
9625
9668
  resolvedLink = link;
9626
9669
  }
9627
- const result = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, resolvedLink, batchId);
9628
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
9629
- return result;
9670
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, resolvedLink, batchId);
9630
9671
  }
9631
9672
  /** Creates a new batch for grouping operations */
9632
9673
  async createBatch() {
@@ -9634,9 +9675,7 @@ class PerspectiveProxy {
9634
9675
  }
9635
9676
  /** Commits a batch of operations */
9636
9677
  async commitBatch(batchId) {
9637
- const result = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").commitBatch(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, batchId);
9638
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
9639
- return result;
9678
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").commitBatch(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, batchId);
9640
9679
  }
9641
9680
  /**
9642
9681
  * Drops an open batch without committing it — the recovery for a failed batched call:
@@ -10004,13 +10043,13 @@ class PerspectiveProxy {
10004
10043
  return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").getShaclTargetClass(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, name);
10005
10044
  }
10006
10045
  /**
10007
- * Get all SHACL shapes stored in this Perspective (one RPC call).
10008
- * The executor resolves all shapes in-process and returns them in bulk.
10046
+ * Get the SHACL shapes stored in this Perspective in one RPC call: all of
10047
+ * them, or only those named in `names` (unknown names are left out).
10009
10048
  * A shape that fails to decode is skipped with a `console.warn`, so it
10010
10049
  * does not hide the others.
10011
10050
  */
10012
- async getAllShacl() {
10013
- const entries = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").getAllShacl(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10051
+ async getAllShacl(options) {
10052
+ const entries = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").getAllShacl(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, options?.names);
10014
10053
  const shapes = [];
10015
10054
  for (const { name, shapeUri, links } of entries) {
10016
10055
  try {
@@ -10251,7 +10290,6 @@ class PerspectiveProxy {
10251
10290
  * record that the abstract class reads, under its own name. */
10252
10291
  async updateSubject(className, exprAddr, values, batchId) {
10253
10292
  await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").updateSubject(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, className, exprAddr, JSON.stringify(values), batchId);
10254
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10255
10293
  }
10256
10294
  /**
10257
10295
  * Creates an instance of a subject class, validated by the executor against the class's
@@ -10270,42 +10308,23 @@ class PerspectiveProxy {
10270
10308
  * const { baseUri } = await perspective.instanceCreate({ className: "Task", properties: { title: "Write" } });
10271
10309
  */
10272
10310
  async instanceCreate(body) {
10273
- const created = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceCreate(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10274
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10275
- return created;
10311
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceCreate(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10276
10312
  }
10277
10313
  /** Sets single-valued properties of an instance, validated; the others stay. See {@link instanceCreate}. */
10278
10314
  async instanceUpdate(body) {
10279
- const updated = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceUpdate(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10280
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10281
- return updated;
10315
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceUpdate(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10282
10316
  }
10283
10317
  /** Removes an instance and every link to and from it. See {@link instanceCreate}. */
10284
10318
  async instanceRemove(body) {
10285
- // Outside a batch the links go one by one, so a rejection (`partiallyRemoved`) can
10286
- // come after some are gone: invalidate either way.
10287
- try {
10288
- return await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceRemove(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10289
- }
10290
- finally {
10291
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10292
- }
10319
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceRemove(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10293
10320
  }
10294
10321
  /** Adds an item to a collection of an instance, validated. See {@link instanceCreate}. */
10295
10322
  async instanceAddToCollection(body) {
10296
- const added = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceAddToCollection(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10297
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10298
- return added;
10323
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceAddToCollection(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10299
10324
  }
10300
10325
  /** Removes an item from a collection of an instance. See {@link instanceCreate}. */
10301
10326
  async instanceRemoveFromCollection(body) {
10302
- // Like instanceRemove, a rejection can come after some links are gone.
10303
- try {
10304
- return await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceRemoveFromCollection(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10305
- }
10306
- finally {
10307
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10308
- }
10327
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceRemoveFromCollection(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10309
10328
  }
10310
10329
  async getSubjectData(subjectClass, exprAddr) {
10311
10330
  if (typeof subjectClass === "string") {
@@ -10369,7 +10388,6 @@ class PerspectiveProxy {
10369
10388
  const ctor = subjectClass?.constructor;
10370
10389
  if (typeof subjectClass === "object" && ctor && Object.prototype.hasOwnProperty.call(ctor, 'builtinUri')) {
10371
10390
  await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").removeSubject(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, ctor.builtinUri, exprAddr, batchId);
10372
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10373
10391
  return;
10374
10392
  }
10375
10393
  let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);
@@ -10379,7 +10397,6 @@ class PerspectiveProxy {
10379
10397
  const markers = await this.get(new LinkQuery({ predicate: "ad4m://abstract" }));
10380
10398
  if (markers.some((link) => shapePattern.test(link.data.source))) {
10381
10399
  await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").removeSubject(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, className, exprAddr, batchId);
10382
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10383
10400
  return;
10384
10401
  }
10385
10402
  // Get destructor actions from SHACL links (Prolog-free)
@@ -10948,7 +10965,7 @@ var __classPrivateFieldGet$6 = (undefined && undefined.__classPrivateFieldGet) |
10948
10965
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10949
10966
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
10950
10967
  };
10951
- var _PerspectiveClient_instances, _PerspectiveClient_apiClient, _PerspectiveClient_expressionClient, _PerspectiveClient_neighbourhoodClient, _PerspectiveClient_aiClient, _PerspectiveClient_released;
10968
+ var _PerspectiveClient_instances, _PerspectiveClient_apiClient, _PerspectiveClient_expressionClient, _PerspectiveClient_neighbourhoodClient, _PerspectiveClient_aiClient, _PerspectiveClient_sparqlInFlight, _PerspectiveClient_writeGeneration, _PerspectiveClient_wrote, _PerspectiveClient_released;
10952
10969
  /** The wire form of a model query's classes: `class_name` for one, `class_names` for a union. */
10953
10970
  function classParams(className) {
10954
10971
  return Array.isArray(className) ? { class_names: className } : { class_name: className };
@@ -10970,6 +10987,11 @@ class PerspectiveClient {
10970
10987
  _PerspectiveClient_expressionClient.set(this, void 0);
10971
10988
  _PerspectiveClient_neighbourhoodClient.set(this, void 0);
10972
10989
  _PerspectiveClient_aiClient.set(this, void 0);
10990
+ _PerspectiveClient_sparqlInFlight.set(this, new Map()
10991
+ /** Per perspective, how many writes through this client have settled; part of the in-flight key. */
10992
+ );
10993
+ /** Per perspective, how many writes through this client have settled; part of the in-flight key. */
10994
+ _PerspectiveClient_writeGeneration.set(this, new Map());
10973
10995
  __classPrivateFieldSet$6(this, _PerspectiveClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), "f");
10974
10996
  }
10975
10997
  setExpressionClient(client) {
@@ -11029,9 +11051,24 @@ class PerspectiveClient {
11029
11051
  const result = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.queryProlog', { uuid, query }, options);
11030
11052
  return JSON.parse(result);
11031
11053
  }
11054
+ /**
11055
+ * Concurrent identical calls (same perspective and query, no `options`)
11056
+ * share one RPC. Each caller parses its own copy of the reply, and a call
11057
+ * made after the shared one settled makes a new RPC. So does a call made
11058
+ * after a write through this client settled: the shared RPC may have been
11059
+ * answered before the write (see `#wrote`).
11060
+ */
11032
11061
  async querySparql(uuid, query, options) {
11033
- const result = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.querySparql', { uuid, engine: 'sparql', query }, options);
11034
- return JSON.parse(result);
11062
+ if (options)
11063
+ return JSON.parse(await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.querySparql', { uuid, engine: 'sparql', query }, options));
11064
+ const key = `${uuid}\n${__classPrivateFieldGet$6(this, _PerspectiveClient_writeGeneration, "f").get(uuid) ?? 0}\n${query}`;
11065
+ let reply = __classPrivateFieldGet$6(this, _PerspectiveClient_sparqlInFlight, "f").get(key);
11066
+ if (!reply) {
11067
+ reply = __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.querySparql', { uuid, engine: 'sparql', query })
11068
+ .finally(() => __classPrivateFieldGet$6(this, _PerspectiveClient_sparqlInFlight, "f").delete(key));
11069
+ __classPrivateFieldGet$6(this, _PerspectiveClient_sparqlInFlight, "f").set(key, reply);
11070
+ }
11071
+ return JSON.parse(await reply);
11035
11072
  }
11036
11073
  /** Open a live SPARQL query. Updates arrive through {@link onQueryUpdate}. */
11037
11074
  /** `options.signal` cancels the call, and the executor stops computing the first result. */
@@ -11088,19 +11125,19 @@ class PerspectiveClient {
11088
11125
  return { perspectiveRemove: result };
11089
11126
  }
11090
11127
  async addLink(uuid, link, status = 'shared', batchId) {
11091
- const added = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.addLink', { uuid, link, status, batchId });
11128
+ const added = await __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.addLink', { uuid, link, status, batchId }));
11092
11129
  return LinkExpression.fromWire(added);
11093
11130
  }
11094
11131
  async addLinks(uuid, links, status = 'shared', batchId) {
11095
- const added = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.addLinks', { uuid, links, status, batchId });
11132
+ const added = await __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.addLinks', { uuid, links, status, batchId }));
11096
11133
  return added.map(LinkExpression.fromWire);
11097
11134
  }
11098
11135
  async removeLinks(uuid, links, batchId) {
11099
- const removed = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.removeLinks', { uuid, links: links.map(linkExpressionInputToWire), batchId });
11136
+ const removed = await __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.removeLinks', { uuid, links: links.map(linkExpressionInputToWire), batchId }));
11100
11137
  return removed.map(LinkExpression.fromWire);
11101
11138
  }
11102
11139
  async linkMutations(uuid, mutations, status) {
11103
- const diff = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.linkMutations', { uuid, mutations: linkMutationsToWire(mutations), status });
11140
+ const diff = await __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.linkMutations', { uuid, mutations: linkMutationsToWire(mutations), status }));
11104
11141
  return LinkExpressionMutations.fromWire(diff);
11105
11142
  }
11106
11143
  /**
@@ -11120,11 +11157,11 @@ class PerspectiveClient {
11120
11157
  * are NOT re-parented — same rule as the watcher).
11121
11158
  */
11122
11159
  async runInterpretation(uuid, transcript, basePrefix, classes, existingScope, mintScope, observe, options) {
11123
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretation', {
11160
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretation', {
11124
11161
  uuid, transcript, basePrefix, classes, existingScope, mintScope,
11125
11162
  observationId: observe?.observationId,
11126
11163
  emitDebugEvents: observe?.emitDebugEvents,
11127
- }, options);
11164
+ }, options));
11128
11165
  }
11129
11166
  /**
11130
11167
  * Tool-calling counterpart to {@link runInterpretation}. The LLM sees a
@@ -11147,7 +11184,7 @@ class PerspectiveClient {
11147
11184
  // `emitDebugEvents` is a dead-letter without an observationId
11148
11185
  // (nothing to key against); the server gates on both.
11149
11186
  observationId, emitDebugEvents, options) {
11150
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretationWithHarness', {
11187
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretationWithHarness', {
11151
11188
  uuid,
11152
11189
  transcript,
11153
11190
  basePrefix,
@@ -11157,7 +11194,7 @@ class PerspectiveClient {
11157
11194
  existingScope,
11158
11195
  observationId,
11159
11196
  emitDebugEvents,
11160
- }, options);
11197
+ }, options));
11161
11198
  }
11162
11199
  /**
11163
11200
  * A conversation with a model in this perspective, using the executor's own tools: the tools
@@ -11170,7 +11207,9 @@ class PerspectiveClient {
11170
11207
  * calls before it answers.
11171
11208
  */
11172
11209
  async runAgent(uuid, messages, settings, options) {
11173
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.runAgent', { uuid, messages, ...settings }, options);
11210
+ const reply = __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.runAgent', { uuid, messages, ...settings }, options);
11211
+ // Without write tools the session only reads.
11212
+ return settings?.writeTools?.length ? __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, reply) : reply;
11174
11213
  }
11175
11214
  /**
11176
11215
  * Register a neighbourhood auto-processor on this perspective. The executor's
@@ -11181,11 +11220,11 @@ class PerspectiveClient {
11181
11220
  * Returns the processor id.
11182
11221
  */
11183
11222
  async addAutoProcessor(uuid, config) {
11184
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.addAutoProcessor', { ...config, uuid });
11223
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.addAutoProcessor', { ...config, uuid }));
11185
11224
  }
11186
11225
  /** Delete an auto-processor's config. `false` when there was none to delete. */
11187
11226
  async removeAutoProcessor(uuid, processorId) {
11188
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.removeAutoProcessor', { uuid, processorId });
11227
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.removeAutoProcessor', { uuid, processorId }));
11189
11228
  }
11190
11229
  /** Pending interpretation overlays (LLM suggestions awaiting human accept/reject). */
11191
11230
  async interpretationOverlays(uuid) {
@@ -11197,18 +11236,18 @@ class PerspectiveClient {
11197
11236
  /** Accept an overlay's suggestion(s): the LLM value becomes the real value and
11198
11237
  * the overlay is deleted. Omit `property` to accept the whole base. */
11199
11238
  async acceptInterpretation(uuid, base, property) {
11200
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.acceptInterpretation', { uuid, base, property });
11239
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.acceptInterpretation', { uuid, base, property }));
11201
11240
  }
11202
11241
  /** Reject an overlay's suggestion(s). Omit `property` to reject the whole base
11203
11242
  * (a rejected `create` deletes the suggested instance). */
11204
11243
  async rejectInterpretation(uuid, base, property) {
11205
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectInterpretation', { uuid, base, property });
11244
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectInterpretation', { uuid, base, property }));
11206
11245
  }
11207
11246
  async proposeFlowTransition(uuid, instanceUri, toState, rationale, outputs) {
11208
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.proposeFlowTransition', { uuid, instanceUri, toState, rationale, outputs });
11247
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.proposeFlowTransition', { uuid, instanceUri, toState, rationale, outputs }));
11209
11248
  }
11210
11249
  async acceptFlowProposal(uuid, proposalUri) {
11211
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.acceptFlowProposal', { uuid, proposalUri });
11250
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.acceptFlowProposal', { uuid, proposalUri }));
11212
11251
  }
11213
11252
  /**
11214
11253
  * Withdraw this agent's own links from a proposal. Resolves to how many
@@ -11216,7 +11255,7 @@ class PerspectiveClient {
11216
11255
  * proposal this agent opened.
11217
11256
  */
11218
11257
  async rejectFlowProposal(uuid, proposalUri) {
11219
- const result = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectFlowProposal', { uuid, proposalUri });
11258
+ const result = await __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectFlowProposal', { uuid, proposalUri }));
11220
11259
  return result.retractedLinks;
11221
11260
  }
11222
11261
  /** Re-decide a flow receipt under this perspective's own flow catalogue. */
@@ -11233,49 +11272,51 @@ class PerspectiveClient {
11233
11272
  async flowStates(uuid, instances) {
11234
11273
  return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.flowStates', { uuid, instances });
11235
11274
  }
11236
- /** The proposals of `instance` the calling agent's replica recorded as
11237
- * fired, sorted. */
11238
- async flowFired(uuid, instance) {
11239
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.flowFired', { uuid, instance });
11275
+ /** For each of `instances`, in order, the proposals the calling agent's
11276
+ * replica recorded as fired, sorted. One call covers up to 200
11277
+ * instances (more is refused with a 400); split a longer list into
11278
+ * batches of 200. */
11279
+ async flowFired(uuid, instances) {
11280
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.flowFired', { uuid, instances });
11240
11281
  }
11241
11282
  /** Mint and store the receipt for a completed flow run. Fails while the
11242
11283
  * run has not settled into a terminal state, and when an output's
11243
11284
  * content no longer matches what the quorum committed to. */
11244
11285
  async mintFlowReceipt(uuid, instanceUri) {
11245
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.mintFlowReceipt', { uuid, instanceUri });
11286
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.mintFlowReceipt', { uuid, instanceUri }));
11246
11287
  }
11247
11288
  async addLinkExpression(uuid, link, status = 'shared', batchId) {
11248
- const added = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.addLinkExpression', { uuid, link: linkExpressionToWire(link), status, batchId });
11289
+ const added = await __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.addLinkExpression', { uuid, link: linkExpressionToWire(link), status, batchId }));
11249
11290
  return LinkExpression.fromWire(added);
11250
11291
  }
11251
11292
  async updateLink(uuid, oldLink, newLink, batchId) {
11252
- const updated = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.updateLink', { uuid, oldLink: linkExpressionInputToWire(oldLink), newLink, batchId });
11293
+ const updated = await __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.updateLink', { uuid, oldLink: linkExpressionInputToWire(oldLink), newLink, batchId }));
11253
11294
  return LinkExpression.fromWire(updated);
11254
11295
  }
11255
11296
  async removeLink(uuid, link, batchId) {
11256
11297
  const { status, ...wire } = linkExpressionInputToWire(link);
11257
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.removeLink', { uuid, link: wire, batchId });
11298
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.removeLink', { uuid, link: wire, batchId }));
11258
11299
  }
11259
11300
  async addSdna(uuid, name, sdnaCode, sdnaType, shaclJson) {
11260
- const result = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.addSdna', { uuid, name, sdnaCode: sdnaCode || "", sdnaType, shaclJson });
11301
+ const result = await __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.addSdna', { uuid, name, sdnaCode: sdnaCode || "", sdnaType, shaclJson }));
11261
11302
  return typeof result === 'boolean' ? result : result.every(Boolean);
11262
11303
  }
11263
11304
  async addSdnaBatch(uuid, entries) {
11264
- const result = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.addSdna', { uuid, entries: entries.map(e => ({ ...e, sdnaCode: e.sdnaCode || "" })) });
11305
+ const result = await __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.addSdna', { uuid, entries: entries.map(e => ({ ...e, sdnaCode: e.sdnaCode || "" })) }));
11265
11306
  return typeof result === 'boolean' ? [result] : result;
11266
11307
  }
11267
11308
  async executeCommands(uuid, commands, expression, parameters, batchId) {
11268
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.executeCommands', { uuid, commands, expression, parameters, batchId });
11309
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.executeCommands', { uuid, commands, expression, parameters, batchId }));
11269
11310
  }
11270
11311
  async createSubject(uuid, subjectClass, expressionAddress, initialValues, batchId) {
11271
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.createSubject', { uuid, subjectClass, expressionAddress, initialValues, batchId });
11312
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.createSubject', { uuid, subjectClass, expressionAddress, initialValues, batchId }));
11272
11313
  }
11273
11314
  /** Through an abstract class (#1435), the executor writes to the record's own classes. */
11274
11315
  async updateSubject(uuid, subjectClass, expressionAddress, values, batchId) {
11275
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.updateSubject', { uuid, subjectClass, expressionAddress, values, batchId });
11316
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.updateSubject', { uuid, subjectClass, expressionAddress, values, batchId }));
11276
11317
  }
11277
11318
  async removeSubject(uuid, subjectClass, expressionAddress, batchId) {
11278
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.removeSubject', { uuid, subjectClass, expressionAddress, batchId });
11319
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.removeSubject', { uuid, subjectClass, expressionAddress, batchId }));
11279
11320
  }
11280
11321
  /**
11281
11322
  * Validated writes (`perspective.instance*`): the executor checks each against the class's
@@ -11295,23 +11336,23 @@ class PerspectiveClient {
11295
11336
  * it to keep the calls that succeeded.
11296
11337
  */
11297
11338
  async instanceCreate(uuid, body) {
11298
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceCreate', { uuid, ...body });
11339
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceCreate', { uuid, ...body }));
11299
11340
  }
11300
11341
  /** Sets the given single-valued properties; the others stay. See {@link instanceCreate}. */
11301
11342
  async instanceUpdate(uuid, body) {
11302
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceUpdate', { uuid, ...body });
11343
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceUpdate', { uuid, ...body }));
11303
11344
  }
11304
11345
  /** Removes the instance and every link to and from it. See {@link instanceCreate}. */
11305
11346
  async instanceRemove(uuid, body) {
11306
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceRemove', { uuid, ...body });
11347
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceRemove', { uuid, ...body }));
11307
11348
  }
11308
11349
  /** Adds an item to a collection (a no-op when it is a member). See {@link instanceCreate}. */
11309
11350
  async instanceAddToCollection(uuid, body) {
11310
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceAddToCollection', { uuid, ...body });
11351
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceAddToCollection', { uuid, ...body }));
11311
11352
  }
11312
11353
  /** Removes an item's membership link from a collection. See {@link instanceCreate}. */
11313
11354
  async instanceRemoveFromCollection(uuid, body) {
11314
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceRemoveFromCollection', { uuid, ...body });
11355
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceRemoveFromCollection', { uuid, ...body }));
11315
11356
  }
11316
11357
  async getSubjectData(uuid, subjectClass, expressionAddress) {
11317
11358
  return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.getSubjectData', { uuid, subjectClass, expressionAddress });
@@ -11347,11 +11388,12 @@ class PerspectiveClient {
11347
11388
  return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.getShacl', { uuid, name });
11348
11389
  }
11349
11390
  /**
11350
- * Retrieve all SHACL shapes in one call. Returns an array of
11351
- * `{name, shapeUri, links}` — one entry per shape (one RPC call).
11391
+ * Retrieve SHACL shapes in one call: every shape, or only those in
11392
+ * `names` (unknown names are left out). Returns `{name, shapeUri, links}`
11393
+ * per shape.
11352
11394
  */
11353
- async getAllShacl(uuid) {
11354
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.getAllShacl', { uuid });
11395
+ async getAllShacl(uuid, names) {
11396
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.getAllShacl', { uuid, names });
11355
11397
  }
11356
11398
  // ExpressionClient functions, needed for Subjects:
11357
11399
  async getExpression(expressionURI) {
@@ -11371,7 +11413,7 @@ class PerspectiveClient {
11371
11413
  return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.createBatch', { uuid });
11372
11414
  }
11373
11415
  async commitBatch(uuid, batchId) {
11374
- const diff = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.commitBatch', { uuid, batchId });
11416
+ const diff = await __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.commitBatch', { uuid, batchId }));
11375
11417
  return LinkExpressionMutations.fromWire(diff);
11376
11418
  }
11377
11419
  /**
@@ -11389,7 +11431,21 @@ class PerspectiveClient {
11389
11431
  return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").onReconnect(callback);
11390
11432
  }
11391
11433
  }
11392
- _PerspectiveClient_apiClient = new WeakMap(), _PerspectiveClient_expressionClient = new WeakMap(), _PerspectiveClient_neighbourhoodClient = new WeakMap(), _PerspectiveClient_aiClient = new WeakMap(), _PerspectiveClient_instances = new WeakSet(), _PerspectiveClient_released =
11434
+ _PerspectiveClient_apiClient = new WeakMap(), _PerspectiveClient_expressionClient = new WeakMap(), _PerspectiveClient_neighbourhoodClient = new WeakMap(), _PerspectiveClient_aiClient = new WeakMap(), _PerspectiveClient_sparqlInFlight = new WeakMap(), _PerspectiveClient_writeGeneration = new WeakMap(), _PerspectiveClient_instances = new WeakSet(), _PerspectiveClient_wrote =
11435
+ /**
11436
+ * Await a write to `uuid`, then start a new write generation for it
11437
+ * (also when the write failed: it may still have changed the perspective).
11438
+ * Calls of {@link querySparql} already waiting keep sharing their RPC; an
11439
+ * identical call started from now on makes its own.
11440
+ */
11441
+ async function _PerspectiveClient_wrote(uuid, write) {
11442
+ try {
11443
+ return await write;
11444
+ }
11445
+ finally {
11446
+ __classPrivateFieldGet$6(this, _PerspectiveClient_writeGeneration, "f").set(uuid, (__classPrivateFieldGet$6(this, _PerspectiveClient_writeGeneration, "f").get(uuid) ?? 0) + 1);
11447
+ }
11448
+ }, _PerspectiveClient_released =
11393
11449
  /** A subscribe call that failed (timed out, aborted, refused) leaves no live
11394
11450
  * query on the executor that nobody holds. The client minted its id, so it
11395
11451
  * disposes it without the reply. A timeout or an abort sends `request.cancel`
@@ -11637,112 +11693,59 @@ var __classPrivateFieldGet$4 = (undefined && undefined.__classPrivateFieldGet) |
11637
11693
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11638
11694
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11639
11695
  };
11640
- var _ExpressionClient_instances, _ExpressionClient_apiClient, _ExpressionClient_memCache, _ExpressionClient_inflight, _ExpressionClient_totalMemBytes, _ExpressionClient_persistent, _ExpressionClient_memCacheResult;
11696
+ var _ExpressionClient_apiClient, _ExpressionClient_expressions;
11697
+ /** Most URLs the executor takes in one `expression.getMany` call. */
11698
+ const MAX_URLS_PER_CALL = 200;
11641
11699
  class ExpressionClient {
11642
11700
  constructor(baseUrl, token, sharedApiClient) {
11643
- _ExpressionClient_instances.add(this);
11644
11701
  _ExpressionClient_apiClient.set(this, void 0);
11645
- // L1: in-memory LRU cache (hot path, sub-ms)
11646
- _ExpressionClient_memCache.set(this, new Map());
11647
- _ExpressionClient_inflight.set(this, new Map());
11648
- _ExpressionClient_totalMemBytes.set(this, 0);
11649
- // L2: persistent cache (IndexedDB in browser, NullCache in Node)
11650
- _ExpressionClient_persistent.set(this, void 0);
11702
+ // A `get` miss is its own `expression.get`, so it waits for no slower
11703
+ // expression and has its own call timeout. The misses of the `getMany`
11704
+ // calls made in one tick go out in `expression.getMany` calls of at most
11705
+ // MAX_URLS_PER_CALL URLs, which answer per URL what `expression.get` would.
11706
+ _ExpressionClient_expressions.set(this, void 0);
11651
11707
  __classPrivateFieldSet$4(this, _ExpressionClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), "f");
11652
- __classPrivateFieldSet$4(this, _ExpressionClient_persistent, createPersistentCache('ad4m-expression-cache', 'expressions'), "f");
11708
+ __classPrivateFieldSet$4(this, _ExpressionClient_expressions, new KeyedCache({
11709
+ load: (url) => __classPrivateFieldGet$4(this, _ExpressionClient_apiClient, "f").call('expression.get', { url }),
11710
+ loadMany: async (urls) => (await __classPrivateFieldGet$4(this, _ExpressionClient_apiClient, "f").call('expression.getMany', { urls })).map(entry => entry && 'code' in entry ? new RpcError(entry.code, entry.message) : entry),
11711
+ maxBatch: MAX_URLS_PER_CALL,
11712
+ persistent: createPersistentCache('ad4m-expression-cache', 'expressions'),
11713
+ maxAgeMs: () => ExpressionClient.EXPRESSION_TTL_MS,
11714
+ persistentMaxAgeMs: () => ExpressionClient.EXPRESSION_TTL_MS,
11715
+ limits: () => ({ entries: ExpressionClient.MAX_MEM_ENTRIES, bytes: ExpressionClient.MAX_MEM_BYTES }),
11716
+ }), "f");
11653
11717
  }
11718
+ /** The expression at `url`; `alwaysGet` skips the literal fast path and the cache. */
11654
11719
  async get(url, alwaysGet = false) {
11655
- // Existing literal fast-path
11656
- if (!alwaysGet) {
11657
- try {
11658
- let literalValue = Literal.fromUrl(url).get();
11659
- if (typeof literalValue === 'object' && literalValue !== null) {
11660
- if ('author' in literalValue && 'timestamp' in literalValue && 'data' in literalValue && 'proof' in literalValue) {
11661
- return literalValue;
11662
- }
11663
- }
11664
- }
11665
- catch (e) { }
11666
- }
11667
- // L1: memory hit
11668
- if (!alwaysGet) {
11669
- const memHit = __classPrivateFieldGet$4(this, _ExpressionClient_memCache, "f").get(url);
11670
- if (memHit)
11671
- return memHit.data;
11672
- }
11673
- // Deduplicate in-flight requests
11674
- if (!alwaysGet) {
11675
- const existing = __classPrivateFieldGet$4(this, _ExpressionClient_inflight, "f").get(url);
11676
- if (existing)
11677
- return existing;
11678
- }
11679
- // L2 check + L3 network
11680
- const promise = (async () => {
11681
- if (!alwaysGet) {
11682
- const persisted = await __classPrivateFieldGet$4(this, _ExpressionClient_persistent, "f").get(url);
11683
- if (persisted) {
11684
- __classPrivateFieldGet$4(this, _ExpressionClient_instances, "m", _ExpressionClient_memCacheResult).call(this, url, persisted); // promote to L1
11685
- return persisted;
11686
- }
11687
- }
11688
- // L3: network fetch
11720
+ if (alwaysGet) {
11689
11721
  const result = await __classPrivateFieldGet$4(this, _ExpressionClient_apiClient, "f").call('expression.get', { url });
11690
- __classPrivateFieldGet$4(this, _ExpressionClient_instances, "m", _ExpressionClient_memCacheResult).call(this, url, result);
11691
- __classPrivateFieldGet$4(this, _ExpressionClient_persistent, "f").put(url, result); // fire-and-forget write to L2
11722
+ if (result)
11723
+ __classPrivateFieldGet$4(this, _ExpressionClient_expressions, "f").set(url, result);
11692
11724
  return result;
11693
- })();
11694
- __classPrivateFieldGet$4(this, _ExpressionClient_inflight, "f").set(url, promise);
11695
- try {
11696
- return await promise;
11697
11725
  }
11698
- finally {
11699
- __classPrivateFieldGet$4(this, _ExpressionClient_inflight, "f").delete(url);
11726
+ try {
11727
+ let literalValue = Literal.fromUrl(url).get();
11728
+ if (typeof literalValue === 'object' && literalValue !== null) {
11729
+ if ('author' in literalValue && 'timestamp' in literalValue && 'data' in literalValue && 'proof' in literalValue) {
11730
+ return literalValue;
11731
+ }
11732
+ }
11700
11733
  }
11734
+ catch (e) { }
11735
+ return __classPrivateFieldGet$4(this, _ExpressionClient_expressions, "f").get(url);
11701
11736
  }
11737
+ /**
11738
+ * The expressions at `urls`, in order (`null` when not found); the misses go
11739
+ * out in calls of at most 200 URLs. Rejects with the `RpcError` `get` gives when a URL's read fails.
11740
+ */
11702
11741
  async getMany(urls) {
11703
- // Check L1 first
11704
- const results = urls.map(u => __classPrivateFieldGet$4(this, _ExpressionClient_memCache, "f").get(u)?.data ?? null);
11705
- let uncachedIndices = results
11706
- .map((r, i) => r === null ? i : -1)
11707
- .filter(i => i >= 0);
11708
- if (uncachedIndices.length === 0)
11709
- return results;
11710
- // Check L2 for remaining misses
11711
- const l2Results = await Promise.all(uncachedIndices.map(i => __classPrivateFieldGet$4(this, _ExpressionClient_persistent, "f").get(urls[i])));
11712
- const stillMissing = [];
11713
- for (let j = 0; j < uncachedIndices.length; j++) {
11714
- const idx = uncachedIndices[j];
11715
- if (l2Results[j]) {
11716
- results[idx] = l2Results[j];
11717
- __classPrivateFieldGet$4(this, _ExpressionClient_instances, "m", _ExpressionClient_memCacheResult).call(this, urls[idx], l2Results[j]); // promote to L1
11718
- }
11719
- else {
11720
- stillMissing.push(idx);
11721
- }
11722
- }
11723
- if (stillMissing.length === 0)
11724
- return results;
11725
- // L3: fetch only truly uncached URLs
11726
- const uncachedUrls = stillMissing.map(i => urls[i]);
11727
- const fetched = await __classPrivateFieldGet$4(this, _ExpressionClient_apiClient, "f").call('expression.getMany', { urls: uncachedUrls });
11728
- for (let i = 0; i < stillMissing.length; i++) {
11729
- const idx = stillMissing[i];
11730
- results[idx] = fetched[i];
11731
- if (fetched[i]) {
11732
- __classPrivateFieldGet$4(this, _ExpressionClient_instances, "m", _ExpressionClient_memCacheResult).call(this, uncachedUrls[i], fetched[i]);
11733
- __classPrivateFieldGet$4(this, _ExpressionClient_persistent, "f").put(uncachedUrls[i], fetched[i]); // fire-and-forget
11734
- }
11735
- }
11736
- return results;
11742
+ return __classPrivateFieldGet$4(this, _ExpressionClient_expressions, "f").getMany(urls);
11737
11743
  }
11738
11744
  /**
11739
- * Clear both L1 (memory) and L2 (persistent) expression caches.
11745
+ * Clear both the memory and the persistent expression caches.
11740
11746
  */
11741
11747
  clearCache() {
11742
- __classPrivateFieldGet$4(this, _ExpressionClient_memCache, "f").clear();
11743
- __classPrivateFieldGet$4(this, _ExpressionClient_inflight, "f").clear();
11744
- __classPrivateFieldSet$4(this, _ExpressionClient_totalMemBytes, 0, "f");
11745
- __classPrivateFieldGet$4(this, _ExpressionClient_persistent, "f").clear(); // fire-and-forget
11748
+ __classPrivateFieldGet$4(this, _ExpressionClient_expressions, "f").clear(true);
11746
11749
  }
11747
11750
  async getRaw(url) {
11748
11751
  return __classPrivateFieldGet$4(this, _ExpressionClient_apiClient, "f").call('expression.getRaw', { url });
@@ -11757,31 +11760,21 @@ class ExpressionClient {
11757
11760
  async interact(url, interactionCall) {
11758
11761
  const result = await __classPrivateFieldGet$4(this, _ExpressionClient_apiClient, "f").call('expression.interact', { url, interactionCall });
11759
11762
  // Interactions can mutate the expression — invalidate cache so next get() fetches fresh
11760
- __classPrivateFieldGet$4(this, _ExpressionClient_memCache, "f").delete(url);
11761
- __classPrivateFieldGet$4(this, _ExpressionClient_inflight, "f").delete(url);
11762
- __classPrivateFieldGet$4(this, _ExpressionClient_persistent, "f").delete(url); // fire-and-forget
11763
+ __classPrivateFieldGet$4(this, _ExpressionClient_expressions, "f").delete(url);
11763
11764
  return result;
11764
11765
  }
11765
11766
  }
11766
- _ExpressionClient_apiClient = new WeakMap(), _ExpressionClient_memCache = new WeakMap(), _ExpressionClient_inflight = new WeakMap(), _ExpressionClient_totalMemBytes = new WeakMap(), _ExpressionClient_persistent = new WeakMap(), _ExpressionClient_instances = new WeakSet(), _ExpressionClient_memCacheResult = function _ExpressionClient_memCacheResult(url, data) {
11767
- const size = JSON.stringify(data).length;
11768
- // Evict oldest entries if we'd exceed limits
11769
- while (__classPrivateFieldGet$4(this, _ExpressionClient_memCache, "f").size >= ExpressionClient.MAX_MEM_ENTRIES ||
11770
- __classPrivateFieldGet$4(this, _ExpressionClient_totalMemBytes, "f") + size > ExpressionClient.MAX_MEM_BYTES) {
11771
- const oldest = __classPrivateFieldGet$4(this, _ExpressionClient_memCache, "f").keys().next().value;
11772
- if (!oldest)
11773
- break;
11774
- const entry = __classPrivateFieldGet$4(this, _ExpressionClient_memCache, "f").get(oldest);
11775
- __classPrivateFieldSet$4(this, _ExpressionClient_totalMemBytes, __classPrivateFieldGet$4(this, _ExpressionClient_totalMemBytes, "f") - entry.size, "f");
11776
- __classPrivateFieldGet$4(this, _ExpressionClient_memCache, "f").delete(oldest);
11777
- }
11778
- __classPrivateFieldGet$4(this, _ExpressionClient_memCache, "f").set(url, { data, size });
11779
- __classPrivateFieldSet$4(this, _ExpressionClient_totalMemBytes, __classPrivateFieldGet$4(this, _ExpressionClient_totalMemBytes, "f") + size, "f");
11780
- };
11781
- /** Maximum number of entries in the L1 memory cache. */
11767
+ _ExpressionClient_apiClient = new WeakMap(), _ExpressionClient_expressions = new WeakMap();
11768
+ /** Maximum number of expressions kept in memory. */
11782
11769
  ExpressionClient.MAX_MEM_ENTRIES = 200;
11783
- /** Maximum total size (in bytes) of L1 memory cache values. */
11770
+ /** Maximum total size (in bytes of JSON) of the expressions kept in memory. */
11784
11771
  ExpressionClient.MAX_MEM_BYTES = 5 * 1024 * 1024; // 5 MB
11772
+ /**
11773
+ * TTL of every cached expression, in memory and in the persistent cache
11774
+ * (ms). A language may change what a URL returns, and no event tells the
11775
+ * client, so a cached expression expires instead of staying stale.
11776
+ */
11777
+ ExpressionClient.EXPRESSION_TTL_MS = 5 * 60000; // 5 minutes
11785
11778
 
11786
11779
  var base64Js = {};
11787
11780
 
@@ -19298,6 +19291,18 @@ function isIncludeProjection(val) {
19298
19291
  /**
19299
19292
  * Shared query helpers used by both the Prolog and SPARQL query pipelines.
19300
19293
  */
19294
+ /**
19295
+ * The `totalCount` of a model query sent with `count: true`. The executor
19296
+ * answers such a query with a count, so an answer without one is an error,
19297
+ * not zero matches.
19298
+ */
19299
+ function requireTotalCount(answer) {
19300
+ const totalCount = answer?.totalCount;
19301
+ if (typeof totalCount !== "number") {
19302
+ throw new Error("model query asked for a count (count: true) but the answer has no totalCount");
19303
+ }
19304
+ return totalCount;
19305
+ }
19301
19306
  /**
19302
19307
  * Resolves the predicate for a parent query.
19303
19308
  *
@@ -20380,12 +20385,17 @@ class ModelQueryBuilder {
20380
20385
  return { live, initial: await live.start() };
20381
20386
  }
20382
20387
  catch (e) {
20383
- live.dispose();
20384
- if (this.currentSubscription === live)
20385
- this.currentSubscription = undefined;
20388
+ this.endFailed(live);
20386
20389
  throw e;
20387
20390
  }
20388
20391
  }
20392
+ /** End `live` after its call failed. A later call may already own
20393
+ * `currentSubscription`, so only clear it if it is still `live`. */
20394
+ endFailed(live) {
20395
+ live.dispose();
20396
+ if (this.currentSubscription === live)
20397
+ this.currentSubscription = undefined;
20398
+ }
20389
20399
  /**
20390
20400
  * Adds where conditions to the query.
20391
20401
  *
@@ -20772,8 +20782,7 @@ class ModelQueryBuilder {
20772
20782
  * ```
20773
20783
  */
20774
20784
  async count() {
20775
- const { totalCount } = await this.execute({ ...this.queryParams, limit: 0 });
20776
- return totalCount;
20785
+ return requireTotalCount(await this.execute({ ...this.queryParams, limit: 0, count: true }));
20777
20786
  }
20778
20787
  /**
20779
20788
  * Gets the total count of matching entities using SPARQL.
@@ -20812,8 +20821,23 @@ class ModelQueryBuilder {
20812
20821
  */
20813
20822
  async countSubscribe(callback) {
20814
20823
  this.dispose();
20815
- const { initial } = await this.live({ ...this.queryParams, limit: 0 }, (raw) => callback(raw.totalCount ?? 0));
20816
- return initial.totalCount ?? 0;
20824
+ // As paginateSubscribe: a push without the asked-for count is logged and
20825
+ // skipped, since a throw here would reach the client's update dispatch.
20826
+ const { live, initial } = await this.live({ ...this.queryParams, limit: 0, count: true }, (raw) => {
20827
+ try {
20828
+ callback(requireTotalCount(raw));
20829
+ }
20830
+ catch (e) {
20831
+ console.error('Count subscription error:', e);
20832
+ }
20833
+ });
20834
+ try {
20835
+ return requireTotalCount(initial);
20836
+ }
20837
+ catch (e) {
20838
+ this.endFailed(live);
20839
+ throw e;
20840
+ }
20817
20841
  }
20818
20842
  /**
20819
20843
  * Subscribes to count updates using SPARQL.
@@ -20839,8 +20863,8 @@ class ModelQueryBuilder {
20839
20863
  */
20840
20864
  async paginate(pageSize, pageNumber) {
20841
20865
  const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
20842
- const { results, totalCount } = await this.execute(paginationQuery);
20843
- return { results, totalCount, pageSize, pageNumber };
20866
+ const answer = await this.execute(paginationQuery);
20867
+ return { results: answer.results, totalCount: requireTotalCount(answer), pageSize, pageNumber };
20844
20868
  }
20845
20869
  /**
20846
20870
  * Gets a page of results using SPARQL.
@@ -20903,9 +20927,10 @@ class ModelQueryBuilder {
20903
20927
  const results = this.parse(raw);
20904
20928
  const fp = fingerprint([results, raw?.totalCount]);
20905
20929
  this.takeSnapshots(results);
20906
- return { page: { results, totalCount: raw?.totalCount, pageSize, pageNumber }, fp };
20930
+ // `count: true` is set above, so the executor sends a total.
20931
+ return { page: { results, totalCount: requireTotalCount(raw), pageSize, pageNumber }, fp };
20907
20932
  };
20908
- const { initial } = await this.live(paginatedQuery, (raw) => {
20933
+ const { live, initial } = await this.live(paginatedQuery, (raw) => {
20909
20934
  try {
20910
20935
  const { page, fp } = toPage(raw);
20911
20936
  if (fp === lastFingerprint)
@@ -20917,9 +20942,16 @@ class ModelQueryBuilder {
20917
20942
  console.error('Paginate subscription error:', e);
20918
20943
  }
20919
20944
  });
20920
- const { page, fp } = toPage(initial);
20921
- lastFingerprint = fp;
20922
- return page;
20945
+ let first;
20946
+ try {
20947
+ first = toPage(initial);
20948
+ }
20949
+ catch (e) {
20950
+ this.endFailed(live);
20951
+ throw e;
20952
+ }
20953
+ lastFingerprint = first.fp;
20954
+ return first.page;
20923
20955
  }
20924
20956
  /**
20925
20957
  * Subscribes to paginated results updates using SPARQL.
@@ -21292,6 +21324,8 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
21292
21324
  }
21293
21325
  return instance;
21294
21326
  }
21327
+ /** The most writes `sendWrites` joins into one `executeAction` call. */
21328
+ const MAX_WRITES_PER_CALL = 200;
21295
21329
  /**
21296
21330
  * Put `childId` under `parent`. A containment scope `{ id }` writes through the
21297
21331
  * built-in `Container` (#1446): the executor runs the adder of the parent's own
@@ -22347,8 +22381,8 @@ class Ad4mModel {
22347
22381
  * ```
22348
22382
  */
22349
22383
  static async findAllAndCount(perspective, query, options) {
22350
- const out = await this.executeModelQuery(perspective, (query ?? {}), undefined, options);
22351
- return out;
22384
+ const answer = await this.executeModelQuery(perspective, { ...(query ?? {}), count: true }, undefined, options);
22385
+ return { results: answer.results, totalCount: requireTotalCount(answer) };
22352
22386
  }
22353
22387
  /**
22354
22388
  * Helper function for pagination with explicit page size and number.
@@ -22369,8 +22403,8 @@ class Ad4mModel {
22369
22403
  */
22370
22404
  static async paginate(perspective, pageSize, pageNumber, query, options) {
22371
22405
  const paginationQuery = { ...(query ?? {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
22372
- const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery, undefined, options);
22373
- return { results: results, totalCount, pageSize, pageNumber };
22406
+ const answer = await this.executeModelQuery(perspective, paginationQuery, undefined, options);
22407
+ return { results: answer.results, totalCount: requireTotalCount(answer), pageSize, pageNumber };
22374
22408
  }
22375
22409
  /**
22376
22410
  * Generates a SPARQL COUNT query for the model.
@@ -22398,20 +22432,20 @@ class Ad4mModel {
22398
22432
  * ```
22399
22433
  */
22400
22434
  static async count(perspective, query, options) {
22401
- const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 }, undefined, options);
22402
- return totalCount;
22435
+ return requireTotalCount(await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0, count: true }, undefined, options));
22403
22436
  }
22404
- async setProperty(key, value, batchId) {
22437
+ /** The `executeAction` write that sets property `key` to `value`; none for an empty value. */
22438
+ async planProperty(key, value) {
22405
22439
  const metadata = this.getPropertyMetadata(key);
22406
22440
  if (!metadata) {
22407
22441
  console.warn(`Property "${key}" has no metadata, skipping`);
22408
- return;
22442
+ return [];
22409
22443
  }
22410
22444
  // Generate actions from metadata (replaces Prolog query)
22411
22445
  const actions = this.generatePropertySetterAction(key, metadata);
22412
22446
  // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal:string:)
22413
22447
  if (value === undefined || value === null || value === "") {
22414
- return;
22448
+ return [];
22415
22449
  }
22416
22450
  const mode = effectiveLiteralStorage(metadata);
22417
22451
  if (mode.kind === "custom") {
@@ -22426,7 +22460,77 @@ class Ad4mModel {
22426
22460
  // Deterministic literal: IRI (POS-index friendly).
22427
22461
  value = valueToLiteralIri(value);
22428
22462
  }
22429
- await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value }], batchId);
22463
+ return [{ commands: actions, parameters: [{ name: "value", value }] }];
22464
+ }
22465
+ /**
22466
+ * The `executeAction` writes of a relation change: one for a set (its
22467
+ * `collectionSetter` takes every value), one per value for an add or remove.
22468
+ */
22469
+ planRelation(key, kind, value) {
22470
+ const metadata = this.getRelationOptions(key);
22471
+ if (!metadata) {
22472
+ console.warn(`Relation "${key}" has no metadata, skipping`);
22473
+ return [];
22474
+ }
22475
+ // Generate actions from metadata (replaces Prolog query)
22476
+ const actions = this.generateRelationAction(key, kind);
22477
+ if (value == null)
22478
+ return [];
22479
+ const values = Array.isArray(value) ? value : [value];
22480
+ const param = (v) => ({ name: "value", value: this.resolveRelationId(v) });
22481
+ if (kind === 'setter')
22482
+ return [{ commands: actions, parameters: values.map(param) }];
22483
+ return values.map(v => ({ commands: actions, parameters: [param(v)] }));
22484
+ }
22485
+ /**
22486
+ * Sends writes in as few `executeAction` calls as keep their links: the
22487
+ * executor runs a call's commands in order, so consecutive writes share one
22488
+ * call, each with its own parameter names. A `collectionSetter` takes every
22489
+ * parameter of its call as a member, so it goes in a call of its own. A
22490
+ * command's `local` flag is per command, so Local and Shared links mix. The
22491
+ * executor tries every parameter name at each position of each command, so
22492
+ * a call holds at most `MAX_WRITES_PER_CALL` writes.
22493
+ */
22494
+ async sendWrites(writes, batchId) {
22495
+ let group = [];
22496
+ const flush = async () => {
22497
+ if (group.length === 1) {
22498
+ await this._perspective.executeAction(group[0].commands, this._baseExpression, group[0].parameters, batchId);
22499
+ }
22500
+ else if (group.length > 1) {
22501
+ const commands = [];
22502
+ const parameters = [];
22503
+ group.forEach((write, i) => {
22504
+ // The executor substitutes a parameter name wherever it occurs in a
22505
+ // command's source, predicate or target; rename `value` the same way.
22506
+ const name = `ad4m-model-write-${i}-value`;
22507
+ const rename = (s) => (typeof s === "string" && write.parameters.length ? s.split("value").join(name) : s);
22508
+ for (const c of write.commands) {
22509
+ commands.push({ ...c, source: rename(c.source), predicate: rename(c.predicate), target: rename(c.target) });
22510
+ }
22511
+ for (const p of write.parameters)
22512
+ parameters.push({ name, value: p.value });
22513
+ });
22514
+ await this._perspective.executeAction(commands, this._baseExpression, parameters, batchId);
22515
+ }
22516
+ group = [];
22517
+ };
22518
+ for (const write of writes) {
22519
+ if (write.commands.some((c) => c.action === "collectionSetter")) {
22520
+ await flush();
22521
+ group = [write];
22522
+ await flush();
22523
+ }
22524
+ else {
22525
+ group.push(write);
22526
+ if (group.length >= MAX_WRITES_PER_CALL)
22527
+ await flush();
22528
+ }
22529
+ }
22530
+ await flush();
22531
+ }
22532
+ async setProperty(key, value, batchId) {
22533
+ await this.sendWrites(await this.planProperty(key, value), batchId);
22430
22534
  }
22431
22535
  /** Resolve a relation argument to a plain string ID. Accepts either a raw
22432
22536
  * string ID or an Ad4mModel instance (in which case `.id` is used). */
@@ -22446,75 +22550,33 @@ class Ad4mModel {
22446
22550
  await this._perspective.updateSubject(abstractName, this._baseExpression, { [key]: { action, value: ids } }, batchId);
22447
22551
  }
22448
22552
  async setRelationValues(key, value, batchId) {
22449
- const metadata = this.getRelationOptions(key);
22450
- if (!metadata) {
22451
- console.warn(`Relation "${key}" has no metadata, skipping`);
22452
- return;
22453
- }
22454
- this._relationsWritten.add(metadata.predicate);
22455
- const abstractName = this.abstractName();
22456
- if (abstractName) {
22457
- if (value != null)
22458
- await this.relationThroughAbstract(abstractName, key, 'setter', value, batchId);
22459
- return;
22460
- }
22461
- // Generate actions from metadata (replaces Prolog query)
22462
- const actions = this.generateRelationAction(key, 'setter');
22463
- if (value != null) {
22464
- if (Array.isArray(value)) {
22465
- await this._perspective.executeAction(actions, this._baseExpression, value.map((v) => ({ name: "value", value: this.resolveRelationId(v) })), batchId);
22466
- }
22467
- else {
22468
- await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(value) }], batchId);
22469
- }
22470
- }
22553
+ await this.writeRelation(key, 'setter', value, batchId);
22471
22554
  }
22472
22555
  async addRelationValue(key, value, batchId) {
22473
- const metadata = this.getRelationOptions(key);
22474
- if (!metadata) {
22475
- console.warn(`Relation "${key}" has no metadata, skipping`);
22476
- return;
22477
- }
22478
- this._relationsWritten.add(metadata.predicate);
22479
- const abstractName = this.abstractName();
22480
- if (abstractName) {
22481
- if (value != null)
22482
- await this.relationThroughAbstract(abstractName, key, 'adder', value, batchId);
22483
- return;
22484
- }
22485
- // Generate actions from metadata (replaces Prolog query)
22486
- const actions = this.generateRelationAction(key, 'adder');
22487
- if (value != null) {
22488
- if (Array.isArray(value)) {
22489
- await Promise.all(value.map((v) => this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(v) }], batchId)));
22490
- }
22491
- else {
22492
- await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(value) }], batchId);
22493
- }
22494
- }
22556
+ await this.writeRelation(key, 'adder', value, batchId);
22495
22557
  }
22496
22558
  async removeRelationValue(key, value, batchId) {
22497
- const metadata = this.getRelationOptions(key);
22498
- if (!metadata) {
22499
- console.warn(`Relation "${key}" has no metadata, skipping`);
22500
- return;
22501
- }
22559
+ await this.writeRelation(key, 'remover', value, batchId);
22560
+ }
22561
+ /** A relation setter, adder or remover call: on a row read through an
22562
+ * abstract class it dispatches through the executor (see
22563
+ * {@link relationThroughAbstract}); otherwise its writes go out in as few
22564
+ * `executeAction` calls as {@link sendWrites} allows. */
22565
+ async writeRelation(key, kind, value, batchId) {
22566
+ const predicate = this.getRelationOptions(key)?.predicate;
22567
+ if (predicate && kind !== 'remover')
22568
+ this._relationsWritten.add(predicate);
22502
22569
  const abstractName = this.abstractName();
22503
- if (abstractName) {
22504
- if (value != null)
22505
- await this.relationThroughAbstract(abstractName, key, 'remover', value, batchId);
22570
+ if (!abstractName) {
22571
+ await this.sendWrites(this.planRelation(key, kind, value), batchId);
22506
22572
  return;
22507
22573
  }
22508
- // Generate actions from metadata (replaces Prolog query)
22509
- const actions = this.generateRelationAction(key, 'remover');
22510
- if (value != null) {
22511
- if (Array.isArray(value)) {
22512
- await Promise.all(value.map((v) => this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(v) }], batchId)));
22513
- }
22514
- else {
22515
- await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(value) }], batchId);
22516
- }
22574
+ if (!this.getRelationOptions(key)) {
22575
+ console.warn(`Relation "${key}" has no metadata, skipping`);
22576
+ return;
22517
22577
  }
22578
+ if (value != null)
22579
+ await this.relationThroughAbstract(abstractName, key, kind, value, batchId);
22518
22580
  }
22519
22581
  /**
22520
22582
  * Saves the model instance to the perspective.
@@ -22604,13 +22666,14 @@ class Ad4mModel {
22604
22666
  const className = await this.perspective.stringOrTemplateObjectToSubjectClassName(this);
22605
22667
  await this.perspective.createSubject(className, this._baseExpression, initialValues, batchId);
22606
22668
  // Relations via innerUpdate; createSubject wrote the scalar properties.
22607
- await this.innerUpdate(false, batchId);
22669
+ const writes = await this.updateWrites(false);
22608
22670
  for (const key of deferredExpressionProps) {
22609
22671
  const value = this[key];
22610
22672
  if (value !== undefined && value !== null) {
22611
- await this.setProperty(key, value, batchId);
22673
+ writes.push(...await this.planProperty(key, value));
22612
22674
  }
22613
22675
  }
22676
+ await this.sendWrites(writes, batchId);
22614
22677
  // If we got a batchId passed in, we let the caller decide when to commit.
22615
22678
  // We can't call getData() since the instance won't exist in the perspective
22616
22679
  // until the batch is committed.
@@ -22672,6 +22735,11 @@ class Ad4mModel {
22672
22735
  return cleanCopy;
22673
22736
  }
22674
22737
  async innerUpdate(setProperties = true, batchId) {
22738
+ await this.sendWrites(await this.updateWrites(setProperties), batchId);
22739
+ }
22740
+ /** The writes of the changed fields, in field order (see {@link sendWrites}). */
22741
+ async updateWrites(setProperties = true) {
22742
+ const writes = [];
22675
22743
  const ctor = this.constructor;
22676
22744
  // Determine which fields actually changed (skip unchanged when snapshot exists)
22677
22745
  const dirty = this._snapshot ? new Set(this.changedFields()) : null;
@@ -22708,18 +22776,21 @@ class Ad4mModel {
22708
22776
  }
22709
22777
  if (value !== undefined && value !== null) {
22710
22778
  if (value?.action) {
22779
+ const envelopePredicate = this.getRelationOptions(key)?.predicate;
22780
+ if (envelopePredicate && value.action !== "remover")
22781
+ this._relationsWritten.add(envelopePredicate);
22711
22782
  switch (value.action) {
22712
22783
  case "setter":
22713
- await this.setRelationValues(key, value.value, batchId);
22784
+ writes.push(...this.planRelation(key, 'setter', value.value));
22714
22785
  break;
22715
22786
  case "adder":
22716
- await this.addRelationValue(key, value.value, batchId);
22787
+ writes.push(...this.planRelation(key, 'adder', value.value));
22717
22788
  break;
22718
22789
  case "remover":
22719
- await this.removeRelationValue(key, value.value, batchId);
22790
+ writes.push(...this.planRelation(key, 'remover', value.value));
22720
22791
  break;
22721
22792
  default:
22722
- await this.setRelationValues(key, value.value, batchId);
22793
+ writes.push(...this.planRelation(key, 'setter', value.value));
22723
22794
  break;
22724
22795
  }
22725
22796
  }
@@ -22727,9 +22798,11 @@ class Ad4mModel {
22727
22798
  // Handle all arrays as relations, including empty ones (which clears the relation).
22728
22799
  // A record being created under an id minted here has no links to
22729
22800
  // clear, so an empty relation there costs a round trip and writes nothing.
22730
- if (value.length === 0 && !this._snapshot && this._idMinted && !this._relationsWritten.has(this.getRelationOptions(key)?.predicate ?? key))
22801
+ const predicate = this.getRelationOptions(key)?.predicate ?? key;
22802
+ if (value.length === 0 && !this._snapshot && this._idMinted && !this._relationsWritten.has(predicate))
22731
22803
  continue;
22732
- await this.setRelationValues(key, value, batchId);
22804
+ this._relationsWritten.add(predicate);
22805
+ writes.push(...this.planRelation(key, 'setter', value));
22733
22806
  }
22734
22807
  else if (value !== undefined && value !== null && value !== "") {
22735
22808
  // A scalar handed to a relation field is a single-member relation.
@@ -22758,7 +22831,8 @@ class Ad4mModel {
22758
22831
  // both paths at once.
22759
22832
  const relationMeta = this.getRelationOptions(key);
22760
22833
  if (relationMeta) {
22761
- await this.setRelationValues(key, [value], batchId);
22834
+ this._relationsWritten.add(relationMeta.predicate);
22835
+ writes.push(...this.planRelation(key, 'setter', [value]));
22762
22836
  continue;
22763
22837
  }
22764
22838
  if (setProperties) {
@@ -22767,11 +22841,12 @@ class Ad4mModel {
22767
22841
  if (propMeta?.flag) {
22768
22842
  continue;
22769
22843
  }
22770
- await this.setProperty(key, value, batchId);
22844
+ writes.push(...await this.planProperty(key, value));
22771
22845
  }
22772
22846
  }
22773
22847
  }
22774
22848
  }
22849
+ return writes;
22775
22850
  }
22776
22851
  /**
22777
22852
  * Evaluate SPARQL getters for a batch of instances on demand.
@@ -23918,7 +23993,7 @@ exports.FlowTransitionProposal = class FlowTransitionProposal extends Ad4mModel
23918
23993
  this.acceptedBy = [];
23919
23994
  // Whether this proposal settled an edge is not on the record: the
23920
23995
  // executor keeps that per agent, outside the graph (#1424). Ask
23921
- // `PerspectiveProxy.flowFired(instance)` for the proposals your replica
23996
+ // `PerspectiveProxy.flowFired(instances)` for the proposals your replica
23922
23997
  // recorded as fired, or listen with `onFlowStateChanged`.
23923
23998
  // "When was this proposal written?" is answered by `Ad4mModel`'s built-in
23924
23999
  // `createdAt`, synthesized on hydration from the earliest link timestamp
@@ -26318,7 +26393,6 @@ exports.buildSHACL = buildSHACL;
26318
26393
  exports.buildSPARQLQuery = buildSPARQLQuery;
26319
26394
  exports.buildWhereCondition = buildWhereCondition;
26320
26395
  exports.capSentence = capSentence;
26321
- exports.clearQueryCache = clearQueryCache;
26322
26396
  exports.coalesce = coalesce;
26323
26397
  exports.compileWhereClause = compileWhereClause;
26324
26398
  exports.concat = concat;
@@ -26336,7 +26410,6 @@ exports.focus = focus;
26336
26410
  exports.formatList = formatList;
26337
26411
  exports.formatQueryValue = formatQueryValue;
26338
26412
  exports.formatSPARQLValue = formatSPARQLValue;
26339
- exports.getCachedResult = getCachedResult;
26340
26413
  exports.getDefaultValueForType = getDefaultValueForType;
26341
26414
  exports.getMemoizedSHACL = getMemoizedSHACL;
26342
26415
  exports.getPropertiesMetadata = getPropertiesMetadata;
@@ -26346,7 +26419,6 @@ exports.hasJsOnlyWhereFilters = hasJsOnlyWhereFilters;
26346
26419
  exports.hintFor = hintFor;
26347
26420
  exports.holdsAWholeWordTerm = holdsAWholeWordTerm;
26348
26421
  exports.ifExpr = ifExpr;
26349
- exports.invalidatePerspectiveCache = invalidatePerspectiveCache;
26350
26422
  exports.isArrayType = isArrayType;
26351
26423
  exports.isBot = isBot;
26352
26424
  exports.isContainedScope = isContainedScope;
@@ -26378,11 +26450,10 @@ exports.parseLitBoolean = parseLitBoolean;
26378
26450
  exports.parseLitNumber = parseLitNumber;
26379
26451
  exports.parseSparqlCount = parseSparqlCount;
26380
26452
  exports.path = path;
26381
- exports.queryCacheSize = queryCacheSize;
26382
26453
  exports.reopenDelay = reopenDelay;
26383
26454
  exports.requireSingleParent = requireSingleParent;
26455
+ exports.requireTotalCount = requireTotalCount;
26384
26456
  exports.resolveParentPredicate = resolveParentPredicate;
26385
- exports.setCachedResult = setCachedResult;
26386
26457
  exports.setPropertyRegistryEntry = setPropertyRegistryEntry;
26387
26458
  exports.setRelationRegistryEntry = setRelationRegistryEntry;
26388
26459
  exports.typeDefsString = typeDefsString;