@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.js CHANGED
@@ -1332,13 +1332,13 @@ function isBot(agent) {
1332
1332
  * never need try/catch around cache operations
1333
1333
  * - Tree-shakeable: import only what you need
1334
1334
  */
1335
- var __classPrivateFieldSet$e = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
1335
+ var __classPrivateFieldSet$f = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
1336
1336
  if (kind === "m") throw new TypeError("Private method is not writable");
1337
1337
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
1338
1338
  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");
1339
1339
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
1340
1340
  };
1341
- var __classPrivateFieldGet$e = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
1341
+ var __classPrivateFieldGet$f = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
1342
1342
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
1343
1343
  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");
1344
1344
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
@@ -1352,15 +1352,15 @@ class IDBCache {
1352
1352
  _IDBCache_storeName.set(this, void 0);
1353
1353
  _IDBCache_dbPromise.set(this, null);
1354
1354
  _IDBCache_version.set(this, 1);
1355
- __classPrivateFieldSet$e(this, _IDBCache_dbName, dbName, "f");
1356
- __classPrivateFieldSet$e(this, _IDBCache_storeName, storeName, "f");
1355
+ __classPrivateFieldSet$f(this, _IDBCache_dbName, dbName, "f");
1356
+ __classPrivateFieldSet$f(this, _IDBCache_storeName, storeName, "f");
1357
1357
  }
