@coasys/ad4m 0.13.1-staging.13 → 0.13.1-staging.15

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 (75) hide show
  1. package/lib/index.cjs +571 -480
  2. package/lib/index.js +571 -476
  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/ExpressionLookupError.d.ts +7 -0
  10. package/lib/src/generated/api/ExpressionLookupError.js +2 -0
  11. package/lib/src/generated/api/ExpressionManyEntry.d.ts +6 -0
  12. package/lib/src/generated/api/ExpressionManyEntry.js +1 -0
  13. package/lib/src/generated/api/FlowFiredEntry.d.ts +11 -0
  14. package/lib/src/generated/api/FlowFiredEntry.js +2 -0
  15. package/lib/src/generated/api/PerspectiveFlowFiredParams.d.ts +3 -3
  16. package/lib/src/generated/api/RpcMethods.d.ts +4 -2
  17. package/lib/src/model/Ad4mModel.d.ts +26 -2
  18. package/lib/src/model/Ad4mModel.js +127 -83
  19. package/lib/src/model/ModelQueryBuilder.d.ts +3 -0
  20. package/lib/src/model/ModelQueryBuilder.js +42 -14
  21. package/lib/src/model/index.d.ts +0 -1
  22. package/lib/src/model/index.js +0 -1
  23. package/lib/src/model/query-common.d.ts +8 -0
  24. package/lib/src/model/query-common.js +12 -0
  25. package/lib/src/model/shacl-gen.js +2 -0
  26. package/lib/src/model/types.d.ts +12 -3
  27. package/lib/src/neighbourhood/SfuManager.d.ts +8 -1
  28. package/lib/src/neighbourhood/SfuManager.js +9 -2
  29. package/lib/src/perspectives/FlowModels.js +1 -1
  30. package/lib/src/perspectives/LiveQuery.d.ts +1 -1
  31. package/lib/src/perspectives/PerspectiveClient.d.ts +17 -6
  32. package/lib/src/perspectives/PerspectiveClient.js +83 -44
  33. package/lib/src/perspectives/PerspectiveProxy.d.ts +19 -10
  34. package/lib/src/perspectives/PerspectiveProxy.js +31 -69
  35. package/lib/src/shacl/SHACLShape.d.ts +4 -0
  36. package/lib/src/shacl/SHACLShape.js +10 -0
  37. package/package.json +2 -2
  38. package/src/Ad4mClient.test.ts +17 -6
  39. package/src/agent/AgentClient.ts +46 -74
  40. package/src/cache/KeyedCache.test.ts +162 -0
  41. package/src/cache/KeyedCache.ts +179 -0
  42. package/src/cache/cache.test.ts +294 -71
  43. package/src/expression/ExpressionClient.ts +46 -131
  44. package/src/generated/api/ExpressionLookupError.ts +6 -0
  45. package/src/generated/api/ExpressionManyEntry.ts +8 -0
  46. package/src/generated/api/FlowFiredEntry.ts +11 -0
  47. package/src/generated/api/PerspectiveFlowFiredParams.ts +3 -3
  48. package/src/generated/api/RpcMethods.ts +4 -2
  49. package/src/model/Ad4mModel.test.ts +237 -43
  50. package/src/model/Ad4mModel.ts +134 -99
  51. package/src/model/ModelQueryBuilder.ts +41 -15
  52. package/src/model/count-result-type.test.ts +72 -0
  53. package/src/model/index.ts +0 -1
  54. package/src/model/query-common.ts +13 -0
  55. package/src/model/relation-filtering.test.ts +3 -5
  56. package/src/model/shacl-gen.ts +1 -0
  57. package/src/model/shacl-roundtrip.test.ts +28 -0
  58. package/src/model/types.ts +9 -3
  59. package/src/model/write-round-trips.test.ts +30 -6
  60. package/src/neighbourhood/SfuManager.test.ts +57 -5
  61. package/src/neighbourhood/SfuManager.ts +10 -2
  62. package/src/perspectives/FlowModels.ts +1 -1
  63. package/src/perspectives/LiveQuery.ts +1 -1
  64. package/src/perspectives/PerspectiveClient.test.ts +287 -0
  65. package/src/perspectives/PerspectiveClient.ts +101 -66
  66. package/src/perspectives/PerspectiveProxy.test.ts +6 -14
  67. package/src/perspectives/PerspectiveProxy.ts +33 -67
  68. package/src/perspectives/TextContent.test.ts +0 -16
  69. package/src/perspectives/shacl-rpc.test.ts +1 -1
  70. package/src/shacl/SHACLShape.test.ts +21 -0
  71. package/src/shacl/SHACLShape.ts +16 -0
  72. package/lib/src/model/query-cache.d.ts +0 -30
  73. package/lib/src/model/query-cache.js +0 -66
  74. package/src/model/query-cache.test.ts +0 -54
  75. 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");
@@ -3027,8 +3148,15 @@ class SfuManager {
3027
3148
  SfuManager.MAX_RECONNECTS = 3;
3028
3149
  /** How long one rebuild keeps retrying a join the executor cannot take yet. */
3029
3150
  SfuManager.REJOIN_WINDOW_MS = 120000;
3030
- /** How long an ICE restart has to bring the connection back before a rebuild. */
3031
- SfuManager.RESTART_TIMEOUT_MS = 5000;
3151
+ /** The executor's wait before the first resend of an unanswered offer.
3152
+ * `OFFER_RETRY_BASE` in `rust-executor/src/sfu/server.rs`. */
3153
+ SfuManager.OFFER_RESEND_BASE_MS = 10000;
3154
+ /** How long ICE has to come back after that resend arrives. */
3155
+ SfuManager.RESTART_AFTER_RESEND_MS = 5000;
3156
+ /** How long an ICE restart has to bring the connection back before a rebuild.
3157
+ * The window stays open through the first resend, then the previous 5 s
3158
+ * for ICE. A restart that connects clears the timer at once. */
3159
+ SfuManager.RESTART_TIMEOUT_MS = SfuManager.OFFER_RESEND_BASE_MS + SfuManager.RESTART_AFTER_RESEND_MS;
3032
3160
  /** How long the roster may leave this session out before the call is rebuilt. */
3033
3161
  SfuManager.UNLISTED_GRACE_MS = 3000;
3034
3162
 
@@ -6021,6 +6149,13 @@ class SHACLShape {
6021
6149
  target: `literal:string:${prop.relationKind}`
6022
6150
  });
6023
6151
  }
