@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
@@ -14,7 +14,6 @@ import { Link } from "../links/Links";
14
14
  import { LinkQuery } from "./LinkQuery";
15
15
  import { Literal } from "../Literal";
16
16
  import { getPropertiesMetadata, getRelationsMetadata } from "../model/decorators";
17
- import { getCachedResult, setCachedResult, invalidatePerspectiveCache } from "../model/query-cache";
18
17
  import { LiveQuery } from "./LiveQuery";
19
18
  import { SHACLShape } from "../shacl/SHACLShape";
20
19
  import { SHACLFlow } from "../shacl/SHACLFlow";
@@ -285,9 +284,7 @@ export class PerspectiveProxy {
285
284
  * @param batchId - Optional batch ID to group this operation with others
286
285
  */
287
286
  async executeAction(actions, expression, parameters, batchId) {
288
- const result = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").executeCommands(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId);
289
- invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
290
- return result;
287
+ return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").executeCommands(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId);
291
288
  }
292
289
  /**
293
290
  * Retrieves links from the perspective that match the given query.
@@ -515,12 +512,15 @@ export class PerspectiveProxy {
515
512
  return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").flowStates(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, instances);
516
513
  }
517
514
  /**
518
- * The proposals of `instance` whose votes settled an edge, as this
519
- * agent's executor recorded them — the flow's history, sorted by URI.
515
+ * For each of `instances`, in order, the proposals whose votes settled an
516
+ * edge, as this agent's executor recorded them — the flow's history,
517
+ * sorted by URI (`fired: []` when none). One call covers up to 200
518
+ * instances (the executor refuses more with a 400); split a longer list
519
+ * into batches of 200.
520
520
  * Replaces the `resolvedAs` property proposals used to carry.
521
521
  */
522
- async flowFired(instance) {
523
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").flowFired(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, instance);
522
+ async flowFired(instances) {
523
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").flowFired(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, instances);
524
524
  }
525
525
  /**
526
526
  * Called whenever a flow instance on this perspective changes state on
@@ -584,20 +584,18 @@ export class PerspectiveProxy {
584
584
  * keep its blocking thread busy until it completes; what's saved is the
585
585
  * serialise + network + client-deserialise tax on the result. Aborted
586
586
  * calls reject with `DOMException('Aborted', 'AbortError')` — match
587
- * `fetch()` for handling. Cached results bypass the round-trip entirely
588
- * and are returned synchronously, ignoring the signal.
587
+ * `fetch()` for handling. A call with `options` makes its own RPC.
588
+ *
589
+ * **Sharing:** concurrent identical calls without `options` share one RPC;
590
+ * each caller gets its own result object. Nothing is cached once the
591
+ * call settles: use a live query for repeated reads of the same data.
589
592
  *
590
593
  * @param query - SPARQL query string (read-only operations only)
591
594
  * @param options - Optional call options (e.g. AbortSignal for cancellation)
592
595
  * @returns Query results as parsed JSON
593
596
  */
594
597
  async querySparql(query, options) {
595
- const cached = getCachedResult(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, query);
596
- if (cached !== undefined)
597
- return cached;
598
- const result = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").querySparql(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, query, options);
599
- setCachedResult(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, query, result);
600
- return result;
598
+ return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").querySparql(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, query, options);
601
599
  }
602
600
  /**
603
601
  * Execute a model query — the executor-side replacement for SPARQL query building + JS hydration.
@@ -610,7 +608,7 @@ export class PerspectiveProxy {
610
608
  * query over their union, whose rows carry `__subjectClass` and
611
609
  * `__subjectClasses` (#1238)
612
610
  * @param queryJson - Structured query as JSON string
613
- * @returns Object with `instances` array and `totalCount`
611
+ * @returns Object with `instances` array, and `totalCount` when the query sets `count: true`
614
612
  */
615
613
  async modelQuery(className, queryJson, options) {
616
614
  return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, options);
@@ -704,9 +702,7 @@ export class PerspectiveProxy {
704
702
  * ```
705
703
  */
706
704
  async add(link, status = 'shared', batchId) {
707
- const result = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
708
- invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
709
- return result;
705
+ return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
710
706
  }
711
707
  /**
712
708
  * Adds multiple links to the perspective in a single operation.
@@ -718,9 +714,7 @@ export class PerspectiveProxy {
718
714
  * @returns Array of created LinkExpressions
719
715
  */
720
716
  async addLinks(links, status = 'shared', batchId) {
721
- const result = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addLinks(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, links, status, batchId);
722
- invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
723
- return result;
717
+ return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addLinks(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, links, status, batchId);
724
718
  }
725
719
  /**
726
720
  * Removes multiple links from the perspective.
@@ -730,9 +724,7 @@ export class PerspectiveProxy {
730
724
  * @returns Array of removed LinkExpressions
731
725
  */
732
726
  async removeLinks(links, batchId) {
733
- const result = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeLinks(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, links, batchId);
734
- invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
735
- return result;
727
+ return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeLinks(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, links, batchId);
736
728
  }
737
729
  /**
738
730
  * Applies a set of link mutations (adds and removes) in a single operation.
@@ -743,9 +735,7 @@ export class PerspectiveProxy {
743
735
  * @returns Object containing results of the mutations
744
736
  */
745
737
  async linkMutations(mutations, status = 'shared') {
746
- const result = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").linkMutations(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, mutations, status);
747
- invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
748
- return result;
738
+ return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").linkMutations(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, mutations, status);
749
739
  }
750
740
  /**
751
741
  * Adds a pre-signed LinkExpression to the perspective.
@@ -772,9 +762,7 @@ export class PerspectiveProxy {
772
762
  * @param batchId - Optional batch ID to group this operation with others
773
763
  */
774
764
  async update(oldLink, newLink, batchId) {
775
- const result = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").updateLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, oldLink, newLink, batchId);
776
- invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
777
- return result;
765
+ return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").updateLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, oldLink, newLink, batchId);
778
766
  }
779
767
  /**
780
768
  * Removes a link from the perspective.
@@ -820,9 +808,7 @@ export class PerspectiveProxy {
820
808
  else {
821
809
  resolvedLink = link;
822
810
  }
823
- const result = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, resolvedLink, batchId);
824
- invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
825
- return result;
811
+ return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, resolvedLink, batchId);
826
812
  }
827
813
  /** Creates a new batch for grouping operations */
828
814
  async createBatch() {
@@ -830,9 +816,7 @@ export class PerspectiveProxy {
830
816
  }
831
817
  /** Commits a batch of operations */
832
818
  async commitBatch(batchId) {
833
- const result = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").commitBatch(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, batchId);
834
- invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
835
- return result;
819
+ return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").commitBatch(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, batchId);
836
820
  }
837
821
  /**
838
822
  * Drops an open batch without committing it — the recovery for a failed batched call:
@@ -1200,13 +1184,13 @@ export class PerspectiveProxy {
1200
1184
  return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").getShaclTargetClass(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, name);
1201
1185
  }
1202
1186
  /**
1203
- * Get all SHACL shapes stored in this Perspective (one RPC call).
1204
- * The executor resolves all shapes in-process and returns them in bulk.
1187
+ * Get the SHACL shapes stored in this Perspective in one RPC call: all of
1188
+ * them, or only those named in `names` (unknown names are left out).
1205
1189
  * A shape that fails to decode is skipped with a `console.warn`, so it
1206
1190
  * does not hide the others.
1207
1191
  */
1208
- async getAllShacl() {
1209
- const entries = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").getAllShacl(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
1192
+ async getAllShacl(options) {
1193
+ const entries = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").getAllShacl(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, options?.names);
1210
1194
  const shapes = [];
1211
1195
  for (const { name, shapeUri, links } of entries) {
1212
1196
  try {
@@ -1447,7 +1431,6 @@ export class PerspectiveProxy {
1447
1431
  * record that the abstract class reads, under its own name. */
1448
1432
  async updateSubject(className, exprAddr, values, batchId) {
1449
1433
  await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").updateSubject(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, exprAddr, JSON.stringify(values), batchId);
1450
- invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
1451
1434
  }
1452
1435
  /**
1453
1436
  * Creates an instance of a subject class, validated by the executor against the class's
@@ -1466,42 +1449,23 @@ export class PerspectiveProxy {
1466
1449
  * const { baseUri } = await perspective.instanceCreate({ className: "Task", properties: { title: "Write" } });
1467
1450
  */
1468
1451
  async instanceCreate(body) {
1469
- const created = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").instanceCreate(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, body);
1470
- invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
1471
- return created;
1452
+ return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").instanceCreate(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, body);
1472
1453
  }
1473
1454
  /** Sets single-valued properties of an instance, validated; the others stay. See {@link instanceCreate}. */
1474
1455
  async instanceUpdate(body) {
1475
- const updated = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").instanceUpdate(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, body);
1476
- invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
1477
- return updated;
1456
+ return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").instanceUpdate(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, body);
1478
1457
  }
1479
1458
  /** Removes an instance and every link to and from it. See {@link instanceCreate}. */
1480
1459
  async instanceRemove(body) {
1481
- // Outside a batch the links go one by one, so a rejection (`partiallyRemoved`) can
1482
- // come after some are gone: invalidate either way.
1483
- try {
1484
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").instanceRemove(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, body);
1485
- }
1486
- finally {
1487
- invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
1488
- }
1460
+ return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").instanceRemove(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, body);
1489
1461
  }
1490
1462
  /** Adds an item to a collection of an instance, validated. See {@link instanceCreate}. */
1491
1463
  async instanceAddToCollection(body) {
1492
- const added = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").instanceAddToCollection(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, body);
1493
- invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
1494
- return added;
1464
+ return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").instanceAddToCollection(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, body);
1495
1465
  }
1496
1466
  /** Removes an item from a collection of an instance. See {@link instanceCreate}. */
1497
1467
  async instanceRemoveFromCollection(body) {
1498
- // Like instanceRemove, a rejection can come after some links are gone.
1499
- try {
1500
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").instanceRemoveFromCollection(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, body);
1501
- }
1502
- finally {
1503
- invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
1504
- }
1468
+ return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").instanceRemoveFromCollection(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, body);
1505
1469
  }
1506
1470
  async getSubjectData(subjectClass, exprAddr) {
1507
1471
  if (typeof subjectClass === "string") {
@@ -1565,7 +1529,6 @@ export class PerspectiveProxy {
1565
1529
  const ctor = subjectClass?.constructor;
1566
1530
  if (typeof subjectClass === "object" && ctor && Object.prototype.hasOwnProperty.call(ctor, 'builtinUri')) {
1567
1531
  await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeSubject(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, ctor.builtinUri, exprAddr, batchId);
1568
- invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
1569
1532
  return;
1570
1533
  }
1571
1534
  let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);
@@ -1575,7 +1538,6 @@ export class PerspectiveProxy {
1575
1538
  const markers = await this.get(new LinkQuery({ predicate: "ad4m://abstract" }));
1576
1539
  if (markers.some((link) => shapePattern.test(link.data.source))) {
1577
1540
  await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeSubject(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, exprAddr, batchId);
1578
- invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
1579
1541
  return;
1580
1542
  }
1581
1543
  // Get destructor actions from SHACL links (Prolog-free)
@@ -98,6 +98,10 @@ export interface SHACLPropertyShape {
98
98
  * Drives direction (forward/reverse), scalar-vs-collection rendering,
99
99
  * and default max-count. */
100
100
  relationKind?: 'hasMany' | 'hasOne' | 'belongsToOne' | 'belongsToMany';
101
+ /** AD4M-specific: the relation is read `polymorphic: true` unless the query
102
+ * says otherwise (`ad4m://polymorphic`). Carried in the shape so the executor
103
+ * applies it at every include depth, below a polymorphic include too. */
104
+ polymorphic?: boolean;
101
105
  /** AD4M-specific: target class name (local-name) for a relation property.
102
106
  * Complements `class` (the SHACL node-shape URI) by providing the bare
103
107
  * model class name used by the executor to look up the target shape
@@ -456,6 +456,13 @@ export class SHACLShape {
456
456
  target: `literal:string:${prop.relationKind}`
457
457
  });
458
458
  }
459
+ if (prop.polymorphic) {
460
+ links.push({
461
+ source: propShapeId,
462
+ predicate: "ad4m://polymorphic",
463
+ target: `literal:${prop.polymorphic}`
464
+ });
465
+ }
459
466
  if (prop.targetClassName) {
460
467
  links.push({
461
468
  source: propShapeId,
@@ -595,6 +602,7 @@ export class SHACLShape {
595
602
  in: json(id, "sh://in"),
596
603
  relationKind: ['hasMany', 'hasOne', 'belongsToOne', 'belongsToMany'].includes(relationKind)
597
604
  ? relationKind : undefined,
605
+ polymorphic: bool(id, "ad4m://polymorphic"),
598
606
  targetClassName: str(id, "ad4m://targetClassName"),
599
607
  whereFilter: json(id, "ad4m://whereFilter"),
600
608
  wherePredicates: json(id, "ad4m://wherePredicates"),
@@ -643,6 +651,7 @@ export class SHACLShape {
643
651
  class: p.class,
644
652
  in: p.in,
645
653
  relation_kind: p.relationKind,
654
+ polymorphic: p.polymorphic,
646
655
  collection: p.collection ?? (isCollection(p) || undefined),
647
656
  target_class_name: p.targetClassName,
648
657
  where_filter: p.whereFilter,
@@ -697,6 +706,7 @@ export class SHACLShape {
697
706
  class: p.class,
698
707
  in: p.in,
699
708
  relationKind: p.relation_kind,
709
+ polymorphic: p.polymorphic,
700
710
  collection: p.collection,
701
711
  targetClassName: p.target_class_name,
702
712
  whereFilter: p.where_filter,
package/package.json CHANGED
@@ -53,8 +53,8 @@
53
53
  "ws": "8.13.0"
54
54
  },
55
55
  "patchedDependencies": {},
56
- "version": "0.13.1-staging.13",
57
- "gitHead": "3f800fc56a6b19a44a53b60b38b1ba2a7b809cf8",
56
+ "version": "0.13.1-staging.15",
57
+ "gitHead": "72dc335c6cb13c4348f10d2b8dc3d06862f8da51",
58
58
  "scripts": {
59
59
  "build": "patch-package && tsc && pnpm run bundle",
60
60
  "bundle": "rollup -c rollup.config.js",
@@ -57,7 +57,7 @@ const MOCK_RESPONSES: Record<string, RpcHandler> = {
57
57
  'agent.lock': { did: 'did:test:123', isInitialized: true, isUnlocked: false },
58
58
  'agent.unlock': { did: 'did:test:123', isInitialized: true, isUnlocked: true },
59
59
  'agent.import': { did: 'did:test:imported', isInitialized: true, isUnlocked: true },
60
- 'agent.byDid': (p: Record<string, unknown>) => ({ did: p.did, perspective: new Perspective() }),
60
+ 'agent.byDIDs': (p: Record<string, unknown>) => (p.dids as string[]).map(did => ({ did, perspective: new Perspective() })),
61
61
  'agent.updateProfile': { did: 'did:test:123', perspective: new Perspective(), directMessageLanguage: 'lang://dm' },
62
62
  'agent.sign': 'signed-message-data',
63
63
  'agent.isLocked': false,
@@ -199,10 +199,10 @@ const MOCK_RESPONSES: Record<string, RpcHandler> = {
199
199
  };
200
200
  },
201
201
  'expression.getMany': (p: Record<string, unknown>) => {
202
- // Return one result per URL (aligned by index), matching real API behavior
202
+ // One entry per URL, in order: what `expression.get` answers for it.
203
203
  const urls = (p.urls || []) as string[];
204
- return urls.map((url: string) => ({
205
- author: 'did:test:1', timestamp: '2023-01-01', data: { type: 'test' },
204
+ return urls.map(() => ({
205
+ author: 'did:test:123', timestamp: '2024-01-01', data: '{"content":"hello"}',
206
206
  language: { address: 'lang://test' }, proof: { valid: true },
207
207
  }));
208
208
  },
@@ -513,6 +513,7 @@ describe('AgentClient', () => {
513
513
 
514
514
  test('byDID() fetches agent by DID', async () => {
515
515
  const agent = await ad4m.agent.byDID('did:test:other');
516
+ expect(lastRpcCall!.params.dids).toEqual(['did:test:other']);
516
517
  expect(agent.did).toBe('did:test:other');
517
518
  });
518
519
 
@@ -1159,8 +1160,18 @@ describe('ExpressionClient', () => {
1159
1160
  test('getMany() returns multiple expressions', async () => {
1160
1161
  const exprs = await ad4m.expression.getMany(['url1', 'url2']);
1161
1162
  expect(exprs).toHaveLength(2);
1162
- expect(exprs[0].author).toBe('did:test:1');
1163
- expect(exprs[1].author).toBe('did:test:1');
1163
+ expect(exprs[0].author).toBe('did:test:123');
1164
+ expect(exprs[1].author).toBe('did:test:123');
1165
+ });
1166
+
1167
+ test('getMany() sends at most 200 URLs per expression.getMany call', async () => {
1168
+ const freshClient = newClient();
1169
+ const urls = Array.from({ length: 201 }, (_, i) => `lang://test/Qm${i}`);
1170
+ const exprs = await freshClient.expression.getMany(urls);
1171
+ expect(exprs).toHaveLength(201);
1172
+ const calls = lastOf(MockWebSocket.instances).rpc.filter(c => c.type === 'expression.getMany');
1173
+ expect(calls.map(c => (c.params.urls as string[]).length)).toEqual([200, 1]);
1174
+ expect(calls.flatMap(c => c.params.urls as string[])).toEqual(urls);
1164
1175
  });
1165
1176
 
1166
1177
  test('getRaw() returns raw expression', async () => {
@@ -1,4 +1,4 @@
1
- import {ApiClient, CallOptions } from '../apiClient';
1
+ import {ApiClient, CallOptions, RpcError } from '../apiClient';
2
2
  import { PerspectiveInput } from "../perspectives/Perspective";
3
3
  import {
4
4
  Agent,
@@ -13,7 +13,8 @@ import { AgentStatus } from "./AgentStatus";
13
13
  import { AGENT_KIND } from "./AgentKind";
14
14
  import { LinkMutations, LinkExpression, LinkInput, linkEqual } from "../links/Links";
15
15
  import { VerificationRequestResult } from "../runtime/RuntimeTypes";
16
- import { PersistentCache, createPersistentCache } from "../cache/PersistentCache";
16
+ import { createPersistentCache } from "../cache/PersistentCache";
17
+ import { KeyedCache, StoredEntry } from "../cache/KeyedCache";
17
18
  import type { Agent as AgentData } from "../generated/api/Agent";
18
19
  import type { AgentSignature } from "../generated/api/AgentSignature";
19
20
  import type { AgentWithIdentity } from "../generated/api/AgentWithIdentity";
@@ -29,38 +30,35 @@ function toAgent(data: AgentData | AgentWithIdentity | null): Agent | null {
29
30
  return data ? Agent.fromWire(data) : null;
30
31
  }
31
32
 
33
+ /** Most DIDs the executor takes in one `agent.byDIDs` call. */
34
+ const MAX_DIDS_PER_CALL = 200;
35
+
32
36
  export class AgentClient {
33
37
  #apiClient: ApiClient;
34
38
 
35
- // ── byDID cache ────────────────────────────────────────────────────
36
- // L1: in-memory promise cache with timestamps for TTL
37
- #memCache = new Map<string, { promise: Promise<Agent>; ts: number }>();
38
- // L2: persistent cache (IndexedDB in browser, NullCache in Node)
39
- // Entries are wrapped with a timestamp so the TTL can be enforced across restarts.
40
- #persistent: PersistentCache<{ agent: Agent; ts: number }>;
41
- // Self-DID for event-driven invalidation (no TTL for own profile)
42
- #selfDid: string | null = null;
43
- /** TTL for remote (non-self) agent profiles in L1 cache (ms). */
39
+ // byDID cache: concurrent misses go out in one `agent.byDIDs` call.
40
+ #agents: KeyedCache<Agent>;
41
+ /**
42
+ * TTL of every cached profile, the own one too, in memory and in the
43
+ * persistent cache (ms). `agent-updated` only comes from this executor, so
44
+ * a profile changed through another executor of the same agent shows up
45
+ * when the entry expires.
46
+ */
44
47
  static REMOTE_AGENT_TTL_MS = 5 * 60_000; // 5 minutes
45
- /** TTL for remote agent profiles in the L2 (IndexedDB) cache (ms).
46
- * After this window any restart triggers a fresh network fetch. */
47
- static REMOTE_AGENT_TTL_L2_MS = 5 * 60_000; // 5 minutes
48
48
 
49
49
  constructor(baseUrl: string, token?: string, sharedApiClient?: ApiClient) {
50
50
  this.#apiClient = sharedApiClient || new ApiClient(baseUrl, token);
51
- this.#persistent = createPersistentCache<{ agent: Agent; ts: number }>('ad4m-agent-cache', 'agents');
51
+ this.#agents = new KeyedCache<Agent>({
52
+ loadMany: (dids) => this.#loadAgents(dids),
53
+ maxBatch: MAX_DIDS_PER_CALL,
54
+ persistent: createPersistentCache<StoredEntry<Agent>>('ad4m-agent-cache', 'agents'),
55
+ maxAgeMs: () => AgentClient.REMOTE_AGENT_TTL_MS,
56
+ persistentMaxAgeMs: () => AgentClient.REMOTE_AGENT_TTL_MS,
57
+ });
52
58
  }
53
59
 
54
60
  async me(): Promise<Agent> {
55
- const agentObject = toAgent(await this.#apiClient.call('agent.get', {}));
56
-
57
- // Auto-set selfDid so event-driven cache invalidation works
58
- // without requiring apps to call setSelfDid() manually
59
- if (agentObject.did && !this.#selfDid) {
60
- this.#selfDid = agentObject.did;
61
- }
62
-
63
- return agentObject;
61
+ return toAgent(await this.#apiClient.call('agent.get', {}));
64
62
  }
65
63
 
66
64
  async status(): Promise<AgentStatus> {
@@ -91,69 +89,43 @@ export class AgentClient {
91
89
  return new AgentStatus(result);
92
90
  }
93
91
 
92
+ /**
93
+ * The agent with this DID, or `null` when it is unknown. Concurrent calls
94
+ * for any DIDs share one `agent.byDIDs` request.
95
+ */
94
96
  async byDID(did: string): Promise<Agent> {
95
- // agent-updated events keep cached entries fresh (the self-DID entry has no TTL).
97
+ // agent-updated events refresh cached entries before their TTL runs out.
96
98
  this.#listen();
97
- const now = Date.now();
98
- const cached = this.#memCache.get(did);
99
-
100
- if (cached) {
101
- const isSelf = did === this.#selfDid;
102
- // Self-DID: L1 always valid (event-driven invalidation)
103
- // Remote DID: L1 valid within TTL
104
- if (isSelf || (now - cached.ts) < AgentClient.REMOTE_AGENT_TTL_MS) {
105
- return cached.promise;
106
- }
107
- }
108
-
109
- // Deduplicate: store the promise immediately so concurrent calls share one RPC
110
- const promise = (async () => {
111
- // L2: check persistent cache before network
112
- const entry = await this.#persistent.get(did);
113
- // entry.agent may be undefined for pre-TTL cache entries (migration) — treat as expired
114
- if (entry?.agent && (now - (entry.ts ?? 0)) < AgentClient.REMOTE_AGENT_TTL_L2_MS) {
115
- return entry.agent;
116
- }
117
-
118
- // L3: network fetch
119
- const result = toAgent(await this.#apiClient.call('agent.byDid', { did }));
120
- this.#persistent.put(did, { agent: result, ts: Date.now() }); // fire-and-forget write to L2
121
- return result;
122
- })();
123
-
124
- this.#memCache.set(did, { promise, ts: now });
125
-
126
- // Clean up on failure so next call retries
127
- promise.catch(() => {
128
- if (this.#memCache.get(did)?.promise === promise) {
129
- this.#memCache.delete(did);
130
- }
131
- });
99
+ return this.#agents.get(did);
100
+ }
132
101
 
133
- return promise;
102
+ /**
103
+ * One `agent.byDIDs` call for the misses of one tick. The executor fails
104
+ * that call when one DID's lookup fails (500), so the DIDs of a failed
105
+ * batch are then read alone: each caller gets what a lone `byDID` gives.
106
+ */
107
+ async #loadAgents(dids: string[]): Promise<Array<Agent | null | Error>> {
108
+ try {
109
+ return (await this.#apiClient.call('agent.byDIDs', { dids })).map(toAgent);
110
+ } catch (error) {
111
+ if (dids.length === 1 || !(error instanceof RpcError) || error.status !== 500) throw error;
112
+ return Promise.all(dids.map(did =>
113
+ this.#apiClient.call('agent.byDid', { did }).then(toAgent, (failure) =>
114
+ failure instanceof Error ? failure : new Error(String(failure)))));
115
+ }
134
116
  }
135
117
 
136
118
  #cacheAgent(agent: Agent): void {
137
119
  if (!agent.did) return;
138
- this.#memCache.set(agent.did, { promise: Promise.resolve(agent), ts: Date.now() });
139
- this.#persistent.put(agent.did, { agent, ts: Date.now() }); // fire-and-forget
120
+ this.#agents.set(agent.did, agent);
140
121
  this.#listen();
141
122
  }
142
123
 
143
- /**
144
- * Set the current agent's own DID.
145
- * The self-DID receives event-driven invalidation and is never TTL-expired.
146
- */
147
- setSelfDid(did: string): void {
148
- this.#selfDid = did;
149
- }
150
-
151
124
  /**
152
125
  * Invalidate a specific DID's cache entry in both L1 and L2.
153
126
  */
154
127
  invalidateByDid(did: string): void {
155
- this.#memCache.delete(did);
156
- this.#persistent.delete(did); // fire-and-forget
128
+ this.#agents.delete(did);
157
129
  }
158
130
 
159
131
  /**
@@ -161,7 +133,7 @@ export class AgentClient {
161
133
  * L2 (IndexedDB) is preserved — agent data remains valid across sessions.
162
134
  */
163
135
  clearByDidCache(): void {
164
- this.#memCache.clear();
136
+ this.#agents.clear();
165
137
  }
166
138
 
167
139
  async updatePublicPerspective(perspective: PerspectiveInput): Promise<Agent> {