1358
1358
  async get(key) {
1359
1359
  try {
1360
- const db = await __classPrivateFieldGet$e(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
1360
+ const db = await __classPrivateFieldGet$f(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
1361
1361
  return new Promise((resolve) => {
1362
- const tx = db.transaction(__classPrivateFieldGet$e(this, _IDBCache_storeName, "f"), 'readonly');
1363
- const store = tx.objectStore(__classPrivateFieldGet$e(this, _IDBCache_storeName, "f"));
1362
+ const tx = db.transaction(__classPrivateFieldGet$f(this, _IDBCache_storeName, "f"), 'readonly');
1363
+ const store = tx.objectStore(__classPrivateFieldGet$f(this, _IDBCache_storeName, "f"));
1364
1364
  const req = store.get(key);
1365
1365
  req.onsuccess = () => resolve(req.result ?? undefined);
1366
1366
  req.onerror = () => resolve(undefined);
@@ -1372,10 +1372,10 @@ class IDBCache {
1372
1372
  }
1373
1373
  async put(key, value) {
1374
1374
  try {
1375
- const db = await __classPrivateFieldGet$e(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
1375
+ const db = await __classPrivateFieldGet$f(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
1376
1376
  return new Promise((resolve) => {
1377
- const tx = db.transaction(__classPrivateFieldGet$e(this, _IDBCache_storeName, "f"), 'readwrite');
1378
- const store = tx.objectStore(__classPrivateFieldGet$e(this, _IDBCache_storeName, "f"));
1377
+ const tx = db.transaction(__classPrivateFieldGet$f(this, _IDBCache_storeName, "f"), 'readwrite');
1378
+ const store = tx.objectStore(__classPrivateFieldGet$f(this, _IDBCache_storeName, "f"));
1379
1379
  store.put(value, key);
1380
1380
  tx.oncomplete = () => resolve();
1381
1381
  tx.onerror = () => resolve(); // fire-and-forget
@@ -1387,10 +1387,10 @@ class IDBCache {
1387
1387
  }
1388
1388
  async delete(key) {
1389
1389
  try {
1390
- const db = await __classPrivateFieldGet$e(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
1390
+ const db = await __classPrivateFieldGet$f(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
1391
1391
  return new Promise((resolve) => {
1392
- const tx = db.transaction(__classPrivateFieldGet$e(this, _IDBCache_storeName, "f"), 'readwrite');
1393
- const store = tx.objectStore(__classPrivateFieldGet$e(this, _IDBCache_storeName, "f"));
1392
+ const tx = db.transaction(__classPrivateFieldGet$f(this, _IDBCache_storeName, "f"), 'readwrite');
1393
+ const store = tx.objectStore(__classPrivateFieldGet$f(this, _IDBCache_storeName, "f"));
1394
1394
  store.delete(key);
1395
1395
  tx.oncomplete = () => resolve();
1396
1396
  tx.onerror = () => resolve();
@@ -1402,10 +1402,10 @@ class IDBCache {
1402
1402
  }
1403
1403
  async clear() {
1404
1404
  try {
1405
- const db = await __classPrivateFieldGet$e(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
1405
+ const db = await __classPrivateFieldGet$f(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
1406
1406
  return new Promise((resolve) => {
1407
- const tx = db.transaction(__classPrivateFieldGet$e(this, _IDBCache_storeName, "f"), 'readwrite');
1408
- const store = tx.objectStore(__classPrivateFieldGet$e(this, _IDBCache_storeName, "f"));
1407
+ const tx = db.transaction(__classPrivateFieldGet$f(this, _IDBCache_storeName, "f"), 'readwrite');
1408
+ const store = tx.objectStore(__classPrivateFieldGet$f(this, _IDBCache_storeName, "f"));
1409
1409
  store.clear();
1410
1410
  tx.oncomplete = () => resolve();
1411
1411
  tx.onerror = () => resolve();
@@ -1417,10 +1417,10 @@ class IDBCache {
1417
1417
  }
1418
1418
  }
1419
1419
  _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() {
1420
- if (!__classPrivateFieldGet$e(this, _IDBCache_dbPromise, "f")) {
1421
- __classPrivateFieldSet$e(this, _IDBCache_dbPromise, new Promise((resolve, reject) => {
1422
- const storeName = __classPrivateFieldGet$e(this, _IDBCache_storeName, "f");
1423
- const req = indexedDB.open(__classPrivateFieldGet$e(this, _IDBCache_dbName, "f"), __classPrivateFieldGet$e(this, _IDBCache_version, "f"));
1420
+ if (!__classPrivateFieldGet$f(this, _IDBCache_dbPromise, "f")) {
1421
+ __classPrivateFieldSet$f(this, _IDBCache_dbPromise, new Promise((resolve, reject) => {
1422
+ const storeName = __classPrivateFieldGet$f(this, _IDBCache_storeName, "f");
1423
+ const req = indexedDB.open(__classPrivateFieldGet$f(this, _IDBCache_dbName, "f"), __classPrivateFieldGet$f(this, _IDBCache_version, "f"));
1424
1424
  req.onupgradeneeded = () => {
1425
1425
  const db = req.result;
1426
1426
  if (!db.objectStoreNames.contains(storeName)) {
@@ -1431,7 +1431,7 @@ _IDBCache_dbName = new WeakMap(), _IDBCache_storeName = new WeakMap(), _IDBCache
1431
1431
  req.onerror = () => reject(req.error);
1432
1432
  }), "f");
1433
1433
  }
1434
- return __classPrivateFieldGet$e(this, _IDBCache_dbPromise, "f");
1434
+ return __classPrivateFieldGet$f(this, _IDBCache_dbPromise, "f");
1435
1435
  };
1436
1436
  // ── NullCache (no-op fallback for Node.js) ───────────────────────────
1437
1437
  class NullCache {
@@ -1459,6 +1459,149 @@ function createPersistentCache(dbName, storeName) {
1459
1459
  return new NullCache();
1460
1460
  }
1461
1461
 
1462
+ var __classPrivateFieldSet$e = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
1463
+ if (kind === "m") throw new TypeError("Private method is not writable");
1464
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
1465
+ 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");
1466
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
1467
+ };
1468
+ var __classPrivateFieldGet$e = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
1469
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
1470
+ 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");
1471
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
1472
+ };
1473
+ 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;
1474
+ /**
1475
+ * Keyed read cache shared by profile and expression lookups. Concurrent reads
1476
+ * of one key share one request; misses of one tick go out in one `loadMany`
1477
+ * call, except a `get()` miss when the options have `load`. A `null` (not
1478
+ * found) is returned but not kept.
1479
+ */
1480
+ class KeyedCache {
1481
+ constructor(opts) {
1482
+ _KeyedCache_instances.add(this);
1483
+ _KeyedCache_opts.set(this, void 0);
1484
+ _KeyedCache_values.set(this, new Map());
1485
+ _KeyedCache_bytes.set(this, 0);
1486
+ _KeyedCache_pending.set(this, new Map());
1487
+ _KeyedCache_batch.set(this, null);
1488
+ __classPrivateFieldSet$e(this, _KeyedCache_opts, opts, "f");
1489
+ }
1490
+ get(key) {
1491
+ const load = __classPrivateFieldGet$e(this, _KeyedCache_opts, "f").load;
1492
+ 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));
1493
+ }
1494
+ getMany(keys) {
1495
+ 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))));
1496
+ }
1497
+ /** Stores a value known to be current; a read in flight for the key is not kept. */
1498
+ set(key, value) {
1499
+ __classPrivateFieldGet$e(this, _KeyedCache_pending, "f").delete(key);
1500
+ __classPrivateFieldGet$e(this, _KeyedCache_instances, "m", _KeyedCache_remember).call(this, key, value, true);
1501
+ }
1502
+ /** Forgets a key in memory and in the persistent store. */
1503
+ delete(key) {
1504
+ __classPrivateFieldGet$e(this, _KeyedCache_pending, "f").delete(key);
1505
+ __classPrivateFieldGet$e(this, _KeyedCache_instances, "m", _KeyedCache_forget).call(this, key);
1506
+ __classPrivateFieldGet$e(this, _KeyedCache_opts, "f").persistent?.delete(key); // fire-and-forget
1507
+ }
1508
+ /** Forgets every key in memory, and in the persistent store when `persistent` is set. */
1509
+ clear(persistent = false) {
1510
+ __classPrivateFieldGet$e(this, _KeyedCache_pending, "f").clear();
1511
+ __classPrivateFieldGet$e(this, _KeyedCache_values, "f").clear();
1512
+ __classPrivateFieldSet$e(this, _KeyedCache_bytes, 0, "f");
1513
+ if (persistent)
1514
+ __classPrivateFieldGet$e(this, _KeyedCache_opts, "f").persistent?.clear(); // fire-and-forget
1515
+ }
1516
+ }
1517
+ _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) {
1518
+ const hit = __classPrivateFieldGet$e(this, _KeyedCache_values, "f").get(key);
1519
+ if (hit && Date.now() - hit.ts < (__classPrivateFieldGet$e(this, _KeyedCache_opts, "f").maxAgeMs?.(key) ?? Infinity))
1520
+ return Promise.resolve(hit.value);
1521
+ const inFlight = __classPrivateFieldGet$e(this, _KeyedCache_pending, "f").get(key);
1522
+ if (inFlight)
1523
+ return inFlight;
1524
+ const loading = fetch(key);
1525
+ const promise = loading.then(({ value, stored }) => {
1526
+ // A set(), delete() or clear() since the read started wins over its result.
1527
+ if (__classPrivateFieldGet$e(this, _KeyedCache_pending, "f").get(key) === promise) {
1528
+ __classPrivateFieldGet$e(this, _KeyedCache_pending, "f").delete(key);
1529
+ if (value !== null)
1530
+ __classPrivateFieldGet$e(this, _KeyedCache_instances, "m", _KeyedCache_remember).call(this, key, value, !stored);
1531
+ }
1532
+ return value;
1533
+ }, (error) => {
1534
+ if (__classPrivateFieldGet$e(this, _KeyedCache_pending, "f").get(key) === promise)
1535
+ __classPrivateFieldGet$e(this, _KeyedCache_pending, "f").delete(key);
1536
+ throw error;
1537
+ });
1538
+ __classPrivateFieldGet$e(this, _KeyedCache_pending, "f").set(key, promise);
1539
+ return promise;
1540
+ }, _KeyedCache_enqueue = function _KeyedCache_enqueue(key) {
1541
+ if (!__classPrivateFieldGet$e(this, _KeyedCache_batch, "f")) {
1542
+ const keys = [];
1543
+ const done = Promise.resolve().then(() => {
1544
+ __classPrivateFieldSet$e(this, _KeyedCache_batch, null, "f");
1545
+ return __classPrivateFieldGet$e(this, _KeyedCache_instances, "m", _KeyedCache_loadBatch).call(this, keys);
1546
+ });
1547
+ __classPrivateFieldSet$e(this, _KeyedCache_batch, { keys, done }, "f");
1548
+ }
1549
+ __classPrivateFieldGet$e(this, _KeyedCache_batch, "f").keys.push(key);
1550
+ return __classPrivateFieldGet$e(this, _KeyedCache_batch, "f").done.then(loaded => {
1551
+ const entry = loaded.get(key);
1552
+ if (entry.value instanceof Error)
1553
+ throw entry.value;
1554
+ return entry;
1555
+ });
1556
+ }, _KeyedCache_loadOne = async function _KeyedCache_loadOne(key, load) {
1557
+ return (await __classPrivateFieldGet$e(this, _KeyedCache_instances, "m", _KeyedCache_stored).call(this, key)) ?? { value: await load(key), stored: false };
1558
+ }, _KeyedCache_loadBatch = async function _KeyedCache_loadBatch(keys) {
1559
+ const loaded = new Map();
1560
+ const stored = await Promise.all(keys.map(key => __classPrivateFieldGet$e(this, _KeyedCache_instances, "m", _KeyedCache_stored).call(this, key)));
1561
+ const misses = keys.filter((key, i) => {
1562
+ if (stored[i])
1563
+ loaded.set(key, stored[i]);
1564
+ return !stored[i];
1565
+ });
1566
+ const size = __classPrivateFieldGet$e(this, _KeyedCache_opts, "f").maxBatch ?? Infinity;
1567
+ const chunks = [];
1568
+ for (let i = 0; i < misses.length; i += size)
1569
+ chunks.push(misses.slice(i, i + size));
1570
+ await Promise.all(chunks.map(async (chunk) => {
1571
+ const values = await __classPrivateFieldGet$e(this, _KeyedCache_opts, "f").loadMany(chunk);
1572
+ chunk.forEach((key, i) => loaded.set(key, { value: values[i] ?? null, stored: false }));
1573
+ }));
1574
+ return loaded;
1575
+ }, _KeyedCache_stored = async function _KeyedCache_stored(key) {
1576
+ const entry = await __classPrivateFieldGet$e(this, _KeyedCache_opts, "f").persistent?.get(key);
1577
+ // An entry without `value` was written in an older format: a miss.
1578
+ if (entry?.value == null || !(Date.now() - (entry.ts ?? 0) < (__classPrivateFieldGet$e(this, _KeyedCache_opts, "f").persistentMaxAgeMs?.() ?? Infinity)))
1579
+ return null;
1580
+ return { value: entry.value, stored: true };
1581
+ }, _KeyedCache_remember = function _KeyedCache_remember(key, value, persist) {
1582
+ const limits = __classPrivateFieldGet$e(this, _KeyedCache_opts, "f").limits?.();
1583
+ const size = limits ? JSON.stringify(value).length : 0;
1584
+ __classPrivateFieldGet$e(this, _KeyedCache_instances, "m", _KeyedCache_forget).call(this, key);
1585
+ if (limits) {
1586
+ for (const oldest of __classPrivateFieldGet$e(this, _KeyedCache_values, "f").keys()) {
1587
+ if (__classPrivateFieldGet$e(this, _KeyedCache_values, "f").size < limits.entries && __classPrivateFieldGet$e(this, _KeyedCache_bytes, "f") + size <= limits.bytes)
1588
+ break;
1589
+ __classPrivateFieldGet$e(this, _KeyedCache_instances, "m", _KeyedCache_forget).call(this, oldest);
1590
+ }
1591
+ }
1592
+ const ts = Date.now();
1593
+ __classPrivateFieldGet$e(this, _KeyedCache_values, "f").set(key, { value, ts, size });
1594
+ __classPrivateFieldSet$e(this, _KeyedCache_bytes, __classPrivateFieldGet$e(this, _KeyedCache_bytes, "f") + size, "f");
1595
+ if (persist)
1596
+ __classPrivateFieldGet$e(this, _KeyedCache_opts, "f").persistent?.put(key, { value, ts }); // fire-and-forget
1597
+ }, _KeyedCache_forget = function _KeyedCache_forget(key) {
1598
+ const entry = __classPrivateFieldGet$e(this, _KeyedCache_values, "f").get(key);
1599
+ if (!entry)
1600
+ return;
1601
+ __classPrivateFieldSet$e(this, _KeyedCache_bytes, __classPrivateFieldGet$e(this, _KeyedCache_bytes, "f") - entry.size, "f");
1602
+ __classPrivateFieldGet$e(this, _KeyedCache_values, "f").delete(key);
1603
+ };
1604
+
1462
1605
  var __classPrivateFieldSet$d = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
1463
1606
  if (kind === "m") throw new TypeError("Private method is not writable");
1464
1607
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
@@ -1470,36 +1613,32 @@ var __classPrivateFieldGet$d = (undefined && undefined.__classPrivateFieldGet) |
1470
1613
  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");
1471
1614
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
1472
1615
  };
1473
- var _AgentClient_instances, _AgentClient_apiClient, _AgentClient_memCache, _AgentClient_persistent, _AgentClient_selfDid, _AgentClient_cacheAgent, _AgentClient_signLinks, _AgentClient_listen, _AgentClient_onAgentUpdated;
1616
+ var _AgentClient_instances, _AgentClient_apiClient, _AgentClient_agents, _AgentClient_loadAgents, _AgentClient_cacheAgent, _AgentClient_signLinks, _AgentClient_listen, _AgentClient_onAgentUpdated;
1474
1617
  function toAgent(data) {
1475
1618
  return data ? Agent.fromWire(data) : null;
1476
1619
  }
1620
+ /** Most DIDs the executor takes in one `agent.byDIDs` call. */
1621
+ const MAX_DIDS_PER_CALL = 200;
1477
1622
  class AgentClient {
1478
1623
  constructor(baseUrl, token, sharedApiClient) {
1479
1624
  _AgentClient_instances.add(this);
1480
1625
  _AgentClient_apiClient.set(this, void 0);
1481
- // ── byDID cache ────────────────────────────────────────────────────
1482
- // L1: in-memory promise cache with timestamps for TTL
1483
- _AgentClient_memCache.set(this, new Map());
1484
- // L2: persistent cache (IndexedDB in browser, NullCache in Node)
1485
- // Entries are wrapped with a timestamp so the TTL can be enforced across restarts.
1486
- _AgentClient_persistent.set(this, void 0);
1487
- // Self-DID for event-driven invalidation (no TTL for own profile)
1488
- _AgentClient_selfDid.set(this, null);
1626
+ // byDID cache: concurrent misses go out in one `agent.byDIDs` call.
1627
+ _AgentClient_agents.set(this, void 0);
1489
1628
  _AgentClient_onAgentUpdated.set(this, (event) => {
1490
1629
  __classPrivateFieldGet$d(this, _AgentClient_instances, "m", _AgentClient_cacheAgent).call(this, Agent.fromWire(event.agent));
1491
1630
  });
1492
1631
  __classPrivateFieldSet$d(this, _AgentClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), "f");
1493
- __classPrivateFieldSet$d(this, _AgentClient_persistent, createPersistentCache('ad4m-agent-cache', 'agents'), "f");
1632
+ __classPrivateFieldSet$d(this, _AgentClient_agents, new KeyedCache({
1633
+ loadMany: (dids) => __classPrivateFieldGet$d(this, _AgentClient_instances, "m", _AgentClient_loadAgents).call(this, dids),
1634
+ maxBatch: MAX_DIDS_PER_CALL,
1635
+ persistent: createPersistentCache('ad4m-agent-cache', 'agents'),
1636
+ maxAgeMs: () => AgentClient.REMOTE_AGENT_TTL_MS,
1637
+ persistentMaxAgeMs: () => AgentClient.REMOTE_AGENT_TTL_MS,
1638
+ }), "f");
1494
1639
  }
1495
1640
  async me() {
1496
- const agentObject = toAgent(await __classPrivateFieldGet$d(this, _AgentClient_apiClient, "f").call('agent.get', {}));
1497
- // Auto-set selfDid so event-driven cache invalidation works
1498
- // without requiring apps to call setSelfDid() manually
1499
- if (agentObject.did && !__classPrivateFieldGet$d(this, _AgentClient_selfDid, "f")) {
1500
- __classPrivateFieldSet$d(this, _AgentClient_selfDid, agentObject.did, "f");
1501
- }
1502
- return agentObject;
1641
+ return toAgent(await __classPrivateFieldGet$d(this, _AgentClient_apiClient, "f").call('agent.get', {}));
1503
1642
  }
1504
1643
  async status() {
1505
1644
  const agentStatus = await __classPrivateFieldGet$d(this, _AgentClient_apiClient, "f").call('agent.status', {});
@@ -1524,61 +1663,27 @@ class AgentClient {
1524
1663
  const result = await __classPrivateFieldGet$d(this, _AgentClient_apiClient, "f").call('agent.unlock', { passphrase, holochain }, options);
1525
1664
  return new AgentStatus(result);
1526
1665
  }
1527
- async byDID(did) {
1528
- // agent-updated events keep cached entries fresh (the self-DID entry has no TTL).
1529
- __classPrivateFieldGet$d(this, _AgentClient_instances, "m", _AgentClient_listen).call(this);
1530
- const now = Date.now();
1531
- const cached = __classPrivateFieldGet$d(this, _AgentClient_memCache, "f").get(did);
1532
- if (cached) {
1533
- const isSelf = did === __classPrivateFieldGet$d(this, _AgentClient_selfDid, "f");
1534
- // Self-DID: L1 always valid (event-driven invalidation)
1535
- // Remote DID: L1 valid within TTL
1536
- if (isSelf || (now - cached.ts) < AgentClient.REMOTE_AGENT_TTL_MS) {
1537
- return cached.promise;
1538
- }
1539
- }
1540
- // Deduplicate: store the promise immediately so concurrent calls share one RPC
1541
- const promise = (async () => {
1542
- // L2: check persistent cache before network
1543
- const entry = await __classPrivateFieldGet$d(this, _AgentClient_persistent, "f").get(did);
1544
- // entry.agent may be undefined for pre-TTL cache entries (migration) — treat as expired
1545
- if (entry?.agent && (now - (entry.ts ?? 0)) < AgentClient.REMOTE_AGENT_TTL_L2_MS) {
1546
- return entry.agent;
1547
- }
1548
- // L3: network fetch
1549
- const result = toAgent(await __classPrivateFieldGet$d(this, _AgentClient_apiClient, "f").call('agent.byDid', { did }));
1550
- __classPrivateFieldGet$d(this, _AgentClient_persistent, "f").put(did, { agent: result, ts: Date.now() }); // fire-and-forget write to L2
1551
- return result;
1552
- })();
1553
- __classPrivateFieldGet$d(this, _AgentClient_memCache, "f").set(did, { promise, ts: now });
1554
- // Clean up on failure so next call retries
1555
- promise.catch(() => {
1556
- if (__classPrivateFieldGet$d(this, _AgentClient_memCache, "f").get(did)?.promise === promise) {
1557
- __classPrivateFieldGet$d(this, _AgentClient_memCache, "f").delete(did);
1558
- }
1559
- });
1560
- return promise;
1561
- }
1562
1666
  /**
1563
- * Set the current agent's own DID.
1564
- * The self-DID receives event-driven invalidation and is never TTL-expired.
1667
+ * The agent with this DID, or `null` when it is unknown. Concurrent calls
1668
+ * for any DIDs share one `agent.byDIDs` request.
1565
1669
  */
1566
- setSelfDid(did) {
1567
- __classPrivateFieldSet$d(this, _AgentClient_selfDid, did, "f");
1670
+ async byDID(did) {
1671
+ // agent-updated events refresh cached entries before their TTL runs out.
1672
+ __classPrivateFieldGet$d(this, _AgentClient_instances, "m", _AgentClient_listen).call(this);
1673
+ return __classPrivateFieldGet$d(this, _AgentClient_agents, "f").get(did);
1568
1674
  }
1569
1675
  /**
1570
1676
  * Invalidate a specific DID's cache entry in both L1 and L2.
1571
1677
  */
1572
1678
  invalidateByDid(did) {
1573
- __classPrivateFieldGet$d(this, _AgentClient_memCache, "f").delete(did);
1574
- __classPrivateFieldGet$d(this, _AgentClient_persistent, "f").delete(did); // fire-and-forget
1679
+ __classPrivateFieldGet$d(this, _AgentClient_agents, "f").delete(did);
1575
1680
  }
1576
1681
  /**
1577
1682
  * Clear the entire L1 (memory) byDID cache.
1578
1683
  * L2 (IndexedDB) is preserved — agent data remains valid across sessions.
1579
1684
  */
1580
1685
  clearByDidCache() {
1581
- __classPrivateFieldGet$d(this, _AgentClient_memCache, "f").clear();
1686
+ __classPrivateFieldGet$d(this, _AgentClient_agents, "f").clear();
1582
1687
  }
1583
1688
  async updatePublicPerspective(perspective) {
1584
1689
  // Send only the signed fields: the public perspective carries no link status.
@@ -1710,11 +1815,25 @@ class AgentClient {
1710
1815
  return __classPrivateFieldGet$d(this, _AgentClient_apiClient, "f").call('hosting.requestPayment', { amountHOT });
1711
1816
  }
1712
1817
  }
1713
- _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) {
1818
+ _AgentClient_apiClient = new WeakMap(), _AgentClient_agents = new WeakMap(), _AgentClient_onAgentUpdated = new WeakMap(), _AgentClient_instances = new WeakSet(), _AgentClient_loadAgents =
1819
+ /**
1820
+ * One `agent.byDIDs` call for the misses of one tick. The executor fails
1821
+ * that call when one DID's lookup fails (500), so the DIDs of a failed
1822
+ * batch are then read alone: each caller gets what a lone `byDID` gives.
1823
+ */
1824
+ async function _AgentClient_loadAgents(dids) {
1825
+ try {
1826
+ return (await __classPrivateFieldGet$d(this, _AgentClient_apiClient, "f").call('agent.byDIDs', { dids })).map(toAgent);
1827
+ }
1828
+ catch (error) {
1829
+ if (dids.length === 1 || !(error instanceof RpcError) || error.status !== 500)
1830
+ throw error;
1831
+ 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)))));
1832
+ }
1833
+ }, _AgentClient_cacheAgent = function _AgentClient_cacheAgent(agent) {
1714
1834
  if (!agent.did)
1715
1835
  return;
1716
- __classPrivateFieldGet$d(this, _AgentClient_memCache, "f").set(agent.did, { promise: Promise.resolve(agent), ts: Date.now() });
1717
- __classPrivateFieldGet$d(this, _AgentClient_persistent, "f").put(agent.did, { agent, ts: Date.now() }); // fire-and-forget
1836
+ __classPrivateFieldGet$d(this, _AgentClient_agents, "f").set(agent.did, agent);
1718
1837
  __classPrivateFieldGet$d(this, _AgentClient_instances, "m", _AgentClient_listen).call(this);
1719
1838
  }, _AgentClient_signLinks =
1720
1839
  /** Has the executor sign `links` as this agent, in a throwaway perspective. */
@@ -1729,11 +1848,13 @@ async function _AgentClient_signLinks(links) {
1729
1848
  }, _AgentClient_listen = function _AgentClient_listen() {
1730
1849
  __classPrivateFieldGet$d(this, _AgentClient_apiClient, "f").on('agent-updated', __classPrivateFieldGet$d(this, _AgentClient_onAgentUpdated, "f"));
1731
1850
  };
1732
- /** TTL for remote (non-self) agent profiles in L1 cache (ms). */
1851
+ /**
1852
+ * TTL of every cached profile, the own one too, in memory and in the
1853
+ * persistent cache (ms). `agent-updated` only comes from this executor, so
1854
+ * a profile changed through another executor of the same agent shows up
1855
+ * when the entry expires.
1856
+ */
1733
1857
  AgentClient.REMOTE_AGENT_TTL_MS = 5 * 60000; // 5 minutes
1734
- /** TTL for remote agent profiles in the L2 (IndexedDB) cache (ms).
1735
- * After this window any restart triggers a fresh network fetch. */
1736
- AgentClient.REMOTE_AGENT_TTL_L2_MS = 5 * 60000; // 5 minutes
1737
1858
 
1738
1859
  var __classPrivateFieldSet$c = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
1739
1860
  if (kind === "m") throw new TypeError("Private method is not writable");
@@ -3023,8 +3144,15 @@ class SfuManager {
3023
3144
  SfuManager.MAX_RECONNECTS = 3;
3024
3145
  /** How long one rebuild keeps retrying a join the executor cannot take yet. */
3025
3146
  SfuManager.REJOIN_WINDOW_MS = 120000;
3026
- /** How long an ICE restart has to bring the connection back before a rebuild. */
3027
- SfuManager.RESTART_TIMEOUT_MS = 5000;
3147
+ /** The executor's wait before the first resend of an unanswered offer.
3148
+ * `OFFER_RETRY_BASE` in `rust-executor/src/sfu/server.rs`. */
3149
+ SfuManager.OFFER_RESEND_BASE_MS = 10000;
3150
+ /** How long ICE has to come back after that resend arrives. */
3151
+ SfuManager.RESTART_AFTER_RESEND_MS = 5000;
3152
+ /** How long an ICE restart has to bring the connection back before a rebuild.
3153
+ * The window stays open through the first resend, then the previous 5 s
3154
+ * for ICE. A restart that connects clears the timer at once. */
3155
+ SfuManager.RESTART_TIMEOUT_MS = SfuManager.OFFER_RESEND_BASE_MS + SfuManager.RESTART_AFTER_RESEND_MS;
3028
3156
  /** How long the roster may leave this session out before the call is rebuilt. */
3029
3157
  SfuManager.UNLISTED_GRACE_MS = 3000;
3030
3158
 
@@ -6017,6 +6145,13 @@ class SHACLShape {
6017
6145
  target: `literal:string:${prop.relationKind}`
6018
6146
  });
6019
6147
  }
6148
+ if (prop.polymorphic) {
6149
+ links.push({
6150
+ source: propShapeId,
6151
+ predicate: "ad4m://polymorphic",
6152
+ target: `literal:${prop.polymorphic}`
6153
+ });
6154
+ }
6020
6155
  if (prop.targetClassName) {
6021
6156
  links.push({
6022
6157
  source: propShapeId,
@@ -6156,6 +6291,7 @@ class SHACLShape {
6156
6291
  in: json(id, "sh://in"),
6157
6292
  relationKind: ['hasMany', 'hasOne', 'belongsToOne', 'belongsToMany'].includes(relationKind)
6158
6293
  ? relationKind : undefined,
6294
+ polymorphic: bool(id, "ad4m://polymorphic"),
6159
6295
  targetClassName: str(id, "ad4m://targetClassName"),
6160
6296
  whereFilter: json(id, "ad4m://whereFilter"),
6161
6297
  wherePredicates: json(id, "ad4m://wherePredicates"),
@@ -6204,6 +6340,7 @@ class SHACLShape {
6204
6340
  class: p.class,
6205
6341
  in: p.in,
6206
6342
  relation_kind: p.relationKind,
6343
+ polymorphic: p.polymorphic,
6207
6344
  collection: p.collection ?? (isCollection(p) || undefined),
6208
6345
  target_class_name: p.targetClassName,
6209
6346
  where_filter: p.whereFilter,
@@ -6258,6 +6395,7 @@ class SHACLShape {
6258
6395
  class: p.class,
6259
6396
  in: p.in,
6260
6397
  relationKind: p.relation_kind,
6398
+ polymorphic: p.polymorphic,
6261
6399
  collection: p.collection,
6262
6400
  targetClassName: p.target_class_name,
6263
6401
  whereFilter: p.where_filter,
@@ -6583,6 +6721,8 @@ isAbstract) {
6583
6721
  // Encode relation kind so the executor can derive direction and
6584
6722
  // scalar-vs-collection rendering without consulting the JS class.
6585
6723
  relShape.relationKind = relMeta.kind;
6724
+ if (relMeta.polymorphic)
6725
+ relShape.polymorphic = true;
6586
6726
  // Scalar relations cap at 1.
6587
6727
  if (relMeta.kind === 'hasOne' || relMeta.kind === 'belongsToOne') {
6588
6728
  relShape.maxCount = 1;
@@ -7643,73 +7783,6 @@ function BelongsToMany(first, second) {
7643
7783
  };
7644
7784
  }
7645
7785
 
7646
- /**
7647
- * Query Result TTL Cache
7648
- *
7649
- * Short-lived cache (200ms TTL) for SPARQL query results.
7650
- * Prevents redundant queries during rapid render cycles where
7651
- * multiple components issue the same query within milliseconds.
7652
- *
7653
- * Key: `perspectiveUUID + queryText`
7654
- */
7655
- const cache = new Map();
7656
- const DEFAULT_TTL_MS = 200;
7657
- function makeKey(perspectiveUUID, queryText) {
7658
- return `${perspectiveUUID}:${queryText}`;
7659
- }
7660
- /**
7661
- * Get a cached query result if it exists and hasn't expired.
7662
- */
7663
- function getCachedResult(perspectiveUUID, queryText) {
7664
- const key = makeKey(perspectiveUUID, queryText);
7665
- const entry = cache.get(key);
7666
- if (!entry)
7667
- return undefined;
7668
- if (Date.now() > entry.expiry) {
7669
- cache.delete(key);
7670
- return undefined;
7671
- }
7672
- return entry.result;
7673
- }
7674
- /**
7675
- * Store a query result in the cache with TTL.
7676
- */
7677
- function setCachedResult(perspectiveUUID, queryText, result, ttlMs = DEFAULT_TTL_MS) {
7678
- // Lazy eviction of expired entries
7679
- const now = Date.now();
7680
- for (const [key, entry] of cache) {
7681
- if (now > entry.expiry) {
7682
- cache.delete(key);
7683
- }
7684
- }
7685
- const cacheKey = makeKey(perspectiveUUID, queryText);
7686
- cache.set(cacheKey, { result, expiry: now + ttlMs });
7687
- }
7688
- /**
7689
- * Invalidate all cache entries for a given perspective.
7690
- * Called after write operations to ensure stale data isn't served.
7691
- */
7692
- function invalidatePerspectiveCache(perspectiveUUID) {
7693
- const prefix = perspectiveUUID + ':';
7694
- for (const [key] of cache) {
7695
- if (key.startsWith(prefix)) {
7696
- cache.delete(key);
7697
- }
7698
- }
7699
- }
7700
- /**
7701
- * Clear all cache entries (useful for testing).
7702
- */
7703
- function clearQueryCache() {
7704
- cache.clear();
7705
- }
7706
- /**
7707
- * Get the current size of the cache (useful for testing).
7708
- */
7709
- function queryCacheSize() {
7710
- return cache.size;
7711
- }
7712
-
7713
7786
  var __classPrivateFieldSet$8 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
7714
7787
  if (kind === "m") throw new TypeError("Private method is not writable");
7715
7788
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
@@ -9085,9 +9158,7 @@ class PerspectiveProxy {
9085
9158
  * @param batchId - Optional batch ID to group this operation with others
9086
9159
  */
9087
9160
  async executeAction(actions, expression, parameters, batchId) {
9088
- 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);
9089
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
9090
- return result;
9161
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").executeCommands(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId);
9091
9162
  }
9092
9163
  /**
9093
9164
  * Retrieves links from the perspective that match the given query.
@@ -9315,12 +9386,15 @@ class PerspectiveProxy {
9315
9386
  return await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").flowStates(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, instances);
9316
9387
  }
9317
9388
  /**
9318
- * The proposals of `instance` whose votes settled an edge, as this
9319
- * agent's executor recorded them — the flow's history, sorted by URI.
9389
+ * For each of `instances`, in order, the proposals whose votes settled an
9390
+ * edge, as this agent's executor recorded them — the flow's history,
9391
+ * sorted by URI (`fired: []` when none). One call covers up to 200
9392
+ * instances (the executor refuses more with a 400); split a longer list
9393
+ * into batches of 200.
9320
9394
  * Replaces the `resolvedAs` property proposals used to carry.
9321
9395
  */
9322
- async flowFired(instance) {
9323
- return await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").flowFired(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, instance);
9396
+ async flowFired(instances) {
9397
+ return await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").flowFired(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, instances);
9324
9398
  }
9325
9399
  /**
9326
9400
  * Called whenever a flow instance on this perspective changes state on
@@ -9384,20 +9458,18 @@ class PerspectiveProxy {
9384
9458
  * keep its blocking thread busy until it completes; what's saved is the
9385
9459
  * serialise + network + client-deserialise tax on the result. Aborted
9386
9460
  * calls reject with `DOMException('Aborted', 'AbortError')` — match
9387
- * `fetch()` for handling. Cached results bypass the round-trip entirely
9388
- * and are returned synchronously, ignoring the signal.
9461
+ * `fetch()` for handling. A call with `options` makes its own RPC.
9462
+ *
9463
+ * **Sharing:** concurrent identical calls without `options` share one RPC;
9464
+ * each caller gets its own result object. Nothing is cached once the
9465
+ * call settles: use a live query for repeated reads of the same data.
9389
9466
  *
9390
9467
  * @param query - SPARQL query string (read-only operations only)
9391
9468
  * @param options - Optional call options (e.g. AbortSignal for cancellation)
9392
9469
  * @returns Query results as parsed JSON
9393
9470
  */
9394
9471
  async querySparql(query, options) {
9395
- const cached = getCachedResult(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, query);
9396
- if (cached !== undefined)
9397
- return cached;
9398
- const result = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").querySparql(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, query, options);
9399
- setCachedResult(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, query, result);
9400
- return result;
9472
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").querySparql(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, query, options);
9401
9473
  }
9402
9474
  /**
9403
9475
  * Execute a model query — the executor-side replacement for SPARQL query building + JS hydration.
@@ -9410,7 +9482,7 @@ class PerspectiveProxy {
9410
9482
  * query over their union, whose rows carry `__subjectClass` and
9411
9483
  * `__subjectClasses` (#1238)
9412
9484
  * @param queryJson - Structured query as JSON string
9413
- * @returns Object with `instances` array and `totalCount`
9485
+ * @returns Object with `instances` array, and `totalCount` when the query sets `count: true`
9414
9486
  */
9415
9487
  async modelQuery(className, queryJson, options) {
9416
9488
  return await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, options);
@@ -9504,9 +9576,7 @@ class PerspectiveProxy {
9504
9576
  * ```
9505
9577
  */
9506
9578
  async add(link, status = 'shared', batchId) {
9507
- const result = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").addLink(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
9508
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
9509
- return result;
9579
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").addLink(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
9510
9580
  }
9511
9581
  /**
9512
9582
  * Adds multiple links to the perspective in a single operation.
@@ -9518,9 +9588,7 @@ class PerspectiveProxy {
9518
9588
  * @returns Array of created LinkExpressions
9519
9589
  */
9520
9590
  async addLinks(links, status = 'shared', batchId) {
9521
- const result = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").addLinks(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, links, status, batchId);
9522
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
9523
- return result;
9591
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").addLinks(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, links, status, batchId);
9524
9592
  }
9525
9593
  /**
9526
9594
  * Removes multiple links from the perspective.
@@ -9530,9 +9598,7 @@ class PerspectiveProxy {
9530
9598
  * @returns Array of removed LinkExpressions
9531
9599
  */
9532
9600
  async removeLinks(links, batchId) {
9533
- const result = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").removeLinks(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, links, batchId);
9534
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
9535
- return result;
9601
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").removeLinks(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, links, batchId);
9536
9602
  }
9537
9603
  /**
9538
9604
  * Applies a set of link mutations (adds and removes) in a single operation.
@@ -9543,9 +9609,7 @@ class PerspectiveProxy {
9543
9609
  * @returns Object containing results of the mutations
9544
9610
  */
9545
9611
  async linkMutations(mutations, status = 'shared') {
9546
- const result = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").linkMutations(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, mutations, status);
9547
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
9548
- return result;
9612
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").linkMutations(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, mutations, status);
9549
9613
  }
9550
9614
  /**
9551
9615
  * Adds a pre-signed LinkExpression to the perspective.
@@ -9572,9 +9636,7 @@ class PerspectiveProxy {
9572
9636
  * @param batchId - Optional batch ID to group this operation with others
9573
9637
  */
9574
9638
  async update(oldLink, newLink, batchId) {
9575
- const result = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").updateLink(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, oldLink, newLink, batchId);
9576
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
9577
- return result;
9639
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").updateLink(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, oldLink, newLink, batchId);
9578
9640
  }
9579
9641
  /**
9580
9642
  * Removes a link from the perspective.
@@ -9620,9 +9682,7 @@ class PerspectiveProxy {
9620
9682
  else {
9621
9683
  resolvedLink = link;
9622
9684
  }
9623
- const result = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, resolvedLink, batchId);
9624
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
9625
- return result;
9685
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, resolvedLink, batchId);
9626
9686
  }
9627
9687
  /** Creates a new batch for grouping operations */
9628
9688
  async createBatch() {
@@ -9630,9 +9690,7 @@ class PerspectiveProxy {
9630
9690
  }
9631
9691
  /** Commits a batch of operations */
9632
9692
  async commitBatch(batchId) {
9633
- const result = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").commitBatch(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, batchId);
9634
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
9635
- return result;
9693
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").commitBatch(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, batchId);
9636
9694
  }
9637
9695
  /**
9638
9696
  * Drops an open batch without committing it — the recovery for a failed batched call:
@@ -10000,13 +10058,13 @@ class PerspectiveProxy {
10000
10058
  return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").getShaclTargetClass(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, name);
10001
10059
  }
10002
10060
  /**
10003
- * Get all SHACL shapes stored in this Perspective (one RPC call).
10004
- * The executor resolves all shapes in-process and returns them in bulk.
10061
+ * Get the SHACL shapes stored in this Perspective in one RPC call: all of
10062
+ * them, or only those named in `names` (unknown names are left out).
10005
10063
  * A shape that fails to decode is skipped with a `console.warn`, so it
10006
10064
  * does not hide the others.
10007
10065
  */
10008
- async getAllShacl() {
10009
- const entries = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").getAllShacl(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10066
+ async getAllShacl(options) {
10067
+ const entries = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").getAllShacl(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, options?.names);
10010
10068
  const shapes = [];
10011
10069
  for (const { name, shapeUri, links } of entries) {
10012
10070
  try {
@@ -10247,7 +10305,6 @@ class PerspectiveProxy {
10247
10305
  * record that the abstract class reads, under its own name. */
10248
10306
  async updateSubject(className, exprAddr, values, batchId) {
10249
10307
  await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").updateSubject(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, className, exprAddr, JSON.stringify(values), batchId);
10250
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10251
10308
  }
10252
10309
  /**
10253
10310
  * Creates an instance of a subject class, validated by the executor against the class's
@@ -10266,42 +10323,23 @@ class PerspectiveProxy {
10266
10323
  * const { baseUri } = await perspective.instanceCreate({ className: "Task", properties: { title: "Write" } });
10267
10324
  */
10268
10325
  async instanceCreate(body) {
10269
- const created = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceCreate(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10270
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10271
- return created;
10326
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceCreate(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10272
10327
  }
10273
10328
  /** Sets single-valued properties of an instance, validated; the others stay. See {@link instanceCreate}. */
10274
10329
  async instanceUpdate(body) {
10275
- const updated = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceUpdate(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10276
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10277
- return updated;
10330
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceUpdate(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10278
10331
  }
10279
10332
  /** Removes an instance and every link to and from it. See {@link instanceCreate}. */
10280
10333
  async instanceRemove(body) {
10281
- // Outside a batch the links go one by one, so a rejection (`partiallyRemoved`) can
10282
- // come after some are gone: invalidate either way.
10283
- try {
10284
- return await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceRemove(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10285
- }
10286
- finally {
10287
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10288
- }
10334
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceRemove(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10289
10335
  }
10290
10336
  /** Adds an item to a collection of an instance, validated. See {@link instanceCreate}. */
10291
10337
  async instanceAddToCollection(body) {
10292
- const added = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceAddToCollection(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10293
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10294
- return added;
10338
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceAddToCollection(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10295
10339
  }
10296
10340
  /** Removes an item from a collection of an instance. See {@link instanceCreate}. */
10297
10341
  async instanceRemoveFromCollection(body) {
10298
- // Like instanceRemove, a rejection can come after some links are gone.
10299
- try {
10300
- return await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceRemoveFromCollection(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10301
- }
10302
- finally {
10303
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10304
- }
10342
+ return __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceRemoveFromCollection(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10305
10343
  }
10306
10344
  async getSubjectData(subjectClass, exprAddr) {
10307
10345
  if (typeof subjectClass === "string") {
@@ -10365,7 +10403,6 @@ class PerspectiveProxy {
10365
10403
  const ctor = subjectClass?.constructor;
10366
10404
  if (typeof subjectClass === "object" && ctor && Object.prototype.hasOwnProperty.call(ctor, 'builtinUri')) {
10367
10405
  await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").removeSubject(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, ctor.builtinUri, exprAddr, batchId);
10368
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10369
10406
  return;
10370
10407
  }
10371
10408
  let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);
@@ -10375,7 +10412,6 @@ class PerspectiveProxy {
10375
10412
  const markers = await this.get(new LinkQuery({ predicate: "ad4m://abstract" }));
10376
10413
  if (markers.some((link) => shapePattern.test(link.data.source))) {
10377
10414
  await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").removeSubject(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, className, exprAddr, batchId);
10378
- invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10379
10415
  return;
10380
10416
  }
10381
10417
  // Get destructor actions from SHACL links (Prolog-free)
@@ -10944,7 +10980,7 @@ var __classPrivateFieldGet$6 = (undefined && undefined.__classPrivateFieldGet) |
10944
10980
  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");
10945
10981
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
10946
10982
  };
10947
- var _PerspectiveClient_instances, _PerspectiveClient_apiClient, _PerspectiveClient_expressionClient, _PerspectiveClient_neighbourhoodClient, _PerspectiveClient_aiClient, _PerspectiveClient_released;
10983
+ var _PerspectiveClient_instances, _PerspectiveClient_apiClient, _PerspectiveClient_expressionClient, _PerspectiveClient_neighbourhoodClient, _PerspectiveClient_aiClient, _PerspectiveClient_sparqlInFlight, _PerspectiveClient_writeGeneration, _PerspectiveClient_wrote, _PerspectiveClient_released;
10948
10984
  /** The wire form of a model query's classes: `class_name` for one, `class_names` for a union. */
10949
10985
  function classParams(className) {
10950
10986
  return Array.isArray(className) ? { class_names: className } : { class_name: className };
@@ -10966,6 +11002,11 @@ class PerspectiveClient {
10966
11002
  _PerspectiveClient_expressionClient.set(this, void 0);
10967
11003
  _PerspectiveClient_neighbourhoodClient.set(this, void 0);
10968
11004
  _PerspectiveClient_aiClient.set(this, void 0);
11005
+ _PerspectiveClient_sparqlInFlight.set(this, new Map()
11006
+ /** Per perspective, how many writes through this client have settled; part of the in-flight key. */
11007
+ );
11008
+ /** Per perspective, how many writes through this client have settled; part of the in-flight key. */
11009
+ _PerspectiveClient_writeGeneration.set(this, new Map());
10969
11010
  __classPrivateFieldSet$6(this, _PerspectiveClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), "f");
10970
11011
  }
10971
11012
  setExpressionClient(client) {
@@ -11025,9 +11066,24 @@ class PerspectiveClient {
11025
11066
  const result = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.queryProlog', { uuid, query }, options);
11026
11067
  return JSON.parse(result);
11027
11068
  }
11069
+ /**
11070
+ * Concurrent identical calls (same perspective and query, no `options`)
11071
+ * share one RPC. Each caller parses its own copy of the reply, and a call
11072
+ * made after the shared one settled makes a new RPC. So does a call made
11073
+ * after a write through this client settled: the shared RPC may have been
11074
+ * answered before the write (see `#wrote`).
11075
+ */
11028
11076
  async querySparql(uuid, query, options) {
11029
- const result = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.querySparql', { uuid, engine: 'sparql', query }, options);
11030
- return JSON.parse(result);
11077
+ if (options)
11078
+ return JSON.parse(await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.querySparql', { uuid, engine: 'sparql', query }, options));
11079
+ const key = `${uuid}\n${__classPrivateFieldGet$6(this, _PerspectiveClient_writeGeneration, "f").get(uuid) ?? 0}\n${query}`;
11080
+ let reply = __classPrivateFieldGet$6(this, _PerspectiveClient_sparqlInFlight, "f").get(key);
11081
+ if (!reply) {
11082
+ reply = __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.querySparql', { uuid, engine: 'sparql', query })
11083
+ .finally(() => __classPrivateFieldGet$6(this, _PerspectiveClient_sparqlInFlight, "f").delete(key));
11084
+ __classPrivateFieldGet$6(this, _PerspectiveClient_sparqlInFlight, "f").set(key, reply);
11085
+ }
11086
+ return JSON.parse(await reply);
11031
11087
  }
11032
11088
  /** Open a live SPARQL query. Updates arrive through {@link onQueryUpdate}. */
11033
11089
  /** `options.signal` cancels the call, and the executor stops computing the first result. */
@@ -11084,19 +11140,19 @@ class PerspectiveClient {
11084
11140
  return { perspectiveRemove: result };
11085
11141
  }
11086
11142
  async addLink(uuid, link, status = 'shared', batchId) {
11087
- const added = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.addLink', { uuid, link, status, batchId });
11143
+ 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 }));
11088
11144
  return LinkExpression.fromWire(added);
11089
11145
  }
11090
11146
  async addLinks(uuid, links, status = 'shared', batchId) {
11091
- const added = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.addLinks', { uuid, links, 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.addLinks', { uuid, links, status, batchId }));
11092
11148
  return added.map(LinkExpression.fromWire);
11093
11149
  }
11094
11150
  async removeLinks(uuid, links, batchId) {
11095
- const removed = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.removeLinks', { uuid, links: links.map(linkExpressionInputToWire), batchId });
11151
+ 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 }));
11096
11152
  return removed.map(LinkExpression.fromWire);
11097
11153
  }
11098
11154
  async linkMutations(uuid, mutations, status) {
11099
- const diff = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.linkMutations', { uuid, mutations: linkMutationsToWire(mutations), status });
11155
+ 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 }));
11100
11156
  return LinkExpressionMutations.fromWire(diff);
11101
11157
  }
11102
11158
  /**
@@ -11116,11 +11172,11 @@ class PerspectiveClient {
11116
11172
  * are NOT re-parented — same rule as the watcher).
11117
11173
  */
11118
11174
  async runInterpretation(uuid, transcript, basePrefix, classes, existingScope, mintScope, observe, options) {
11119
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretation', {
11175
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretation', {
11120
11176
  uuid, transcript, basePrefix, classes, existingScope, mintScope,
11121
11177
  observationId: observe?.observationId,
11122
11178
  emitDebugEvents: observe?.emitDebugEvents,
11123
- }, options);
11179
+ }, options));
11124
11180
  }
11125
11181
  /**
11126
11182
  * Tool-calling counterpart to {@link runInterpretation}. The LLM sees a
@@ -11143,7 +11199,7 @@ class PerspectiveClient {
11143
11199
  // `emitDebugEvents` is a dead-letter without an observationId
11144
11200
  // (nothing to key against); the server gates on both.
11145
11201
  observationId, emitDebugEvents, options) {
11146
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretationWithHarness', {
11202
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretationWithHarness', {
11147
11203
  uuid,
11148
11204
  transcript,
11149
11205
  basePrefix,
@@ -11153,7 +11209,7 @@ class PerspectiveClient {
11153
11209
  existingScope,
11154
11210
  observationId,
11155
11211
  emitDebugEvents,
11156
- }, options);
11212
+ }, options));
11157
11213
  }
11158
11214
  /**
11159
11215
  * A conversation with a model in this perspective, using the executor's own tools: the tools
@@ -11166,7 +11222,9 @@ class PerspectiveClient {
11166
11222
  * calls before it answers.
11167
11223
  */
11168
11224
  async runAgent(uuid, messages, settings, options) {
11169
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.runAgent', { uuid, messages, ...settings }, options);
11225
+ const reply = __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.runAgent', { uuid, messages, ...settings }, options);
11226
+ // Without write tools the session only reads.
11227
+ return settings?.writeTools?.length ? __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, reply) : reply;
11170
11228
  }
11171
11229
  /**
11172
11230
  * Register a neighbourhood auto-processor on this perspective. The executor's
@@ -11177,11 +11235,11 @@ class PerspectiveClient {
11177
11235
  * Returns the processor id.
11178
11236
  */
11179
11237
  async addAutoProcessor(uuid, config) {
11180
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.addAutoProcessor', { ...config, uuid });
11238
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.addAutoProcessor', { ...config, uuid }));
11181
11239
  }
11182
11240
  /** Delete an auto-processor's config. `false` when there was none to delete. */
11183
11241
  async removeAutoProcessor(uuid, processorId) {
11184
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.removeAutoProcessor', { uuid, processorId });
11242
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.removeAutoProcessor', { uuid, processorId }));
11185
11243
  }
11186
11244
  /** Pending interpretation overlays (LLM suggestions awaiting human accept/reject). */
11187
11245
  async interpretationOverlays(uuid) {
@@ -11193,18 +11251,18 @@ class PerspectiveClient {
11193
11251
  /** Accept an overlay's suggestion(s): the LLM value becomes the real value and
11194
11252
  * the overlay is deleted. Omit `property` to accept the whole base. */
11195
11253
  async acceptInterpretation(uuid, base, property) {
11196
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.acceptInterpretation', { uuid, base, property });
11254
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.acceptInterpretation', { uuid, base, property }));
11197
11255
  }
11198
11256
  /** Reject an overlay's suggestion(s). Omit `property` to reject the whole base
11199
11257
  * (a rejected `create` deletes the suggested instance). */
11200
11258
  async rejectInterpretation(uuid, base, property) {
11201
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectInterpretation', { uuid, base, property });
11259
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectInterpretation', { uuid, base, property }));
11202
11260
  }
11203
11261
  async proposeFlowTransition(uuid, instanceUri, toState, rationale, outputs) {
11204
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.proposeFlowTransition', { uuid, instanceUri, toState, rationale, outputs });
11262
+ 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 }));
11205
11263
  }
11206
11264
  async acceptFlowProposal(uuid, proposalUri) {
11207
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.acceptFlowProposal', { uuid, proposalUri });
11265
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.acceptFlowProposal', { uuid, proposalUri }));
11208
11266
  }
11209
11267
  /**
11210
11268
  * Withdraw this agent's own links from a proposal. Resolves to how many
@@ -11212,7 +11270,7 @@ class PerspectiveClient {
11212
11270
  * proposal this agent opened.
11213
11271
  */
11214
11272
  async rejectFlowProposal(uuid, proposalUri) {
11215
- const result = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectFlowProposal', { uuid, proposalUri });
11273
+ 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 }));
11216
11274
  return result.retractedLinks;
11217
11275
  }
11218
11276
  /** Re-decide a flow receipt under this perspective's own flow catalogue. */
@@ -11229,49 +11287,51 @@ class PerspectiveClient {
11229
11287
  async flowStates(uuid, instances) {
11230
11288
  return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.flowStates', { uuid, instances });
11231
11289
  }
11232
- /** The proposals of `instance` the calling agent's replica recorded as
11233
- * fired, sorted. */
11234
- async flowFired(uuid, instance) {
11235
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.flowFired', { uuid, instance });
11290
+ /** For each of `instances`, in order, the proposals the calling agent's
11291
+ * replica recorded as fired, sorted. One call covers up to 200
11292
+ * instances (more is refused with a 400); split a longer list into
11293
+ * batches of 200. */
11294
+ async flowFired(uuid, instances) {
11295
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.flowFired', { uuid, instances });
11236
11296
  }
11237
11297
  /** Mint and store the receipt for a completed flow run. Fails while the
11238
11298
  * run has not settled into a terminal state, and when an output's
11239
11299
  * content no longer matches what the quorum committed to. */
11240
11300
  async mintFlowReceipt(uuid, instanceUri) {
11241
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.mintFlowReceipt', { uuid, instanceUri });
11301
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.mintFlowReceipt', { uuid, instanceUri }));
11242
11302
  }
11243
11303
  async addLinkExpression(uuid, link, status = 'shared', batchId) {
11244
- const added = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.addLinkExpression', { uuid, link: linkExpressionToWire(link), status, batchId });
11304
+ 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 }));
11245
11305
  return LinkExpression.fromWire(added);
11246
11306
  }
11247
11307
  async updateLink(uuid, oldLink, newLink, batchId) {
11248
- const updated = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.updateLink', { uuid, oldLink: linkExpressionInputToWire(oldLink), newLink, batchId });
11308
+ 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 }));
11249
11309
  return LinkExpression.fromWire(updated);
11250
11310
  }