6152
+ if (prop.polymorphic) {
6153
+ links.push({
6154
+ source: propShapeId,
6155
+ predicate: "ad4m://polymorphic",
6156
+ target: `literal:${prop.polymorphic}`
6157
+ });
6158
+ }
6024
6159
  if (prop.targetClassName) {
6025
6160
  links.push({
6026
6161
  source: propShapeId,
@@ -6160,6 +6295,7 @@ class SHACLShape {
6160
6295
  in: json(id, "sh://in"),
6161
6296
  relationKind: ['hasMany', 'hasOne', 'belongsToOne', 'belongsToMany'].includes(relationKind)
6162
6297
  ? relationKind : undefined,
6298
+ polymorphic: bool(id, "ad4m://polymorphic"),
6163
6299
  targetClassName: str(id, "ad4m://targetClassName"),
6164
6300
  whereFilter: json(id, "ad4m://whereFilter"),
6165
6301
  wherePredicates: json(id, "ad4m://wherePredicates"),
@@ -6208,6 +6344,7 @@ class SHACLShape {
6208
6344
  class: p.class,
6209
6345
  in: p.in,
6210
6346
  relation_kind: p.relationKind,
6347
+ polymorphic: p.polymorphic,
6211
6348
  collection: p.collection ?? (isCollection(p) || undefined),
6212
6349
  target_class_name: p.targetClassName,
6213
6350
  where_filter: p.whereFilter,
@@ -6262,6 +6399,7 @@ class SHACLShape {
6262
6399
  class: p.class,
6263
6400
  in: p.in,
6264
6401
  relationKind: p.relation_kind,
6402
+ polymorphic: p.polymorphic,
6265
6403
  collection: p.collection,
6266
6404
  targetClassName: p.target_class_name,
6267
6405
  whereFilter: p.where_filter,
@@ -6587,6 +6725,8 @@ isAbstract) {
6587
6725
  // Encode relation kind so the executor can derive direction and
6588
6726
  // scalar-vs-collection rendering without consulting the JS class.
6589
6727
  relShape.relationKind = relMeta.kind;
6728
+ if (relMeta.polymorphic)
6729
+ relShape.polymorphic = true;
6590
6730
  // Scalar relations cap at 1.
6591
6731
  if (relMeta.kind === 'hasOne' || relMeta.kind === 'belongsToOne') {
6592
6732
  relShape.maxCount = 1;
@@ -7647,73 +7787,6 @@ function BelongsToMany(first, second) {
7647
7787
  };
7648
7788
  }
7649
7789
 
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
7790
  var __classPrivateFieldSet$8 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
7718
7791
  if (kind === "m") throw new TypeError("Private method is not writable");
7719
7792
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
@@ -9089,9 +9162,7 @@ class PerspectiveProxy {
9089
9162
  * @param batchId - Optional batch ID to group this operation with others
9090
9163
  */
9091
9164
  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;
9165
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").executeCommands(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId);
9095
9166
  }
9096
9167
  /**
9097
9168
  * Retrieves links from the perspective that match the given query.
@@ -9319,12 +9390,15 @@ class PerspectiveProxy {
9319
9390
  return await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").flowStates(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, instances);
9320
9391
  }
9321
9392
  /**
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.
9393
+ * For each of `instances`, in order, the proposals whose votes settled an
9394
+ * edge, as this agent's executor recorded them — the flow's history,
9395
+ * sorted by URI (`fired: []` when none). One call covers up to 200
9396
+ * instances (the executor refuses more with a 400); split a longer list
9397
+ * into batches of 200.
9324
9398
  * Replaces the `resolvedAs` property proposals used to carry.
9325
9399
  */
9326
- async flowFired(instance) {
9327
- return await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").flowFired(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, instance);
9400
+ async flowFired(instances) {
9401
+ return await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").flowFired(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, instances);
9328
9402
  }
9329
9403
  /**
9330
9404
  * Called whenever a flow instance on this perspective changes state on
@@ -9388,20 +9462,18 @@ class PerspectiveProxy {
9388
9462
  * keep its blocking thread busy until it completes; what's saved is the
9389
9463
  * serialise + network + client-deserialise tax on the result. Aborted
9390
9464
  * 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.
9465
+ * `fetch()` for handling. A call with `options` makes its own RPC.
9466
+ *
9467
+ * **Sharing:** concurrent identical calls without `options` share one RPC;
9468
+ * each caller gets its own result object. Nothing is cached once the
9469
+ * call settles: use a live query for repeated reads of the same data.
9393
9470
  *
9394
9471
  * @param query - SPARQL query string (read-only operations only)
9395
9472
  * @param options - Optional call options (e.g. AbortSignal for cancellation)
9396
9473
  * @returns Query results as parsed JSON
9397
9474
  */
9398
9475
  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;
9476
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").querySparql(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, query, options);
9405
9477
  }
9406
9478
  /**
9407
9479
  * Execute a model query — the executor-side replacement for SPARQL query building + JS hydration.
@@ -9414,7 +9486,7 @@ class PerspectiveProxy {
9414
9486
  * query over their union, whose rows carry `__subjectClass` and
9415
9487
  * `__subjectClasses` (#1238)
9416
9488
  * @param queryJson - Structured query as JSON string
9417
- * @returns Object with `instances` array and `totalCount`
9489
+ * @returns Object with `instances` array, and `totalCount` when the query sets `count: true`
9418
9490
  */
9419
9491
  async modelQuery(className, queryJson, options) {
9420
9492
  return await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, options);
@@ -9508,9 +9580,7 @@ class PerspectiveProxy {
9508
9580
  * ```
9509
9581
  */
9510
9582
  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;
9583
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").addLink(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
9514
9584
  }
9515
9585
  /**
9516
9586
  * Adds multiple links to the perspective in a single operation.
@@ -9522,9 +9592,7 @@ class PerspectiveProxy {
9522
9592
  * @returns Array of created LinkExpressions
9523
9593
  */
9524
9594
  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;
9595
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").addLinks(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, links, status, batchId);
9528
9596
  }
9529
9597
  /**
9530
9598
  * Removes multiple links from the perspective.
@@ -9534,9 +9602,7 @@ class PerspectiveProxy {
9534
9602
  * @returns Array of removed LinkExpressions
9535
9603
  */
9536
9604
  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;
9605
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").removeLinks(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, links, batchId);
9540
9606
  }
9541
9607
  /**
9542
9608
  * Applies a set of link mutations (adds and removes) in a single operation.
@@ -9547,9 +9613,7 @@ class PerspectiveProxy {
9547
9613
  * @returns Object containing results of the mutations
9548
9614
  */
9549
9615
  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;
9616
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").linkMutations(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, mutations, status);
9553
9617
  }
9554
9618
  /**
9555
9619
  * Adds a pre-signed LinkExpression to the perspective.
@@ -9576,9 +9640,7 @@ class PerspectiveProxy {
9576
9640
  * @param batchId - Optional batch ID to group this operation with others
9577
9641
  */
9578
9642
  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;
9643
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").updateLink(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, oldLink, newLink, batchId);
9582
9644
  }
9583
9645
  /**
9584
9646
  * Removes a link from the perspective.
@@ -9624,9 +9686,7 @@ class PerspectiveProxy {
9624
9686
  else {
9625
9687
  resolvedLink = link;
9626
9688
  }
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;
9689
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, resolvedLink, batchId);
9630
9690
  }
9631
9691
  /** Creates a new batch for grouping operations */
9632
9692
  async createBatch() {
@@ -9634,9 +9694,7 @@ class PerspectiveProxy {
9634
9694
  }
9635
9695
  /** Commits a batch of operations */
9636
9696
  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;
9697
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").commitBatch(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, batchId);
9640
9698
  }
9641
9699
  /**
9642
9700
  * Drops an open batch without committing it — the recovery for a failed batched call:
@@ -10004,13 +10062,13 @@ class PerspectiveProxy {
10004
10062
  return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").getShaclTargetClass(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, name);
10005
10063
  }
10006
10064
  /**
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.
10065
+ * Get the SHACL shapes stored in this Perspective in one RPC call: all of
10066
+ * them, or only those named in `names` (unknown names are left out).
10009
10067
  * A shape that fails to decode is skipped with a `console.warn`, so it
10010
10068
  * does not hide the others.
10011
10069
  */
10012
- async getAllShacl() {
10013
- const entries = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").getAllShacl(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10070
+ async getAllShacl(options) {
10071
+ const entries = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").getAllShacl(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, options?.names);
10014
10072
  const shapes = [];
10015
10073
  for (const { name, shapeUri, links } of entries) {
10016
10074
  try {
@@ -10251,7 +10309,6 @@ class PerspectiveProxy {
10251
10309
  * record that the abstract class reads, under its own name. */
10252
10310
  async updateSubject(className, exprAddr, values, batchId) {
10253
10311
  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
10312
  }
10256
10313
  /**
10257
10314
  * Creates an instance of a subject class, validated by the executor against the class's
@@ -10270,42 +10327,23 @@ class PerspectiveProxy {
10270
10327
  * const { baseUri } = await perspective.instanceCreate({ className: "Task", properties: { title: "Write" } });
10271
10328
  */
10272
10329
  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;
10330
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceCreate(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10276
10331
  }
10277
10332
  /** Sets single-valued properties of an instance, validated; the others stay. See {@link instanceCreate}. */
10278
10333
  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;
10334
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceUpdate(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10282
10335
  }
10283
10336
  /** Removes an instance and every link to and from it. See {@link instanceCreate}. */
10284
10337
  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
- }
10338
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceRemove(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10293
10339
  }
10294
10340
  /** Adds an item to a collection of an instance, validated. See {@link instanceCreate}. */
10295
10341
  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;
10342
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceAddToCollection(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10299
10343
  }
10300
10344
  /** Removes an item from a collection of an instance. See {@link instanceCreate}. */
10301
10345
  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
- }
10346
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceRemoveFromCollection(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10309
10347
  }
10310
10348
  async getSubjectData(subjectClass, exprAddr) {
10311
10349
  if (typeof subjectClass === "string") {
@@ -10369,7 +10407,6 @@ class PerspectiveProxy {
10369
10407
  const ctor = subjectClass?.constructor;
10370
10408
  if (typeof subjectClass === "object" && ctor && Object.prototype.hasOwnProperty.call(ctor, 'builtinUri')) {
10371
10409
  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
10410
  return;
10374
10411
  }
10375
10412
  let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);
@@ -10379,7 +10416,6 @@ class PerspectiveProxy {
10379
10416
  const markers = await this.get(new LinkQuery({ predicate: "ad4m://abstract" }));
10380
10417
  if (markers.some((link) => shapePattern.test(link.data.source))) {
10381
10418
  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
10419
  return;
10384
10420
  }
10385
10421
  // Get destructor actions from SHACL links (Prolog-free)
@@ -10948,7 +10984,7 @@ var __classPrivateFieldGet$6 = (undefined && undefined.__classPrivateFieldGet) |
10948
10984
  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
10985
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
10950
10986
  };
10951
- var _PerspectiveClient_instances, _PerspectiveClient_apiClient, _PerspectiveClient_expressionClient, _PerspectiveClient_neighbourhoodClient, _PerspectiveClient_aiClient, _PerspectiveClient_released;
10987
+ var _PerspectiveClient_instances, _PerspectiveClient_apiClient, _PerspectiveClient_expressionClient, _PerspectiveClient_neighbourhoodClient, _PerspectiveClient_aiClient, _PerspectiveClient_sparqlInFlight, _PerspectiveClient_writeGeneration, _PerspectiveClient_wrote, _PerspectiveClient_released;
10952
10988
  /** The wire form of a model query's classes: `class_name` for one, `class_names` for a union. */
10953
10989
  function classParams(className) {
10954
10990
  return Array.isArray(className) ? { class_names: className } : { class_name: className };
@@ -10970,6 +11006,11 @@ class PerspectiveClient {
10970
11006
  _PerspectiveClient_expressionClient.set(this, void 0);
10971
11007
  _PerspectiveClient_neighbourhoodClient.set(this, void 0);
10972
11008
  _PerspectiveClient_aiClient.set(this, void 0);
11009
+ _PerspectiveClient_sparqlInFlight.set(this, new Map()
11010
+ /** Per perspective, how many writes through this client have settled; part of the in-flight key. */
11011
+ );
11012
+ /** Per perspective, how many writes through this client have settled; part of the in-flight key. */
11013
+ _PerspectiveClient_writeGeneration.set(this, new Map());
10973
11014
  __classPrivateFieldSet$6(this, _PerspectiveClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), "f");
10974
11015
  }
10975
11016
  setExpressionClient(client) {
@@ -11029,9 +11070,24 @@ class PerspectiveClient {
11029
11070
  const result = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.queryProlog', { uuid, query }, options);
11030
11071
  return JSON.parse(result);
11031
11072
  }
11073
+ /**
11074
+ * Concurrent identical calls (same perspective and query, no `options`)
11075
+ * share one RPC. Each caller parses its own copy of the reply, and a call
11076
+ * made after the shared one settled makes a new RPC. So does a call made
11077
+ * after a write through this client settled: the shared RPC may have been
11078
+ * answered before the write (see `#wrote`).
11079
+ */
11032
11080
  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);
11081
+ if (options)
11082
+ return JSON.parse(await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.querySparql', { uuid, engine: 'sparql', query }, options));
11083
+ const key = `${uuid}\n${__classPrivateFieldGet$6(this, _PerspectiveClient_writeGeneration, "f").get(uuid) ?? 0}\n${query}`;
11084
+ let reply = __classPrivateFieldGet$6(this, _PerspectiveClient_sparqlInFlight, "f").get(key);
11085
+ if (!reply) {
11086
+ reply = __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.querySparql', { uuid, engine: 'sparql', query })
11087
+ .finally(() => __classPrivateFieldGet$6(this, _PerspectiveClient_sparqlInFlight, "f").delete(key));
11088
+ __classPrivateFieldGet$6(this, _PerspectiveClient_sparqlInFlight, "f").set(key, reply);
11089
+ }
11090
+ return JSON.parse(await reply);
11035
11091
  }
11036
11092
  /** Open a live SPARQL query. Updates arrive through {@link onQueryUpdate}. */
11037
11093
  /** `options.signal` cancels the call, and the executor stops computing the first result. */
@@ -11088,19 +11144,19 @@ class PerspectiveClient {
11088
11144
  return { perspectiveRemove: result };
11089
11145
  }
11090
11146
  async addLink(uuid, link, status = 'shared', batchId) {
11091
- const added = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.addLink', { uuid, link, status, batchId });
11147
+ 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
11148
  return LinkExpression.fromWire(added);
11093
11149
  }
11094
11150
  async addLinks(uuid, links, status = 'shared', batchId) {
11095
- const added = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.addLinks', { uuid, links, status, batchId });
11151
+ 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
11152
  return added.map(LinkExpression.fromWire);
11097
11153
  }
11098
11154
  async removeLinks(uuid, links, batchId) {
11099
- const removed = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.removeLinks', { uuid, links: links.map(linkExpressionInputToWire), batchId });
11155
+ 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
11156
  return removed.map(LinkExpression.fromWire);
11101
11157
  }
11102
11158
  async linkMutations(uuid, mutations, status) {
11103
- const diff = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.linkMutations', { uuid, mutations: linkMutationsToWire(mutations), status });
11159
+ 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
11160
  return LinkExpressionMutations.fromWire(diff);
11105
11161
  }
11106
11162
  /**
@@ -11120,11 +11176,11 @@ class PerspectiveClient {
11120
11176
  * are NOT re-parented — same rule as the watcher).
11121
11177
  */
11122
11178
  async runInterpretation(uuid, transcript, basePrefix, classes, existingScope, mintScope, observe, options) {
11123
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretation', {
11179
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretation', {
11124
11180
  uuid, transcript, basePrefix, classes, existingScope, mintScope,
11125
11181
  observationId: observe?.observationId,
11126
11182
  emitDebugEvents: observe?.emitDebugEvents,
11127
- }, options);
11183
+ }, options));
11128
11184
  }
11129
11185
  /**
11130
11186
  * Tool-calling counterpart to {@link runInterpretation}. The LLM sees a
@@ -11147,7 +11203,7 @@ class PerspectiveClient {
11147
11203
  // `emitDebugEvents` is a dead-letter without an observationId
11148
11204
  // (nothing to key against); the server gates on both.
11149
11205
  observationId, emitDebugEvents, options) {
11150
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretationWithHarness', {
11206
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretationWithHarness', {
11151
11207
  uuid,
11152
11208
  transcript,
11153
11209
  basePrefix,
@@ -11157,7 +11213,7 @@ class PerspectiveClient {
11157
11213
  existingScope,
11158
11214
  observationId,
11159
11215
  emitDebugEvents,
11160
- }, options);
11216
+ }, options));
11161
11217
  }
11162
11218
  /**
11163
11219
  * A conversation with a model in this perspective, using the executor's own tools: the tools
@@ -11170,7 +11226,9 @@ class PerspectiveClient {
11170
11226
  * calls before it answers.
11171
11227
  */
11172
11228
  async runAgent(uuid, messages, settings, options) {
11173
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.runAgent', { uuid, messages, ...settings }, options);
11229
+ const reply = __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.runAgent', { uuid, messages, ...settings }, options);
11230
+ // Without write tools the session only reads.
11231
+ return settings?.writeTools?.length ? __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, reply) : reply;
11174
11232
  }