11251
11311
  async removeLink(uuid, link, batchId) {
11252
11312
  const { status, ...wire } = linkExpressionInputToWire(link);
11253
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.removeLink', { uuid, link: wire, batchId });
11313
+ 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 }));
11254
11314
  }
11255
11315
  async addSdna(uuid, name, sdnaCode, sdnaType, shaclJson) {
11256
- const result = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.addSdna', { uuid, name, sdnaCode: sdnaCode || "", sdnaType, shaclJson });
11316
+ 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 }));
11257
11317
  return typeof result === 'boolean' ? result : result.every(Boolean);
11258
11318
  }
11259
11319
  async addSdnaBatch(uuid, entries) {
11260
- const result = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.addSdna', { uuid, entries: entries.map(e => ({ ...e, sdnaCode: e.sdnaCode || "" })) });
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, entries: entries.map(e => ({ ...e, sdnaCode: e.sdnaCode || "" })) }));
11261
11321
  return typeof result === 'boolean' ? [result] : result;
11262
11322
  }
11263
11323
  async executeCommands(uuid, commands, expression, parameters, batchId) {
11264
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.executeCommands', { uuid, commands, expression, parameters, batchId });
11324
+ 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 }));
11265
11325
  }
11266
11326
  async createSubject(uuid, subjectClass, expressionAddress, initialValues, batchId) {
11267
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.createSubject', { uuid, subjectClass, expressionAddress, initialValues, batchId });
11327
+ 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 }));
11268
11328
  }
11269
11329
  /** Through an abstract class (#1435), the executor writes to the record's own classes. */
11270
11330
  async updateSubject(uuid, subjectClass, expressionAddress, values, batchId) {
11271
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.updateSubject', { uuid, subjectClass, expressionAddress, values, batchId });
11331
+ 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 }));
11272
11332
  }
11273
11333
  async removeSubject(uuid, subjectClass, expressionAddress, batchId) {
11274
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.removeSubject', { uuid, subjectClass, expressionAddress, batchId });
11334
+ 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 }));
11275
11335
  }
11276
11336
  /**
11277
11337
  * Validated writes (`perspective.instance*`): the executor checks each against the class's
@@ -11291,23 +11351,23 @@ class PerspectiveClient {
11291
11351
  * it to keep the calls that succeeded.
11292
11352
  */
11293
11353
  async instanceCreate(uuid, body) {
11294
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceCreate', { uuid, ...body });
11354
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceCreate', { uuid, ...body }));
11295
11355
  }
11296
11356
  /** Sets the given single-valued properties; the others stay. See {@link instanceCreate}. */
11297
11357
  async instanceUpdate(uuid, body) {
11298
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceUpdate', { uuid, ...body });
11358
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceUpdate', { uuid, ...body }));
11299
11359
  }