11175
11233
  /**
11176
11234
  * Register a neighbourhood auto-processor on this perspective. The executor's
@@ -11181,11 +11239,11 @@ class PerspectiveClient {
11181
11239
  * Returns the processor id.
11182
11240
  */
11183
11241
  async addAutoProcessor(uuid, config) {
11184
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.addAutoProcessor', { ...config, uuid });
11242
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.addAutoProcessor', { ...config, uuid }));
11185
11243
  }
11186
11244
  /** Delete an auto-processor's config. `false` when there was none to delete. */
11187
11245
  async removeAutoProcessor(uuid, processorId) {
11188
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.removeAutoProcessor', { uuid, processorId });
11246
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.removeAutoProcessor', { uuid, processorId }));
11189
11247
  }
11190
11248
  /** Pending interpretation overlays (LLM suggestions awaiting human accept/reject). */
11191
11249
  async interpretationOverlays(uuid) {
@@ -11197,18 +11255,18 @@ class PerspectiveClient {
11197
11255
  /** Accept an overlay's suggestion(s): the LLM value becomes the real value and
11198
11256
  * the overlay is deleted. Omit `property` to accept the whole base. */
11199
11257
  async acceptInterpretation(uuid, base, property) {
11200
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.acceptInterpretation', { uuid, base, property });
11258
+ 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
11259
  }
11202
11260
  /** Reject an overlay's suggestion(s). Omit `property` to reject the whole base
11203
11261
  * (a rejected `create` deletes the suggested instance). */
11204
11262
  async rejectInterpretation(uuid, base, property) {
11205
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectInterpretation', { uuid, base, property });
11263
+ 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
11264
  }
11207
11265
  async proposeFlowTransition(uuid, instanceUri, toState, rationale, outputs) {
11208
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.proposeFlowTransition', { uuid, instanceUri, toState, rationale, outputs });
11266
+ 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
11267
  }
11210
11268
  async acceptFlowProposal(uuid, proposalUri) {
11211
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.acceptFlowProposal', { uuid, proposalUri });
11269
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.acceptFlowProposal', { uuid, proposalUri }));
11212
11270
  }
11213
11271
  /**
11214
11272
  * Withdraw this agent's own links from a proposal. Resolves to how many
@@ -11216,7 +11274,7 @@ class PerspectiveClient {
11216
11274
  * proposal this agent opened.
11217
11275
  */
11218
11276
  async rejectFlowProposal(uuid, proposalUri) {
11219
- const result = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectFlowProposal', { uuid, proposalUri });
11277
+ 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
11278
  return result.retractedLinks;
11221
11279
  }
11222
11280
  /** Re-decide a flow receipt under this perspective's own flow catalogue. */
@@ -11233,49 +11291,51 @@ class PerspectiveClient {
11233
11291
  async flowStates(uuid, instances) {
11234
11292
  return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.flowStates', { uuid, instances });
11235
11293
  }
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 });
11294
+ /** For each of `instances`, in order, the proposals the calling agent's
11295
+ * replica recorded as fired, sorted. One call covers up to 200
11296
+ * instances (more is refused with a 400); split a longer list into
11297
+ * batches of 200. */
11298
+ async flowFired(uuid, instances) {
11299
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.flowFired', { uuid, instances });
11240
11300
  }
11241
11301
  /** Mint and store the receipt for a completed flow run. Fails while the
11242
11302
  * run has not settled into a terminal state, and when an output's
11243
11303
  * content no longer matches what the quorum committed to. */
11244
11304
  async mintFlowReceipt(uuid, instanceUri) {
11245
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.mintFlowReceipt', { uuid, instanceUri });
11305
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.mintFlowReceipt', { uuid, instanceUri }));
11246
11306
  }
11247
11307
  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 });