11300
11360
  /** Removes the instance and every link to and from it. See {@link instanceCreate}. */
11301
11361
  async instanceRemove(uuid, body) {
11302
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceRemove', { uuid, ...body });
11362
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceRemove', { uuid, ...body }));
11303
11363
  }
11304
11364
  /** Adds an item to a collection (a no-op when it is a member). See {@link instanceCreate}. */
11305
11365
  async instanceAddToCollection(uuid, body) {
11306
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceAddToCollection', { uuid, ...body });
11366
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceAddToCollection', { uuid, ...body }));
11307
11367
  }
11308
11368
  /** Removes an item's membership link from a collection. See {@link instanceCreate}. */
11309
11369
  async instanceRemoveFromCollection(uuid, body) {
11310
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceRemoveFromCollection', { uuid, ...body });
11370
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_wrote).call(this, uuid, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceRemoveFromCollection', { uuid, ...body }));
11311
11371
  }
11312
11372
  async getSubjectData(uuid, subjectClass, expressionAddress) {
11313
11373
  return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.getSubjectData', { uuid, subjectClass, expressionAddress });
@@ -11343,11 +11403,12 @@ class PerspectiveClient {
11343
11403
  return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.getShacl', { uuid, name });
11344
11404
  }
11345
11405
  /**
11346
- * Retrieve all SHACL shapes in one call. Returns an array of
11347
- * `{name, shapeUri, links}` — one entry per shape (one RPC call).
11406
+ * Retrieve SHACL shapes in one call: every shape, or only those in
11407
+ * `names` (unknown names are left out). Returns `{name, shapeUri, links}`
11408
+ * per shape.
11348
11409
  */
11349
- async getAllShacl(uuid) {
11350
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.getAllShacl', { uuid });
11410
+ async getAllShacl(uuid, names) {
11411
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.getAllShacl', { uuid, names });
11351
11412
  }
11352
11413
  // ExpressionClient functions, needed for Subjects:
11353
11414
  async getExpression(expressionURI) {
@@ -11367,7 +11428,7 @@ class PerspectiveClient {
11367
11428
  return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.createBatch', { uuid });
11368
11429
  }
11369
11430
  async commitBatch(uuid, batchId) {
11370
- const diff = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.commitBatch', { uuid, batchId });
11431
+ 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 }));
11371
11432
  return LinkExpressionMutations.fromWire(diff);
11372
11433
  }
11373
11434
  /**
@@ -11385,7 +11446,21 @@ class PerspectiveClient {
11385
11446
  return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").onReconnect(callback);
11386
11447
  }
11387
11448
  }
11388
- _PerspectiveClient_apiClient = new WeakMap(), _PerspectiveClient_expressionClient = new WeakMap(), _PerspectiveClient_neighbourhoodClient = new WeakMap(), _PerspectiveClient_aiClient = new WeakMap(), _PerspectiveClient_instances = new WeakSet(), _PerspectiveClient_released =
11449
+ _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 =
11450
+ /**
11451
+ * Await a write to `uuid`, then start a new write generation for it
11452
+ * (also when the write failed: it may still have changed the perspective).
11453
+ * Calls of {@link querySparql} already waiting keep sharing their RPC; an
11454
+ * identical call started from now on makes its own.
11455
+ */
11456
+ async function _PerspectiveClient_wrote(uuid, write) {
11457
+ try {
11458
+ return await write;
11459
+ }
11460
+ finally {
11461
+ __classPrivateFieldGet$6(this, _PerspectiveClient_writeGeneration, "f").set(uuid, (__classPrivateFieldGet$6(this, _PerspectiveClient_writeGeneration, "f").get(uuid) ?? 0) + 1);
11462
+ }
11463
+ }, _PerspectiveClient_released =
11389
11464
  /** A subscribe call that failed (timed out, aborted, refused) leaves no live
11390
11465
  * query on the executor that nobody holds. The client minted its id, so it
11391
11466
  * disposes it without the reply. A timeout or an abort sends `request.cancel`
@@ -11633,112 +11708,59 @@ var __classPrivateFieldGet$4 = (undefined && undefined.__classPrivateFieldGet) |
11633
11708
  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");
11634
11709
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11635
11710
  };
11636
- var _ExpressionClient_instances, _ExpressionClient_apiClient, _ExpressionClient_memCache, _ExpressionClient_inflight, _ExpressionClient_totalMemBytes, _ExpressionClient_persistent, _ExpressionClient_memCacheResult;
11711
+ var _ExpressionClient_apiClient, _ExpressionClient_expressions;
11712
+ /** Most URLs the executor takes in one `expression.getMany` call. */
11713
+ const MAX_URLS_PER_CALL = 200;
11637
11714
  class ExpressionClient {
11638
11715
  constructor(baseUrl, token, sharedApiClient) {
11639
- _ExpressionClient_instances.add(this);
11640
11716
  _ExpressionClient_apiClient.set(this, void 0);
11641
- // L1: in-memory LRU cache (hot path, sub-ms)
11642
- _ExpressionClient_memCache.set(this, new Map());
11643
- _ExpressionClient_inflight.set(this, new Map());
11644
- _ExpressionClient_totalMemBytes.set(this, 0);
11645
- // L2: persistent cache (IndexedDB in browser, NullCache in Node)
11646
- _ExpressionClient_persistent.set(this, void 0);
11717
+ // A `get` miss is its own `expression.get`, so it waits for no slower
11718
+ // expression and has its own call timeout. The misses of the `getMany`
11719
+ // calls made in one tick go out in `expression.getMany` calls of at most
11720
+ // MAX_URLS_PER_CALL URLs, which answer per URL what `expression.get` would.
11721
+ _ExpressionClient_expressions.set(this, void 0);
11647
11722
  __classPrivateFieldSet$4(this, _ExpressionClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), "f");
11648
- __classPrivateFieldSet$4(this, _ExpressionClient_persistent, createPersistentCache('ad4m-expression-cache', 'expressions'), "f");
11723
+ __classPrivateFieldSet$4(this, _ExpressionClient_expressions, new KeyedCache({
11724
+ load: (url) => __classPrivateFieldGet$4(this, _ExpressionClient_apiClient, "f").call('expression.get', { url }),
11725
+ 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),
11726
+ maxBatch: MAX_URLS_PER_CALL,
11727
+ persistent: createPersistentCache('ad4m-expression-cache', 'expressions'),
11728
+ maxAgeMs: () => ExpressionClient.EXPRESSION_TTL_MS,
11729
+ persistentMaxAgeMs: () => ExpressionClient.EXPRESSION_TTL_MS,
11730
+ limits: () => ({ entries: ExpressionClient.MAX_MEM_ENTRIES, bytes: ExpressionClient.MAX_MEM_BYTES }),
11731
+ }), "f");
11649
11732
  }