11308
+ 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
11309
  return LinkExpression.fromWire(added);
11250
11310
  }
11251
11311
  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 });
11312
+ 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
11313
  return LinkExpression.fromWire(updated);
11254
11314
  }
11255
11315
  async removeLink(uuid, link, batchId) {
11256
11316
  const { status, ...wire } = linkExpressionInputToWire(link);
11257
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.removeLink', { uuid, link: wire, batchId });
11317
+ 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
11318
  }
11259
11319
  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 });
11320
+ 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
11321
  return typeof result === 'boolean' ? result : result.every(Boolean);
11262
11322
  }
11263
11323
  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 || "" })) });
11324
+ 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
11325
  return typeof result === 'boolean' ? [result] : result;
11266
11326
  }
11267
11327
  async executeCommands(uuid, commands, expression, parameters, batchId) {
11268
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.executeCommands', { uuid, commands, expression, parameters, batchId });
11328
+ 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
11329
  }
11270
11330
  async createSubject(uuid, subjectClass, expressionAddress, initialValues, batchId) {
11271
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.createSubject', { uuid, subjectClass, expressionAddress, initialValues, batchId });
11331
+ 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
11332
  }
11273
11333
  /** Through an abstract class (#1435), the executor writes to the record's own classes. */
11274
11334
  async updateSubject(uuid, subjectClass, expressionAddress, values, batchId) {
11275
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.updateSubject', { uuid, subjectClass, expressionAddress, values, batchId });
11335
+ 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
11336
  }
11277
11337
  async removeSubject(uuid, subjectClass, expressionAddress, batchId) {
11278
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.removeSubject', { uuid, subjectClass, expressionAddress, batchId });
11338
+ 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
11339
  }
11280
11340
  /**
11281
11341
  * Validated writes (`perspective.instance*`): the executor checks each against the class's
@@ -11295,23 +11355,23 @@ class PerspectiveClient {
11295
11355
  * it to keep the calls that succeeded.
11296
11356
  */
11297
11357
  async instanceCreate(uuid, body) {
11298
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceCreate', { uuid, ...body });
11358
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceCreate', { uuid, ...body }));
11299
11359
  }
11300
11360
  /** Sets the given single-valued properties; the others stay. See {@link instanceCreate}. */
11301
11361
  async instanceUpdate(uuid, body) {
11302
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceUpdate', { uuid, ...body });
11362
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceUpdate', { uuid, ...body }));
11303
11363
  }
11304
11364
  /** Removes the instance and every link to and from it. See {@link instanceCreate}. */
11305
11365
  async instanceRemove(uuid, body) {
11306
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceRemove', { uuid, ...body });
11366
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceRemove', { uuid, ...body }));
11307
11367
  }
11308
11368
  /** Adds an item to a collection (a no-op when it is a member). See {@link instanceCreate}. */
11309
11369
  async instanceAddToCollection(uuid, body) {
11310
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceAddToCollection', { uuid, ...body });
11370
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceAddToCollection', { uuid, ...body }));
11311
11371
  }
11312
11372
  /** Removes an item's membership link from a collection. See {@link instanceCreate}. */
11313
11373
  async instanceRemoveFromCollection(uuid, body) {
11314
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceRemoveFromCollection', { uuid, ...body });
11374
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceRemoveFromCollection', { uuid, ...body }));
11315
11375
  }