11733
+ /** The expression at `url`; `alwaysGet` skips the literal fast path and the cache. */
11650
11734
  async get(url, alwaysGet = false) {
11651
- // Existing literal fast-path
11652
- if (!alwaysGet) {
11653
- try {
11654
- let literalValue = Literal.fromUrl(url).get();
11655
- if (typeof literalValue === 'object' && literalValue !== null) {
11656
- if ('author' in literalValue && 'timestamp' in literalValue && 'data' in literalValue && 'proof' in literalValue) {
11657
- return literalValue;
11658
- }
11659
- }
11660
- }
11661
- catch (e) { }
11662
- }
11663
- // L1: memory hit
11664
- if (!alwaysGet) {
11665
- const memHit = __classPrivateFieldGet$4(this, _ExpressionClient_memCache, "f").get(url);
11666
- if (memHit)
11667
- return memHit.data;
11668
- }
11669
- // Deduplicate in-flight requests
11670
- if (!alwaysGet) {
11671
- const existing = __classPrivateFieldGet$4(this, _ExpressionClient_inflight, "f").get(url);
11672
- if (existing)
11673
- return existing;
11674
- }
11675
- // L2 check + L3 network
11676
- const promise = (async () => {
11677
- if (!alwaysGet) {
11678
- const persisted = await __classPrivateFieldGet$4(this, _ExpressionClient_persistent, "f").get(url);
11679
- if (persisted) {
11680
- __classPrivateFieldGet$4(this, _ExpressionClient_instances, "m", _ExpressionClient_memCacheResult).call(this, url, persisted); // promote to L1
11681
- return persisted;
11682
- }
11683
- }
11684
- // L3: network fetch
11735
+ if (alwaysGet) {
11685
11736
  const result = await __classPrivateFieldGet$4(this, _ExpressionClient_apiClient, "f").call('expression.get', { url });
11686
- __classPrivateFieldGet$4(this, _ExpressionClient_instances, "m", _ExpressionClient_memCacheResult).call(this, url, result);
11687
- __classPrivateFieldGet$4(this, _ExpressionClient_persistent, "f").put(url, result); // fire-and-forget write to L2
11737
+ if (result)
11738
+ __classPrivateFieldGet$4(this, _ExpressionClient_expressions, "f").set(url, result);
11688
11739
  return result;
11689
- })();
11690
- __classPrivateFieldGet$4(this, _ExpressionClient_inflight, "f").set(url, promise);
11691
- try {
11692
- return await promise;
11693
11740
  }
11694
- finally {
11695
- __classPrivateFieldGet$4(this, _ExpressionClient_inflight, "f").delete(url);
11741
+ try {
11742
+ let literalValue = Literal.fromUrl(url).get();
11743
+ if (typeof literalValue === 'object' && literalValue !== null) {
11744
+ if ('author' in literalValue && 'timestamp' in literalValue && 'data' in literalValue && 'proof' in literalValue) {
11745
+ return literalValue;
11746
+ }
11747
+ }
11696
11748
  }
11749
+ catch (e) { }
11750
+ return __classPrivateFieldGet$4(this, _ExpressionClient_expressions, "f").get(url);
11697
11751
  }
11752
+ /**
11753
+ * The expressions at `urls`, in order (`null` when not found); the misses go
11754
+ * out in calls of at most 200 URLs. Rejects with the `RpcError` `get` gives when a URL's read fails.
11755
+ */
11698
11756
  async getMany(urls) {
11699
- // Check L1 first
11700
- const results = urls.map(u => __classPrivateFieldGet$4(this, _ExpressionClient_memCache, "f").get(u)?.data ?? null);
11701
- let uncachedIndices = results
11702
- .map((r, i) => r === null ? i : -1)
11703
- .filter(i => i >= 0);
11704
- if (uncachedIndices.length === 0)
11705
- return results;
11706
- // Check L2 for remaining misses
11707
- const l2Results = await Promise.all(uncachedIndices.map(i => __classPrivateFieldGet$4(this, _ExpressionClient_persistent, "f").get(urls[i])));
11708
- const stillMissing = [];
11709
- for (let j = 0; j < uncachedIndices.length; j++) {
11710
- const idx = uncachedIndices[j];
11711
- if (l2Results[j]) {
11712
- results[idx] = l2Results[j];
11713
- __classPrivateFieldGet$4(this, _ExpressionClient_instances, "m", _ExpressionClient_memCacheResult).call(this, urls[idx], l2Results[j]); // promote to L1
11714
- }
11715
- else {
11716
- stillMissing.push(idx);
11717
- }
11718
- }
11719
- if (stillMissing.length === 0)
11720
- return results;
11721
- // L3: fetch only truly uncached URLs
11722
- const uncachedUrls = stillMissing.map(i => urls[i]);
11723
- const fetched = await __classPrivateFieldGet$4(this, _ExpressionClient_apiClient, "f").call('expression.getMany', { urls: uncachedUrls });
11724
- for (let i = 0; i < stillMissing.length; i++) {
11725
- const idx = stillMissing[i];
11726
- results[idx] = fetched[i];
11727
- if (fetched[i]) {
11728
- __classPrivateFieldGet$4(this, _ExpressionClient_instances, "m", _ExpressionClient_memCacheResult).call(this, uncachedUrls[i], fetched[i]);
11729
- __classPrivateFieldGet$4(this, _ExpressionClient_persistent, "f").put(uncachedUrls[i], fetched[i]); // fire-and-forget
11730
- }
11731
- }
11732
- return results;
11757
+ return __classPrivateFieldGet$4(this, _ExpressionClient_expressions, "f").getMany(urls);
11733
11758
  }
11734
11759
  /**
11735
- * Clear both L1 (memory) and L2 (persistent) expression caches.
11760
+ * Clear both the memory and the persistent expression caches.
11736
11761
  */
11737
11762
  clearCache() {
11738
- __classPrivateFieldGet$4(this, _ExpressionClient_memCache, "f").clear();
11739
- __classPrivateFieldGet$4(this, _ExpressionClient_inflight, "f").clear();
11740
- __classPrivateFieldSet$4(this, _ExpressionClient_totalMemBytes, 0, "f");
11741
- __classPrivateFieldGet$4(this, _ExpressionClient_persistent, "f").clear(); // fire-and-forget
11763
+ __classPrivateFieldGet$4(this, _ExpressionClient_expressions, "f").clear(true);
11742
11764
  }
11743
11765
  async getRaw(url) {
11744
11766
  return __classPrivateFieldGet$4(this, _ExpressionClient_apiClient, "f").call('expression.getRaw', { url });
@@ -11753,31 +11775,21 @@ class ExpressionClient {
11753
11775
  async interact(url, interactionCall) {
11754
11776
  const result = await __classPrivateFieldGet$4(this, _ExpressionClient_apiClient, "f").call('expression.interact', { url, interactionCall });
11755
11777
  // Interactions can mutate the expression — invalidate cache so next get() fetches fresh
11756
- __classPrivateFieldGet$4(this, _ExpressionClient_memCache, "f").delete(url);
11757
- __classPrivateFieldGet$4(this, _ExpressionClient_inflight, "f").delete(url);
11758
- __classPrivateFieldGet$4(this, _ExpressionClient_persistent, "f").delete(url); // fire-and-forget
11778
+ __classPrivateFieldGet$4(this, _ExpressionClient_expressions, "f").delete(url);
11759
11779
  return result;
11760
11780
  }
11761
11781
  }
11762
- _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) {
11763
- const size = JSON.stringify(data).length;
11764
- // Evict oldest entries if we'd exceed limits
11765
- while (__classPrivateFieldGet$4(this, _ExpressionClient_memCache, "f").size >= ExpressionClient.MAX_MEM_ENTRIES ||
11766
- __classPrivateFieldGet$4(this, _ExpressionClient_totalMemBytes, "f") + size > ExpressionClient.MAX_MEM_BYTES) {
11767
- const oldest = __classPrivateFieldGet$4(this, _ExpressionClient_memCache, "f").keys().next().value;
11768
- if (!oldest)
11769
- break;
11770
- const entry = __classPrivateFieldGet$4(this, _ExpressionClient_memCache, "f").get(oldest);
11771
- __classPrivateFieldSet$4(this, _ExpressionClient_totalMemBytes, __classPrivateFieldGet$4(this, _ExpressionClient_totalMemBytes, "f") - entry.size, "f");
11772
- __classPrivateFieldGet$4(this, _ExpressionClient_memCache, "f").delete(oldest);
11773
- }
11774
- __classPrivateFieldGet$4(this, _ExpressionClient_memCache, "f").set(url, { data, size });
11775
- __classPrivateFieldSet$4(this, _ExpressionClient_totalMemBytes, __classPrivateFieldGet$4(this, _ExpressionClient_totalMemBytes, "f") + size, "f");
11776
- };
11777
- /** Maximum number of entries in the L1 memory cache. */
11782
+ _ExpressionClient_apiClient = new WeakMap(), _ExpressionClient_expressions = new WeakMap();
11783
+ /** Maximum number of expressions kept in memory. */
11778
11784
  ExpressionClient.MAX_MEM_ENTRIES = 200;
11779
- /** Maximum total size (in bytes) of L1 memory cache values. */
11785
+ /** Maximum total size (in bytes of JSON) of the expressions kept in memory. */
11780
11786
  ExpressionClient.MAX_MEM_BYTES = 5 * 1024 * 1024; // 5 MB
11787
+ /**
11788
+ * TTL of every cached expression, in memory and in the persistent cache
11789
+ * (ms). A language may change what a URL returns, and no event tells the
11790
+ * client, so a cached expression expires instead of staying stale.
11791
+ */
11792
+ ExpressionClient.EXPRESSION_TTL_MS = 5 * 60000; // 5 minutes
11781
11793
 
11782
11794
  var base64Js = {};
11783
11795
 
@@ -19294,6 +19306,18 @@ function isIncludeProjection(val) {
19294
19306
  /**
19295
19307
  * Shared query helpers used by both the Prolog and SPARQL query pipelines.
19296
19308
  */
19309
+ /**
19310
+ * The `totalCount` of a model query sent with `count: true`. The executor
19311
+ * answers such a query with a count, so an answer without one is an error,
19312
+ * not zero matches.
19313
+ */
19314
+ function requireTotalCount(answer) {
19315
+ const totalCount = answer?.totalCount;
19316
+ if (typeof totalCount !== "number") {
19317
+ throw new Error("model query asked for a count (count: true) but the answer has no totalCount");
19318
+ }
19319
+ return totalCount;
19320
+ }
19297
19321
  /**
19298
19322
  * Resolves the predicate for a parent query.
19299
19323
  *
@@ -20376,12 +20400,17 @@ class ModelQueryBuilder {
20376
20400
  return { live, initial: await live.start() };
20377
20401
  }
20378
20402
  catch (e) {
20379
- live.dispose();
20380
- if (this.currentSubscription === live)
20381
- this.currentSubscription = undefined;
20403
+ this.endFailed(live);
20382
20404
  throw e;
20383
20405
  }
20384
20406
  }
20407
+ /** End `live` after its call failed. A later call may already own
20408
+ * `currentSubscription`, so only clear it if it is still `live`. */
20409
+ endFailed(live) {
20410
+ live.dispose();
20411
+ if (this.currentSubscription === live)
20412
+ this.currentSubscription = undefined;
20413
+ }
20385
20414
  /**
20386
20415
  * Adds where conditions to the query.
20387
20416
  *
@@ -20768,8 +20797,7 @@ class ModelQueryBuilder {
20768
20797
  * ```
20769
20798
  */
20770
20799
  async count() {
20771
- const { totalCount } = await this.execute({ ...this.queryParams, limit: 0 });
20772
- return totalCount;
20800
+ return requireTotalCount(await this.execute({ ...this.queryParams, limit: 0, count: true }));
20773
20801
  }
20774
20802
  /**
20775
20803
  * Gets the total count of matching entities using SPARQL.
@@ -20808,8 +20836,23 @@ class ModelQueryBuilder {
20808
20836
  */
20809
20837
  async countSubscribe(callback) {
20810
20838
  this.dispose();
20811
- const { initial } = await this.live({ ...this.queryParams, limit: 0 }, (raw) => callback(raw.totalCount ?? 0));
20812
- return initial.totalCount ?? 0;
20839
+ // As paginateSubscribe: a push without the asked-for count is logged and
20840
+ // skipped, since a throw here would reach the client's update dispatch.
20841
+ const { live, initial } = await this.live({ ...this.queryParams, limit: 0, count: true }, (raw) => {
20842
+ try {
20843
+ callback(requireTotalCount(raw));
20844
+ }
20845
+ catch (e) {
20846
+ console.error('Count subscription error:', e);
20847
+ }
20848
+ });
20849
+ try {
20850
+ return requireTotalCount(initial);
20851
+ }
20852
+ catch (e) {
20853
+ this.endFailed(live);
20854
+ throw e;
20855
+ }
20813
20856
  }
20814
20857
  /**
20815
20858
  * Subscribes to count updates using SPARQL.
@@ -20835,8 +20878,8 @@ class ModelQueryBuilder {
20835
20878
  */
20836
20879
  async paginate(pageSize, pageNumber) {
20837
20880
  const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
20838
- const { results, totalCount } = await this.execute(paginationQuery);
20839
- return { results, totalCount, pageSize, pageNumber };
20881
+ const answer = await this.execute(paginationQuery);
20882
+ return { results: answer.results, totalCount: requireTotalCount(answer), pageSize, pageNumber };
20840
20883
  }
20841
20884
  /**
20842
20885
  * Gets a page of results using SPARQL.
@@ -20899,9 +20942,10 @@ class ModelQueryBuilder {
20899
20942
  const results = this.parse(raw);
20900
20943
  const fp = fingerprint([results, raw?.totalCount]);
20901
20944
  this.takeSnapshots(results);
20902
- return { page: { results, totalCount: raw?.totalCount, pageSize, pageNumber }, fp };
20945
+ // `count: true` is set above, so the executor sends a total.
20946
+ return { page: { results, totalCount: requireTotalCount(raw), pageSize, pageNumber }, fp };
20903
20947
  };
20904
- const { initial } = await this.live(paginatedQuery, (raw) => {
20948
+ const { live, initial } = await this.live(paginatedQuery, (raw) => {
20905
20949
  try {
20906
20950
  const { page, fp } = toPage(raw);
20907
20951
  if (fp === lastFingerprint)
@@ -20913,9 +20957,16 @@ class ModelQueryBuilder {
20913
20957
  console.error('Paginate subscription error:', e);
20914
20958
  }
20915
20959
  });
20916
- const { page, fp } = toPage(initial);
20917
- lastFingerprint = fp;
20918
- return page;
20960
+ let first;
20961
+ try {
20962
+ first = toPage(initial);
20963
+ }
20964
+ catch (e) {
20965
+ this.endFailed(live);
20966
+ throw e;
20967
+ }
20968
+ lastFingerprint = first.fp;
20969
+ return first.page;
20919
20970
  }
20920
20971
  /**
20921
20972
  * Subscribes to paginated results updates using SPARQL.
@@ -20991,7 +21042,8 @@ const SUBJECT_CLASS_KEY = '__subjectClass';
20991
21042
  * The walk stops descending *through* a polymorphic relation, because there is
20992
21043
  * nothing to descend into: its targets are of several classes by definition, so
20993
21044
  * no single class's metadata could say what a deeper include means. The
20994
- * executor resolves those nested includes against each concrete class instead.
21045
+ * executor applies each concrete class's declared default from its shape
21046
+ * (`ad4m://polymorphic`) to those nested includes instead.
20995
21047
  */
20996
21048
  function applyPolymorphicIncludeDefaults(includes, ctor) {
20997
21049
  const relMeta = getRelationsMetadata(ctor);
@@ -21288,6 +21340,8 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
21288
21340
  }
21289
21341
  return instance;
21290
21342
  }
21343
+ /** The most writes `sendWrites` joins into one `executeAction` call. */
21344
+ const MAX_WRITES_PER_CALL = 200;
21291
21345
  /**
21292
21346
  * Put `childId` under `parent`. A containment scope `{ id }` writes through the
21293
21347
  * built-in `Container` (#1446): the executor runs the adder of the parent's own
@@ -22343,8 +22397,8 @@ class Ad4mModel {
22343
22397
  * ```
22344
22398
  */
22345
22399
  static async findAllAndCount(perspective, query, options) {
22346
- const out = await this.executeModelQuery(perspective, (query ?? {}), undefined, options);
22347
- return out;
22400
+ const answer = await this.executeModelQuery(perspective, { ...(query ?? {}), count: true }, undefined, options);
22401
+ return { results: answer.results, totalCount: requireTotalCount(answer) };
22348
22402
  }
22349
22403
  /**
22350
22404
  * Helper function for pagination with explicit page size and number.
@@ -22365,8 +22419,8 @@ class Ad4mModel {
22365
22419
  */
22366
22420
  static async paginate(perspective, pageSize, pageNumber, query, options) {
22367
22421
  const paginationQuery = { ...(query ?? {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
22368
- const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery, undefined, options);
22369
- return { results: results, totalCount, pageSize, pageNumber };
22422
+ const answer = await this.executeModelQuery(perspective, paginationQuery, undefined, options);
22423
+ return { results: answer.results, totalCount: requireTotalCount(answer), pageSize, pageNumber };
22370
22424
  }
22371
22425
  /**
22372
22426
  * Generates a SPARQL COUNT query for the model.
@@ -22394,20 +22448,20 @@ class Ad4mModel {
22394
22448
  * ```
22395
22449
  */
22396
22450
  static async count(perspective, query, options) {
22397
- const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 }, undefined, options);
22398
- return totalCount;
22451
+ return requireTotalCount(await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0, count: true }, undefined, options));
22399
22452
  }