11316
11376
  async getSubjectData(uuid, subjectClass, expressionAddress) {
11317
11377
  return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.getSubjectData', { uuid, subjectClass, expressionAddress });
@@ -11347,11 +11407,12 @@ class PerspectiveClient {
11347
11407
  return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.getShacl', { uuid, name });
11348
11408
  }
11349
11409
  /**
11350
- * Retrieve all SHACL shapes in one call. Returns an array of
11351
- * `{name, shapeUri, links}` — one entry per shape (one RPC call).
11410
+ * Retrieve SHACL shapes in one call: every shape, or only those in
11411
+ * `names` (unknown names are left out). Returns `{name, shapeUri, links}`
11412
+ * per shape.
11352
11413
  */
11353
- async getAllShacl(uuid) {
11354
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.getAllShacl', { uuid });
11414
+ async getAllShacl(uuid, names) {
11415
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.getAllShacl', { uuid, names });
11355
11416
  }
11356
11417
  // ExpressionClient functions, needed for Subjects:
11357
11418
  async getExpression(expressionURI) {
@@ -11371,7 +11432,7 @@ class PerspectiveClient {
11371
11432
  return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.createBatch', { uuid });
11372
11433
  }
11373
11434
  async commitBatch(uuid, batchId) {
11374
- const diff = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.commitBatch', { uuid, batchId });
11435
+ 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
11436
  return LinkExpressionMutations.fromWire(diff);
11376
11437
  }
11377
11438
  /**
@@ -11389,7 +11450,21 @@ class PerspectiveClient {
11389
11450
  return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").onReconnect(callback);
11390
11451
  }
11391
11452
  }
11392
- _PerspectiveClient_apiClient = new WeakMap(), _PerspectiveClient_expressionClient = new WeakMap(), _PerspectiveClient_neighbourhoodClient = new WeakMap(), _PerspectiveClient_aiClient = new WeakMap(), _PerspectiveClient_instances = new WeakSet(), _PerspectiveClient_released =
11453
+ _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 =
11454
+ /**
11455
+ * Await a write to `uuid`, then start a new write generation for it
11456
+ * (also when the write failed: it may still have changed the perspective).
11457
+ * Calls of {@link querySparql} already waiting keep sharing their RPC; an
11458
+ * identical call started from now on makes its own.
11459
+ */
11460
+ async function _PerspectiveClient_wrote(uuid, write) {
11461
+ try {
11462
+ return await write;
11463
+ }
11464
+ finally {
11465
+ __classPrivateFieldGet$6(this, _PerspectiveClient_writeGeneration, "f").set(uuid, (__classPrivateFieldGet$6(this, _PerspectiveClient_writeGeneration, "f").get(uuid) ?? 0) + 1);
11466
+ }
11467
+ }, _PerspectiveClient_released =
11393
11468
  /** A subscribe call that failed (timed out, aborted, refused) leaves no live
11394
11469
  * query on the executor that nobody holds. The client minted its id, so it
11395
11470
  * disposes it without the reply. A timeout or an abort sends `request.cancel`
@@ -11637,112 +11712,59 @@ var __classPrivateFieldGet$4 = (undefined && undefined.__classPrivateFieldGet) |
11637
11712
  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
11713
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11639
11714
  };
11640
- var _ExpressionClient_instances, _ExpressionClient_apiClient, _ExpressionClient_memCache, _ExpressionClient_inflight, _ExpressionClient_totalMemBytes, _ExpressionClient_persistent, _ExpressionClient_memCacheResult;
11715
+ var _ExpressionClient_apiClient, _ExpressionClient_expressions;
11716
+ /** Most URLs the executor takes in one `expression.getMany` call. */
11717
+ const MAX_URLS_PER_CALL = 200;
11641
11718
  class ExpressionClient {
11642
11719
  constructor(baseUrl, token, sharedApiClient) {
11643
- _ExpressionClient_instances.add(this);
11644
11720
  _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);
11721
+ // A `get` miss is its own `expression.get`, so it waits for no slower
11722
+ // expression and has its own call timeout. The misses of the `getMany`
11723
+ // calls made in one tick go out in `expression.getMany` calls of at most
11724
+ // MAX_URLS_PER_CALL URLs, which answer per URL what `expression.get` would.
11725
+ _ExpressionClient_expressions.set(this, void 0);
11651
11726
  __classPrivateFieldSet$4(this, _ExpressionClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), "f");
11652
- __classPrivateFieldSet$4(this, _ExpressionClient_persistent, createPersistentCache('ad4m-expression-cache', 'expressions'), "f");
11727
+ __classPrivateFieldSet$4(this, _ExpressionClient_expressions, new KeyedCache({
11728
+ load: (url) => __classPrivateFieldGet$4(this, _ExpressionClient_apiClient, "f").call('expression.get', { url }),
11729
+ 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),
11730
+ maxBatch: MAX_URLS_PER_CALL,
11731
+ persistent: createPersistentCache('ad4m-expression-cache', 'expressions'),
11732
+ maxAgeMs: () => ExpressionClient.EXPRESSION_TTL_MS,
11733
+ persistentMaxAgeMs: () => ExpressionClient.EXPRESSION_TTL_MS,
11734
+ limits: () => ({ entries: ExpressionClient.MAX_MEM_ENTRIES, bytes: ExpressionClient.MAX_MEM_BYTES }),
11735
+ }), "f");
11653
11736
  }
11737
+ /** The expression at `url`; `alwaysGet` skips the literal fast path and the cache. */
11654
11738
  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
11739
+ if (alwaysGet) {
11689
11740
  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
11741
+ if (result)
11742
+ __classPrivateFieldGet$4(this, _ExpressionClient_expressions, "f").set(url, result);
11692
11743
  return result;
11693
- })();
11694
- __classPrivateFieldGet$4(this, _ExpressionClient_inflight, "f").set(url, promise);
11695
- try {
11696
- return await promise;
11697
11744
  }
11698
- finally {
11699
- __classPrivateFieldGet$4(this, _ExpressionClient_inflight, "f").delete(url);
11745
+ try {
11746
+ let literalValue = Literal.fromUrl(url).get();
11747
+ if (typeof literalValue === 'object' && literalValue !== null) {
11748
+ if ('author' in literalValue && 'timestamp' in literalValue && 'data' in literalValue && 'proof' in literalValue) {
11749
+ return literalValue;
11750
+ }
11751
+ }
11700
11752
  }
11753
+ catch (e) { }
11754
+ return __classPrivateFieldGet$4(this, _ExpressionClient_expressions, "f").get(url);
11701
11755
  }
11756
+ /**
11757
+ * The expressions at `urls`, in order (`null` when not found); the misses go
11758
+ * out in calls of at most 200 URLs. Rejects with the `RpcError` `get` gives when a URL's read fails.
11759
+ */
11702
11760
  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;
11761
+ return __classPrivateFieldGet$4(this, _ExpressionClient_expressions, "f").getMany(urls);
11737
11762
  }
11738
11763
  /**
11739
- * Clear both L1 (memory) and L2 (persistent) expression caches.
11764
+ * Clear both the memory and the persistent expression caches.
11740
11765
  */
11741
11766
  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
11767
+ __classPrivateFieldGet$4(this, _ExpressionClient_expressions, "f").clear(true);
11746
11768
  }