22400
- async setProperty(key, value, batchId) {
22453
+ /** The `executeAction` write that sets property `key` to `value`; none for an empty value. */
22454
+ async planProperty(key, value) {
22401
22455
  const metadata = this.getPropertyMetadata(key);
22402
22456
  if (!metadata) {
22403
22457
  console.warn(`Property "${key}" has no metadata, skipping`);
22404
- return;
22458
+ return [];
22405
22459
  }
22406
22460
  // Generate actions from metadata (replaces Prolog query)
22407
22461
  const actions = this.generatePropertySetterAction(key, metadata);
22408
22462
  // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal:string:)
22409
22463
  if (value === undefined || value === null || value === "") {
22410
- return;
22464
+ return [];
22411
22465
  }
22412
22466
  const mode = effectiveLiteralStorage(metadata);
22413
22467
  if (mode.kind === "custom") {
@@ -22422,7 +22476,77 @@ class Ad4mModel {
22422
22476
  // Deterministic literal: IRI (POS-index friendly).
22423
22477
  value = valueToLiteralIri(value);
22424
22478
  }
22425
- await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value }], batchId);
22479
+ return [{ commands: actions, parameters: [{ name: "value", value }] }];
22480
+ }
22481
+ /**
22482
+ * The `executeAction` writes of a relation change: one for a set (its
22483
+ * `collectionSetter` takes every value), one per value for an add or remove.
22484
+ */
22485
+ planRelation(key, kind, value) {
22486
+ const metadata = this.getRelationOptions(key);
22487
+ if (!metadata) {
22488
+ console.warn(`Relation "${key}" has no metadata, skipping`);
22489
+ return [];
22490
+ }
22491
+ // Generate actions from metadata (replaces Prolog query)
22492
+ const actions = this.generateRelationAction(key, kind);
22493
+ if (value == null)
22494
+ return [];
22495
+ const values = Array.isArray(value) ? value : [value];
22496
+ const param = (v) => ({ name: "value", value: this.resolveRelationId(v) });
22497
+ if (kind === 'setter')
22498
+ return [{ commands: actions, parameters: values.map(param) }];
22499
+ return values.map(v => ({ commands: actions, parameters: [param(v)] }));
22500
+ }
22501
+ /**
22502
+ * Sends writes in as few `executeAction` calls as keep their links: the
22503
+ * executor runs a call's commands in order, so consecutive writes share one
22504
+ * call, each with its own parameter names. A `collectionSetter` takes every
22505
+ * parameter of its call as a member, so it goes in a call of its own. A
22506
+ * command's `local` flag is per command, so Local and Shared links mix. The
22507
+ * executor tries every parameter name at each position of each command, so
22508
+ * a call holds at most `MAX_WRITES_PER_CALL` writes.
22509
+ */
22510
+ async sendWrites(writes, batchId) {
22511
+ let group = [];
22512
+ const flush = async () => {
22513
+ if (group.length === 1) {
22514
+ await this._perspective.executeAction(group[0].commands, this._baseExpression, group[0].parameters, batchId);
22515
+ }
22516
+ else if (group.length > 1) {
22517
+ const commands = [];
22518
+ const parameters = [];
22519
+ group.forEach((write, i) => {
22520
+ // The executor substitutes a parameter name wherever it occurs in a
22521
+ // command's source, predicate or target; rename `value` the same way.
22522
+ const name = `ad4m-model-write-${i}-value`;
22523
+ const rename = (s) => (typeof s === "string" && write.parameters.length ? s.split("value").join(name) : s);
22524
+ for (const c of write.commands) {
22525
+ commands.push({ ...c, source: rename(c.source), predicate: rename(c.predicate), target: rename(c.target) });
22526
+ }
22527
+ for (const p of write.parameters)
22528
+ parameters.push({ name, value: p.value });
22529
+ });
22530
+ await this._perspective.executeAction(commands, this._baseExpression, parameters, batchId);
22531
+ }
22532
+ group = [];
22533
+ };
22534
+ for (const write of writes) {
22535
+ if (write.commands.some((c) => c.action === "collectionSetter")) {
22536
+ await flush();
22537
+ group = [write];
22538
+ await flush();
22539
+ }
22540
+ else {
22541
+ group.push(write);
22542
+ if (group.length >= MAX_WRITES_PER_CALL)
22543
+ await flush();
22544
+ }
22545
+ }
22546
+ await flush();
22547
+ }
22548
+ async setProperty(key, value, batchId) {
22549
+ await this.sendWrites(await this.planProperty(key, value), batchId);
22426
22550
  }
22427
22551
  /** Resolve a relation argument to a plain string ID. Accepts either a raw
22428
22552
  * string ID or an Ad4mModel instance (in which case `.id` is used). */
@@ -22442,75 +22566,33 @@ class Ad4mModel {
22442
22566
  await this._perspective.updateSubject(abstractName, this._baseExpression, { [key]: { action, value: ids } }, batchId);
22443
22567
  }
22444
22568
  async setRelationValues(key, value, batchId) {
22445
- const metadata = this.getRelationOptions(key);
22446
- if (!metadata) {
22447
- console.warn(`Relation "${key}" has no metadata, skipping`);
22448
- return;
22449
- }
22450
- this._relationsWritten.add(metadata.predicate);
22451
- const abstractName = this.abstractName();
22452
- if (abstractName) {
22453
- if (value != null)
22454
- await this.relationThroughAbstract(abstractName, key, 'setter', value, batchId);
22455
- return;
22456
- }
22457
- // Generate actions from metadata (replaces Prolog query)
22458
- const actions = this.generateRelationAction(key, 'setter');
22459
- if (value != null) {
22460
- if (Array.isArray(value)) {
22461
- await this._perspective.executeAction(actions, this._baseExpression, value.map((v) => ({ name: "value", value: this.resolveRelationId(v) })), batchId);
22462
- }
22463
- else {
22464
- await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(value) }], batchId);
22465
- }
22466
- }
22569
+ await this.writeRelation(key, 'setter', value, batchId);
22467
22570
  }