11747
11769
  async getRaw(url) {
11748
11770
  return __classPrivateFieldGet$4(this, _ExpressionClient_apiClient, "f").call('expression.getRaw', { url });
@@ -11757,31 +11779,21 @@ class ExpressionClient {
11757
11779
  async interact(url, interactionCall) {
11758
11780
  const result = await __classPrivateFieldGet$4(this, _ExpressionClient_apiClient, "f").call('expression.interact', { url, interactionCall });
11759
11781
  // 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
11782
+ __classPrivateFieldGet$4(this, _ExpressionClient_expressions, "f").delete(url);
11763
11783
  return result;
11764
11784
  }
11765
11785
  }
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. */
11786
+ _ExpressionClient_apiClient = new WeakMap(), _ExpressionClient_expressions = new WeakMap();
11787
+ /** Maximum number of expressions kept in memory. */
11782
11788
  ExpressionClient.MAX_MEM_ENTRIES = 200;
11783
- /** Maximum total size (in bytes) of L1 memory cache values. */
11789
+ /** Maximum total size (in bytes of JSON) of the expressions kept in memory. */
11784
11790
  ExpressionClient.MAX_MEM_BYTES = 5 * 1024 * 1024; // 5 MB
11791
+ /**
11792
+ * TTL of every cached expression, in memory and in the persistent cache
11793
+ * (ms). A language may change what a URL returns, and no event tells the
11794
+ * client, so a cached expression expires instead of staying stale.
11795
+ */
11796
+ ExpressionClient.EXPRESSION_TTL_MS = 5 * 60000; // 5 minutes
11785
11797
 
11786
11798
  var base64Js = {};
11787
11799
 
@@ -19298,6 +19310,18 @@ function isIncludeProjection(val) {
19298
19310
  /**
19299
19311
  * Shared query helpers used by both the Prolog and SPARQL query pipelines.
19300
19312
  */
19313
+ /**
19314
+ * The `totalCount` of a model query sent with `count: true`. The executor
19315
+ * answers such a query with a count, so an answer without one is an error,
19316
+ * not zero matches.
19317
+ */
19318
+ function requireTotalCount(answer) {
19319
+ const totalCount = answer?.totalCount;
19320
+ if (typeof totalCount !== "number") {
19321
+ throw new Error("model query asked for a count (count: true) but the answer has no totalCount");
19322
+ }
19323
+ return totalCount;
19324
+ }
19301
19325
  /**
19302
19326
  * Resolves the predicate for a parent query.
19303
19327
  *
@@ -20380,12 +20404,17 @@ class ModelQueryBuilder {
20380
20404
  return { live, initial: await live.start() };
20381
20405
  }
20382
20406
  catch (e) {
20383
- live.dispose();
20384
- if (this.currentSubscription === live)
20385
- this.currentSubscription = undefined;
20407
+ this.endFailed(live);
20386
20408
  throw e;
20387
20409
  }
20388
20410
  }
20411
+ /** End `live` after its call failed. A later call may already own
20412
+ * `currentSubscription`, so only clear it if it is still `live`. */
20413
+ endFailed(live) {
20414
+ live.dispose();
20415
+ if (this.currentSubscription === live)
20416
+ this.currentSubscription = undefined;
20417
+ }
20389
20418
  /**
20390
20419
  * Adds where conditions to the query.
20391
20420
  *
@@ -20772,8 +20801,7 @@ class ModelQueryBuilder {
20772
20801
  * ```
20773
20802
  */
20774
20803
  async count() {
20775
- const { totalCount } = await this.execute({ ...this.queryParams, limit: 0 });
20776
- return totalCount;
20804
+ return requireTotalCount(await this.execute({ ...this.queryParams, limit: 0, count: true }));
20777
20805
  }
20778
20806
  /**
20779
20807
  * Gets the total count of matching entities using SPARQL.
@@ -20812,8 +20840,23 @@ class ModelQueryBuilder {
20812
20840
  */
20813
20841
  async countSubscribe(callback) {
20814
20842
  this.dispose();
20815
- const { initial } = await this.live({ ...this.queryParams, limit: 0 }, (raw) => callback(raw.totalCount ?? 0));
20816
- return initial.totalCount ?? 0;
20843
+ // As paginateSubscribe: a push without the asked-for count is logged and
20844
+ // skipped, since a throw here would reach the client's update dispatch.
20845
+ const { live, initial } = await this.live({ ...this.queryParams, limit: 0, count: true }, (raw) => {
20846
+ try {
20847
+ callback(requireTotalCount(raw));
20848
+ }
20849
+ catch (e) {
20850
+ console.error('Count subscription error:', e);
20851
+ }
20852
+ });
20853
+ try {
20854
+ return requireTotalCount(initial);
20855
+ }
20856
+ catch (e) {
20857
+ this.endFailed(live);
20858
+ throw e;
20859
+ }
20817
20860
  }
20818
20861
  /**
20819
20862
  * Subscribes to count updates using SPARQL.
@@ -20839,8 +20882,8 @@ class ModelQueryBuilder {
20839
20882
  */
20840
20883
  async paginate(pageSize, pageNumber) {
20841
20884
  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 };
20885
+ const answer = await this.execute(paginationQuery);
20886
+ return { results: answer.results, totalCount: requireTotalCount(answer), pageSize, pageNumber };
20844
20887
  }
20845
20888
  /**
20846
20889
  * Gets a page of results using SPARQL.
@@ -20903,9 +20946,10 @@ class ModelQueryBuilder {
20903
20946
  const results = this.parse(raw);
20904
20947
  const fp = fingerprint([results, raw?.totalCount]);
20905
20948
  this.takeSnapshots(results);
20906
- return { page: { results, totalCount: raw?.totalCount, pageSize, pageNumber }, fp };
20949
+ // `count: true` is set above, so the executor sends a total.
20950
+ return { page: { results, totalCount: requireTotalCount(raw), pageSize, pageNumber }, fp };
20907
20951
  };
20908
- const { initial } = await this.live(paginatedQuery, (raw) => {
20952
+ const { live, initial } = await this.live(paginatedQuery, (raw) => {
20909
20953
  try {
20910
20954
  const { page, fp } = toPage(raw);
20911
20955
  if (fp === lastFingerprint)
@@ -20917,9 +20961,16 @@ class ModelQueryBuilder {
20917
20961
  console.error('Paginate subscription error:', e);
20918
20962
  }
20919
20963
  });
20920
- const { page, fp } = toPage(initial);
20921
- lastFingerprint = fp;
20922
- return page;
20964
+ let first;
20965
+ try {
20966
+ first = toPage(initial);
20967
+ }
20968
+ catch (e) {
20969
+ this.endFailed(live);
20970
+ throw e;
20971
+ }
20972
+ lastFingerprint = first.fp;
20973
+ return first.page;
20923
20974
  }
20924
20975
  /**
20925
20976
  * Subscribes to paginated results updates using SPARQL.
@@ -20995,7 +21046,8 @@ const SUBJECT_CLASS_KEY = '__subjectClass';
20995
21046
  * The walk stops descending *through* a polymorphic relation, because there is
20996
21047
  * nothing to descend into: its targets are of several classes by definition, so
20997
21048
  * no single class's metadata could say what a deeper include means. The
20998
- * executor resolves those nested includes against each concrete class instead.
21049
+ * executor applies each concrete class's declared default from its shape
21050
+ * (`ad4m://polymorphic`) to those nested includes instead.
20999
21051
  */
21000
21052
  function applyPolymorphicIncludeDefaults(includes, ctor) {
21001
21053
  const relMeta = getRelationsMetadata(ctor);
@@ -21292,6 +21344,8 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
21292
21344
  }
21293
21345
  return instance;
21294
21346
  }
21347
+ /** The most writes `sendWrites` joins into one `executeAction` call. */
21348
+ const MAX_WRITES_PER_CALL = 200;
21295
21349
  /**
21296
21350
  * Put `childId` under `parent`. A containment scope `{ id }` writes through the
21297
21351
  * built-in `Container` (#1446): the executor runs the adder of the parent's own
@@ -22347,8 +22401,8 @@ class Ad4mModel {
22347
22401
  * ```
22348
22402
  */
22349
22403
  static async findAllAndCount(perspective, query, options) {
22350
- const out = await this.executeModelQuery(perspective, (query ?? {}), undefined, options);
22351
- return out;
22404
+ const answer = await this.executeModelQuery(perspective, { ...(query ?? {}), count: true }, undefined, options);
22405
+ return { results: answer.results, totalCount: requireTotalCount(answer) };
22352
22406
  }