22468
22571
  async addRelationValue(key, value, batchId) {
22469
- const metadata = this.getRelationOptions(key);
22470
- if (!metadata) {
22471
- console.warn(`Relation "${key}" has no metadata, skipping`);
22472
- return;
22473
- }
22474
- this._relationsWritten.add(metadata.predicate);
22475
- const abstractName = this.abstractName();
22476
- if (abstractName) {
22477
- if (value != null)
22478
- await this.relationThroughAbstract(abstractName, key, 'adder', value, batchId);
22479
- return;
22480
- }
22481
- // Generate actions from metadata (replaces Prolog query)
22482
- const actions = this.generateRelationAction(key, 'adder');
22483
- if (value != null) {
22484
- if (Array.isArray(value)) {
22485
- await Promise.all(value.map((v) => this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(v) }], batchId)));
22486
- }
22487
- else {
22488
- await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(value) }], batchId);
22489
- }
22490
- }
22572
+ await this.writeRelation(key, 'adder', value, batchId);
22491
22573
  }
22492
22574
  async removeRelationValue(key, value, batchId) {
22493
- const metadata = this.getRelationOptions(key);
22494
- if (!metadata) {
22495
- console.warn(`Relation "${key}" has no metadata, skipping`);
22496
- return;
22497
- }
22575
+ await this.writeRelation(key, 'remover', value, batchId);
22576
+ }
22577
+ /** A relation setter, adder or remover call: on a row read through an
22578
+ * abstract class it dispatches through the executor (see
22579
+ * {@link relationThroughAbstract}); otherwise its writes go out in as few
22580
+ * `executeAction` calls as {@link sendWrites} allows. */
22581
+ async writeRelation(key, kind, value, batchId) {
22582
+ const predicate = this.getRelationOptions(key)?.predicate;
22583
+ if (predicate && kind !== 'remover')
22584
+ this._relationsWritten.add(predicate);
22498
22585
  const abstractName = this.abstractName();
22499
- if (abstractName) {
22500
- if (value != null)
22501
- await this.relationThroughAbstract(abstractName, key, 'remover', value, batchId);
22586
+ if (!abstractName) {
22587
+ await this.sendWrites(this.planRelation(key, kind, value), batchId);
22502
22588
  return;
22503
22589
  }
22504
- // Generate actions from metadata (replaces Prolog query)
22505
- const actions = this.generateRelationAction(key, 'remover');
22506
- if (value != null) {
22507
- if (Array.isArray(value)) {
22508
- await Promise.all(value.map((v) => this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(v) }], batchId)));
22509
- }
22510
- else {
22511
- await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(value) }], batchId);
22512
- }
22590
+ if (!this.getRelationOptions(key)) {
22591
+ console.warn(`Relation "${key}" has no metadata, skipping`);
22592
+ return;
22513
22593
  }
22594
+ if (value != null)
22595
+ await this.relationThroughAbstract(abstractName, key, kind, value, batchId);
22514
22596
  }
22515
22597
  /**
22516
22598
  * Saves the model instance to the perspective.
@@ -22600,13 +22682,14 @@ class Ad4mModel {
22600
22682
  const className = await this.perspective.stringOrTemplateObjectToSubjectClassName(this);
22601
22683
  await this.perspective.createSubject(className, this._baseExpression, initialValues, batchId);
22602
22684
  // Relations via innerUpdate; createSubject wrote the scalar properties.
22603
- await this.innerUpdate(false, batchId);
22685
+ const writes = await this.updateWrites(false);
22604
22686
  for (const key of deferredExpressionProps) {
22605
22687
  const value = this[key];
22606
22688
  if (value !== undefined && value !== null) {
22607
- await this.setProperty(key, value, batchId);
22689
+ writes.push(...await this.planProperty(key, value));
22608
22690
  }
22609
22691
  }
22692
+ await this.sendWrites(writes, batchId);
22610
22693
  // If we got a batchId passed in, we let the caller decide when to commit.
22611
22694
  // We can't call getData() since the instance won't exist in the perspective
22612
22695
  // until the batch is committed.
@@ -22668,6 +22751,11 @@ class Ad4mModel {
22668
22751
  return cleanCopy;
22669
22752
  }
22670
22753
  async innerUpdate(setProperties = true, batchId) {
22754
+ await this.sendWrites(await this.updateWrites(setProperties), batchId);
22755
+ }
22756
+ /** The writes of the changed fields, in field order (see {@link sendWrites}). */
22757
+ async updateWrites(setProperties = true) {
22758
+ const writes = [];
22671
22759
  const ctor = this.constructor;
22672
22760
  // Determine which fields actually changed (skip unchanged when snapshot exists)
22673
22761
  const dirty = this._snapshot ? new Set(this.changedFields()) : null;
@@ -22704,18 +22792,21 @@ class Ad4mModel {
22704
22792
  }
22705
22793
  if (value !== undefined && value !== null) {
22706
22794
  if (value?.action) {
22795
+ const envelopePredicate = this.getRelationOptions(key)?.predicate;
22796
+ if (envelopePredicate && value.action !== "remover")
22797
+ this._relationsWritten.add(envelopePredicate);
22707
22798
  switch (value.action) {
22708
22799
  case "setter":
22709
- await this.setRelationValues(key, value.value, batchId);
22800
+ writes.push(...this.planRelation(key, 'setter', value.value));
22710
22801
  break;
22711
22802
  case "adder":
22712
- await this.addRelationValue(key, value.value, batchId);
22803
+ writes.push(...this.planRelation(key, 'adder', value.value));
22713
22804
  break;
22714
22805
  case "remover":
22715
- await this.removeRelationValue(key, value.value, batchId);
22806
+ writes.push(...this.planRelation(key, 'remover', value.value));
22716
22807
  break;
22717
22808
  default:
22718
- await this.setRelationValues(key, value.value, batchId);
22809
+ writes.push(...this.planRelation(key, 'setter', value.value));
22719
22810
  break;
22720
22811
  }
22721
22812
  }
@@ -22723,9 +22814,11 @@ class Ad4mModel {
22723
22814
  // Handle all arrays as relations, including empty ones (which clears the relation).
22724
22815
  // A record being created under an id minted here has no links to
22725
22816
  // clear, so an empty relation there costs a round trip and writes nothing.
22726
- if (value.length === 0 && !this._snapshot && this._idMinted && !this._relationsWritten.has(this.getRelationOptions(key)?.predicate ?? key))
22817
+ const predicate = this.getRelationOptions(key)?.predicate ?? key;
22818
+ if (value.length === 0 && !this._snapshot && this._idMinted && !this._relationsWritten.has(predicate))
22727
22819
  continue;
22728
- await this.setRelationValues(key, value, batchId);
22820
+ this._relationsWritten.add(predicate);
22821
+ writes.push(...this.planRelation(key, 'setter', value));
22729
22822
  }
22730
22823
  else if (value !== undefined && value !== null && value !== "") {
22731
22824
  // A scalar handed to a relation field is a single-member relation.
@@ -22754,7 +22847,8 @@ class Ad4mModel {
22754
22847
  // both paths at once.
22755
22848
  const relationMeta = this.getRelationOptions(key);
22756
22849
  if (relationMeta) {
22757
- await this.setRelationValues(key, [value], batchId);
22850
+ this._relationsWritten.add(relationMeta.predicate);
22851
+ writes.push(...this.planRelation(key, 'setter', [value]));
22758
22852
  continue;
22759
22853
  }
22760
22854
  if (setProperties) {
@@ -22763,11 +22857,12 @@ class Ad4mModel {
22763
22857
  if (propMeta?.flag) {
22764
22858
  continue;
22765
22859
  }
22766
- await this.setProperty(key, value, batchId);
22860
+ writes.push(...await this.planProperty(key, value));
22767
22861
  }
22768
22862
  }
22769
22863
  }
22770
22864
  }
22865
+ return writes;
22771
22866
  }
22772
22867
  /**
22773
22868
  * Evaluate SPARQL getters for a batch of instances on demand.
@@ -23914,7 +24009,7 @@ let FlowTransitionProposal = class FlowTransitionProposal extends Ad4mModel {
23914
24009
  this.acceptedBy = [];
23915
24010
  // Whether this proposal settled an edge is not on the record: the
23916
24011
  // executor keeps that per agent, outside the graph (#1424). Ask
23917
- // `PerspectiveProxy.flowFired(instance)` for the proposals your replica
24012
+ // `PerspectiveProxy.flowFired(instances)` for the proposals your replica
23918
24013
  // recorded as fired, or listen with `onFlowStateChanged`.
23919
24014
  // "When was this proposal written?" is answered by `Ad4mModel`'s built-in
23920
24015
  // `createdAt`, synthesized on hydration from the earliest link timestamp
@@ -26189,4 +26284,4 @@ const SCOPED_EVENTS = new Set([
26189
26284
  "flow-state-changed",
26190
26285
  ]);
26191
26286
 
26192
- export { ACCEPTED_BY_GETTER, AGENT_KIND, AGENT_KIND_BOT, AIClient, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, AI_RECOMMENDED_MODELS, AI_SERVER_INSTALL_LINKS, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, AutoProcessorConfig, BelongsToMany, BelongsToOne, CALL_PROTOCOL_VERSION, Capability, CapabilityInput, ComputeLogEntry, Container, DEFAULT_ICE_SERVERS, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, FlowInstance, FlowInstanceRecord, FlowTransitionProposal, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, IdentityClient, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, InterpretationOverlay, InterpretationRun, LOCAL_INSTALL_TIMEOUT_MS, LONG_METHODS, LONG_TIMEOUT_MS, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LiveQuery, MENTION_TEXT_LIMIT, Mentioning, MeshManager, Model, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OPENS_METHODS, OnlineAgent, Optional, PROPOSER_GETTER, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, READ_METHODS, REOPEN_BASE_DELAY_MS, REOPEN_MAX_DELAY_MS, ReadOnly, Resource, ResourceInput, RpcError, RuntimeInfo, SCOPED_EVENTS, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TextContent, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, WakerSubscriptionManager, agentKind, applyUpdate, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, coalesce, compileWhereClause, concat, createPersistentCache, createTelepresenceChannel, determineNamespace, determinePredicate, effectiveLiteralStorage, escapeQueryString, exists, exprRef2String, fileToDataUri, fn, focus, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, hintFor, holdsAWholeWordTerm, ifExpr, invalidatePerspectiveCache, isArrayType, isBot, isContainedScope, isContainmentTraversal, isExpression, isIncludeProjection, isLink, isNodeExpression, isNumericType, isObjectType, isSchemaType, isTraverseScope, linkEqual, linkExpressionInputToWire, linkExpressionToWire, linkMutationsToWire, literal, looksLikeUri, mentionOf, neighbourhoodExpressionFromWire, normalizeNamespaceString, normalizeSchemaType, normalizeValue, normalizeWhereForSparql, parseCallMessage, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, queryCacheSize, reopenDelay, requireSingleParent, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString, valueToLiteralIri };
26287
+ export { ACCEPTED_BY_GETTER, AGENT_KIND, AGENT_KIND_BOT, AIClient, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, AI_RECOMMENDED_MODELS, AI_SERVER_INSTALL_LINKS, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, AutoProcessorConfig, BelongsToMany, BelongsToOne, CALL_PROTOCOL_VERSION, Capability, CapabilityInput, ComputeLogEntry, Container, DEFAULT_ICE_SERVERS, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, FlowInstance, FlowInstanceRecord, FlowTransitionProposal, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, IdentityClient, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, InterpretationOverlay, InterpretationRun, LOCAL_INSTALL_TIMEOUT_MS, LONG_METHODS, LONG_TIMEOUT_MS, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LiveQuery, MENTION_TEXT_LIMIT, Mentioning, MeshManager, Model, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OPENS_METHODS, OnlineAgent, Optional, PROPOSER_GETTER, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, READ_METHODS, REOPEN_BASE_DELAY_MS, REOPEN_MAX_DELAY_MS, ReadOnly, Resource, ResourceInput, RpcError, RuntimeInfo, SCOPED_EVENTS, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TextContent, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, WakerSubscriptionManager, agentKind, applyUpdate, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, coalesce, compileWhereClause, concat, createPersistentCache, createTelepresenceChannel, determineNamespace, determinePredicate, effectiveLiteralStorage, escapeQueryString, exists, exprRef2String, fileToDataUri, fn, focus, formatList, formatQueryValue, formatSPARQLValue, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, hintFor, holdsAWholeWordTerm, ifExpr, isArrayType, isBot, isContainedScope, isContainmentTraversal, isExpression, isIncludeProjection, isLink, isNodeExpression, isNumericType, isObjectType, isSchemaType, isTraverseScope, linkEqual, linkExpressionInputToWire, linkExpressionToWire, linkMutationsToWire, literal, looksLikeUri, mentionOf, neighbourhoodExpressionFromWire, normalizeNamespaceString, normalizeSchemaType, normalizeValue, normalizeWhereForSparql, parseCallMessage, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, reopenDelay, requireSingleParent, requireTotalCount, resolveParentPredicate, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString, valueToLiteralIri };