22353
22407
  /**
22354
22408
  * Helper function for pagination with explicit page size and number.
@@ -22369,8 +22423,8 @@ class Ad4mModel {
22369
22423
  */
22370
22424
  static async paginate(perspective, pageSize, pageNumber, query, options) {
22371
22425
  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 };
22426
+ const answer = await this.executeModelQuery(perspective, paginationQuery, undefined, options);
22427
+ return { results: answer.results, totalCount: requireTotalCount(answer), pageSize, pageNumber };
22374
22428
  }
22375
22429
  /**
22376
22430
  * Generates a SPARQL COUNT query for the model.
@@ -22398,20 +22452,20 @@ class Ad4mModel {
22398
22452
  * ```
22399
22453
  */
22400
22454
  static async count(perspective, query, options) {
22401
- const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 }, undefined, options);
22402
- return totalCount;
22455
+ return requireTotalCount(await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0, count: true }, undefined, options));
22403
22456
  }
22404
- async setProperty(key, value, batchId) {
22457
+ /** The `executeAction` write that sets property `key` to `value`; none for an empty value. */
22458
+ async planProperty(key, value) {
22405
22459
  const metadata = this.getPropertyMetadata(key);
22406
22460
  if (!metadata) {
22407
22461
  console.warn(`Property "${key}" has no metadata, skipping`);
22408
- return;
22462
+ return [];
22409
22463
  }
22410
22464
  // Generate actions from metadata (replaces Prolog query)
22411
22465
  const actions = this.generatePropertySetterAction(key, metadata);
22412
22466
  // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal:string:)
22413
22467
  if (value === undefined || value === null || value === "") {
22414
- return;
22468
+ return [];
22415
22469
  }
22416
22470
  const mode = effectiveLiteralStorage(metadata);
22417
22471
  if (mode.kind === "custom") {
@@ -22426,7 +22480,77 @@ class Ad4mModel {
22426
22480
  // Deterministic literal: IRI (POS-index friendly).
22427
22481
  value = valueToLiteralIri(value);
22428
22482
  }
22429
- await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value }], batchId);
22483
+ return [{ commands: actions, parameters: [{ name: "value", value }] }];
22484
+ }
22485
+ /**
22486
+ * The `executeAction` writes of a relation change: one for a set (its
22487
+ * `collectionSetter` takes every value), one per value for an add or remove.
22488
+ */
22489
+ planRelation(key, kind, value) {
22490
+ const metadata = this.getRelationOptions(key);
22491
+ if (!metadata) {
22492
+ console.warn(`Relation "${key}" has no metadata, skipping`);
22493
+ return [];
22494
+ }
22495
+ // Generate actions from metadata (replaces Prolog query)
22496
+ const actions = this.generateRelationAction(key, kind);
22497
+ if (value == null)
22498
+ return [];
22499
+ const values = Array.isArray(value) ? value : [value];
22500
+ const param = (v) => ({ name: "value", value: this.resolveRelationId(v) });
22501
+ if (kind === 'setter')
22502
+ return [{ commands: actions, parameters: values.map(param) }];
22503
+ return values.map(v => ({ commands: actions, parameters: [param(v)] }));
22504
+ }
22505
+ /**
22506
+ * Sends writes in as few `executeAction` calls as keep their links: the
22507
+ * executor runs a call's commands in order, so consecutive writes share one
22508
+ * call, each with its own parameter names. A `collectionSetter` takes every
22509
+ * parameter of its call as a member, so it goes in a call of its own. A
22510
+ * command's `local` flag is per command, so Local and Shared links mix. The
22511
+ * executor tries every parameter name at each position of each command, so
22512
+ * a call holds at most `MAX_WRITES_PER_CALL` writes.
22513
+ */
22514
+ async sendWrites(writes, batchId) {
22515
+ let group = [];
22516
+ const flush = async () => {
22517
+ if (group.length === 1) {
22518
+ await this._perspective.executeAction(group[0].commands, this._baseExpression, group[0].parameters, batchId);
22519
+ }
22520
+ else if (group.length > 1) {
22521
+ const commands = [];
22522
+ const parameters = [];
22523
+ group.forEach((write, i) => {
22524
+ // The executor substitutes a parameter name wherever it occurs in a
22525
+ // command's source, predicate or target; rename `value` the same way.
22526
+ const name = `ad4m-model-write-${i}-value`;
22527
+ const rename = (s) => (typeof s === "string" && write.parameters.length ? s.split("value").join(name) : s);
22528
+ for (const c of write.commands) {
22529
+ commands.push({ ...c, source: rename(c.source), predicate: rename(c.predicate), target: rename(c.target) });
22530
+ }
22531
+ for (const p of write.parameters)
22532
+ parameters.push({ name, value: p.value });
22533
+ });
22534
+ await this._perspective.executeAction(commands, this._baseExpression, parameters, batchId);
22535
+ }
22536
+ group = [];
22537
+ };
22538
+ for (const write of writes) {
22539
+ if (write.commands.some((c) => c.action === "collectionSetter")) {
22540
+ await flush();
22541
+ group = [write];
22542
+ await flush();
22543
+ }
22544
+ else {
22545
+ group.push(write);
22546
+ if (group.length >= MAX_WRITES_PER_CALL)
22547
+ await flush();
22548
+ }
22549
+ }
22550
+ await flush();
22551
+ }
22552
+ async setProperty(key, value, batchId) {
22553
+ await this.sendWrites(await this.planProperty(key, value), batchId);
22430
22554
  }
22431
22555
  /** Resolve a relation argument to a plain string ID. Accepts either a raw
22432
22556
  * string ID or an Ad4mModel instance (in which case `.id` is used). */
@@ -22446,75 +22570,33 @@ class Ad4mModel {
22446
22570
  await this._perspective.updateSubject(abstractName, this._baseExpression, { [key]: { action, value: ids } }, batchId);
22447
22571
  }
22448
22572
  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
- }
22573
+ await this.writeRelation(key, 'setter', value, batchId);
22471
22574
  }
22472
22575
  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
- }
22576
+ await this.writeRelation(key, 'adder', value, batchId);
22495
22577
  }
22496
22578
  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
- }
22579
+ await this.writeRelation(key, 'remover', value, batchId);
22580
+ }
22581
+ /** A relation setter, adder or remover call: on a row read through an
22582
+ * abstract class it dispatches through the executor (see
22583
+ * {@link relationThroughAbstract}); otherwise its writes go out in as few
22584
+ * `executeAction` calls as {@link sendWrites} allows. */
22585
+ async writeRelation(key, kind, value, batchId) {
22586
+ const predicate = this.getRelationOptions(key)?.predicate;
22587
+ if (predicate && kind !== 'remover')
22588
+ this._relationsWritten.add(predicate);
22502
22589
  const abstractName = this.abstractName();
22503
- if (abstractName) {
22504
- if (value != null)
22505
- await this.relationThroughAbstract(abstractName, key, 'remover', value, batchId);
22590
+ if (!abstractName) {
22591
+ await this.sendWrites(this.planRelation(key, kind, value), batchId);
22506
22592
  return;
22507
22593
  }
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
- }
22594
+ if (!this.getRelationOptions(key)) {
22595
+ console.warn(`Relation "${key}" has no metadata, skipping`);
22596
+ return;
22517
22597
  }
22598
+ if (value != null)
22599
+ await this.relationThroughAbstract(abstractName, key, kind, value, batchId);
22518
22600
  }
22519
22601
  /**
22520
22602
  * Saves the model instance to the perspective.
@@ -22604,13 +22686,14 @@ class Ad4mModel {
22604
22686
  const className = await this.perspective.stringOrTemplateObjectToSubjectClassName(this);
22605
22687
  await this.perspective.createSubject(className, this._baseExpression, initialValues, batchId);
22606
22688
  // Relations via innerUpdate; createSubject wrote the scalar properties.
22607
- await this.innerUpdate(false, batchId);
22689
+ const writes = await this.updateWrites(false);
22608
22690
  for (const key of deferredExpressionProps) {
22609
22691
  const value = this[key];
22610
22692
  if (value !== undefined && value !== null) {
22611
- await this.setProperty(key, value, batchId);
22693
+ writes.push(...await this.planProperty(key, value));
22612
22694
  }
22613
22695
  }
22696
+ await this.sendWrites(writes, batchId);
22614
22697
  // If we got a batchId passed in, we let the caller decide when to commit.
22615
22698
  // We can't call getData() since the instance won't exist in the perspective
22616
22699
  // until the batch is committed.
@@ -22672,6 +22755,11 @@ class Ad4mModel {
22672
22755
  return cleanCopy;
22673
22756
  }
22674
22757
  async innerUpdate(setProperties = true, batchId) {
22758
+ await this.sendWrites(await this.updateWrites(setProperties), batchId);
22759
+ }
22760
+ /** The writes of the changed fields, in field order (see {@link sendWrites}). */
22761
+ async updateWrites(setProperties = true) {
22762
+ const writes = [];
22675
22763
  const ctor = this.constructor;
22676
22764
  // Determine which fields actually changed (skip unchanged when snapshot exists)
22677
22765
  const dirty = this._snapshot ? new Set(this.changedFields()) : null;
@@ -22708,18 +22796,21 @@ class Ad4mModel {
22708
22796
  }
22709
22797
  if (value !== undefined && value !== null) {
22710
22798
  if (value?.action) {
22799
+ const envelopePredicate = this.getRelationOptions(key)?.predicate;
22800
+ if (envelopePredicate && value.action !== "remover")
22801
+ this._relationsWritten.add(envelopePredicate);
22711
22802
  switch (value.action) {
22712
22803
  case "setter":
22713
- await this.setRelationValues(key, value.value, batchId);
22804
+ writes.push(...this.planRelation(key, 'setter', value.value));
22714
22805
  break;
22715
22806
  case "adder":
22716
- await this.addRelationValue(key, value.value, batchId);
22807
+ writes.push(...this.planRelation(key, 'adder', value.value));
22717
22808
  break;
22718
22809
  case "remover":
22719
- await this.removeRelationValue(key, value.value, batchId);
22810
+ writes.push(...this.planRelation(key, 'remover', value.value));
22720
22811
  break;
22721
22812
  default:
22722
- await this.setRelationValues(key, value.value, batchId);
22813
+ writes.push(...this.planRelation(key, 'setter', value.value));
22723
22814
  break;
22724
22815
  }
22725
22816
  }
@@ -22727,9 +22818,11 @@ class Ad4mModel {
22727
22818
  // Handle all arrays as relations, including empty ones (which clears the relation).
22728
22819
  // A record being created under an id minted here has no links to
22729
22820
  // 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))
22821
+ const predicate = this.getRelationOptions(key)?.predicate ?? key;
22822
+ if (value.length === 0 && !this._snapshot && this._idMinted && !this._relationsWritten.has(predicate))
22731
22823
  continue;
22732
- await this.setRelationValues(key, value, batchId);
22824
+ this._relationsWritten.add(predicate);
22825
+ writes.push(...this.planRelation(key, 'setter', value));
22733
22826
  }
22734
22827
  else if (value !== undefined && value !== null && value !== "") {
22735
22828
  // A scalar handed to a relation field is a single-member relation.
@@ -22758,7 +22851,8 @@ class Ad4mModel {
22758
22851
  // both paths at once.
22759
22852
  const relationMeta = this.getRelationOptions(key);
22760
22853
  if (relationMeta) {
22761
- await this.setRelationValues(key, [value], batchId);
22854
+ this._relationsWritten.add(relationMeta.predicate);
22855
+ writes.push(...this.planRelation(key, 'setter', [value]));
22762
22856
  continue;
22763
22857
  }
22764
22858
  if (setProperties) {
@@ -22767,11 +22861,12 @@ class Ad4mModel {
22767
22861
  if (propMeta?.flag) {
22768
22862
  continue;
22769
22863
  }
22770
- await this.setProperty(key, value, batchId);
22864
+ writes.push(...await this.planProperty(key, value));
22771
22865
  }
22772
22866
  }
22773
22867
  }
22774
22868
  }
22869
+ return writes;
22775
22870
  }
22776
22871
  /**
22777
22872
  * Evaluate SPARQL getters for a batch of instances on demand.
@@ -23918,7 +24013,7 @@ exports.FlowTransitionProposal = class FlowTransitionProposal extends Ad4mModel
23918
24013
  this.acceptedBy = [];
23919
24014
  // Whether this proposal settled an edge is not on the record: the
23920
24015
  // executor keeps that per agent, outside the graph (#1424). Ask
23921
- // `PerspectiveProxy.flowFired(instance)` for the proposals your replica
24016
+ // `PerspectiveProxy.flowFired(instances)` for the proposals your replica
23922
24017
  // recorded as fired, or listen with `onFlowStateChanged`.
23923
24018
  // "When was this proposal written?" is answered by `Ad4mModel`'s built-in
23924
24019
  // `createdAt`, synthesized on hydration from the earliest link timestamp
@@ -26318,7 +26413,6 @@ exports.buildSHACL = buildSHACL;
26318
26413
  exports.buildSPARQLQuery = buildSPARQLQuery;
26319
26414
  exports.buildWhereCondition = buildWhereCondition;
26320
26415
  exports.capSentence = capSentence;
26321
- exports.clearQueryCache = clearQueryCache;
26322
26416
  exports.coalesce = coalesce;
26323
26417
  exports.compileWhereClause = compileWhereClause;
26324
26418
  exports.concat = concat;
@@ -26336,7 +26430,6 @@ exports.focus = focus;
26336
26430
  exports.formatList = formatList;
26337
26431
  exports.formatQueryValue = formatQueryValue;
26338
26432
  exports.formatSPARQLValue = formatSPARQLValue;
26339
- exports.getCachedResult = getCachedResult;
26340
26433
  exports.getDefaultValueForType = getDefaultValueForType;
26341
26434
  exports.getMemoizedSHACL = getMemoizedSHACL;
26342
26435
  exports.getPropertiesMetadata = getPropertiesMetadata;
@@ -26346,7 +26439,6 @@ exports.hasJsOnlyWhereFilters = hasJsOnlyWhereFilters;
26346
26439
  exports.hintFor = hintFor;
26347
26440
  exports.holdsAWholeWordTerm = holdsAWholeWordTerm;
26348
26441
  exports.ifExpr = ifExpr;
26349
- exports.invalidatePerspectiveCache = invalidatePerspectiveCache;
26350
26442
  exports.isArrayType = isArrayType;
26351
26443
  exports.isBot = isBot;
26352
26444
  exports.isContainedScope = isContainedScope;
@@ -26378,11 +26470,10 @@ exports.parseLitBoolean = parseLitBoolean;
26378
26470
  exports.parseLitNumber = parseLitNumber;
26379
26471
  exports.parseSparqlCount = parseSparqlCount;
26380
26472
  exports.path = path;
26381
- exports.queryCacheSize = queryCacheSize;
26382
26473
  exports.reopenDelay = reopenDelay;
26383
26474
  exports.requireSingleParent = requireSingleParent;
26475
+ exports.requireTotalCount = requireTotalCount;
26384
26476
  exports.resolveParentPredicate = resolveParentPredicate;
26385
- exports.setCachedResult = setCachedResult;
26386
26477
  exports.setPropertyRegistryEntry = setPropertyRegistryEntry;
26387
26478
  exports.setRelationRegistryEntry = setRelationRegistryEntry;
26388
26479
  exports.typeDefsString = typeDefsString;