@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
@@ -0,0 +1,6 @@
1
+ import type { ExpressionLookupError } from "./ExpressionLookupError";
2
+ import type { ExpressionRendered } from "./ExpressionRendered";
3
+ /**
4
+ * One `expression.getMany` entry (`null` when `expression.get` returns `null`).
5
+ */
6
+ export type ExpressionManyEntry = ExpressionLookupError | ExpressionRendered;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The proposals of one instance this agent has marked fired, as
3
+ * `perspective.flowFired` returns them.
4
+ */
5
+ export type FlowFiredEntry = {
6
+ instance: string;
7
+ /**
8
+ * Sorted; empty when this agent has marked none.
9
+ */
10
+ fired: Array<string>;
11
+ };
@@ -0,0 +1,2 @@
1
+ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
+ export {};
@@ -1,8 +1,8 @@
1
1
  /**
2
- * `perspective.flowFired`: the proposals of `instance` the calling agent's
3
- * pass has recorded as fired, sorted.
2
+ * `perspective.flowFired`: for each of `instances`, in order, the proposals
3
+ * the calling agent's pass has recorded as fired, sorted.
4
4
  */
5
5
  export type PerspectiveFlowFiredParams = {
6
6
  uuid: string;
7
- instance: string;
7
+ instances: Array<string>;
8
8
  };
@@ -59,10 +59,12 @@ import type { EntanglementProofsWrapper } from "./EntanglementProofsWrapper";
59
59
  import type { EventName } from "./Events";
60
60
  import type { ExportRequest } from "./ExportRequest";
61
61
  import type { ExpressionInteractRequest } from "./ExpressionInteractRequest";
62
+ import type { ExpressionManyEntry } from "./ExpressionManyEntry";
62
63
  import type { ExpressionManyRequest } from "./ExpressionManyRequest";
63
64
  import type { ExpressionRendered } from "./ExpressionRendered";
64
65
  import type { ExpressionUrlRequest } from "./ExpressionUrlRequest";
65
66
  import type { FireOutcome } from "./FireOutcome";
67
+ import type { FlowFiredEntry } from "./FlowFiredEntry";
66
68
  import type { FlowStateEntry } from "./FlowStateEntry";
67
69
  import type { FriendsListRequest } from "./FriendsListRequest";
68
70
  import type { GenerateAgentRequest } from "./GenerateAgentRequest";
@@ -506,7 +508,7 @@ export interface RpcMethods {
506
508
  };
507
509
  "expression.getMany": {
508
510
  params: ExpressionManyRequest;
509
- result: Array<ExpressionRendered | null>;
511
+ result: Array<ExpressionManyEntry | null>;
510
512
  };
511
513
  "expression.getRaw": {
512
514
  params: ExpressionUrlRequest;
@@ -730,7 +732,7 @@ export interface RpcMethods {
730
732
  };
731
733
  "perspective.flowFired": {
732
734
  params: PerspectiveFlowFiredParams;
733
- result: Array<string>;
735
+ result: Array<FlowFiredEntry>;
734
736
  };
735
737
  "perspective.flowStates": {
736
738
  params: PerspectiveFlowStatesParams;
@@ -3,7 +3,7 @@ import { CallOptions } from "../apiClient";
3
3
  import type { SHACLShape } from "../shacl/SHACLShape";
4
4
  import type { JSONSchema, JSONSchemaToModelOptions } from "./json-schema";
5
5
  import { ModelQueryBuilder } from "./ModelQueryBuilder";
6
- import type { Scope, IncludeMap, Query, GetOptions, ResultsWithTotalCount, PaginationResult, ModelMetadata, TypedQuery, IncludeExtras, IncludeOf, LinksMap } from "./types";
6
+ import type { Scope, IncludeMap, Query, GetOptions, Page, ResultsWithTotalCount, PaginationResult, ModelMetadata, TypedQuery, IncludeExtras, IncludeOf, LinksMap } from "./types";
7
7
  /**
8
8
  * Base class for defining data models in AD4M.
9
9
  *
@@ -379,7 +379,7 @@ export declare class Ad4mModel {
379
379
  */
380
380
  static parseUnionResult(classes: (typeof Ad4mModel)[], perspective: PerspectiveProxy, raw: any, include?: IncludeMap, properties?: string[]): Ad4mModel[];
381
381
  /** @internal */
382
- static executeUnionQuery(perspective: PerspectiveProxy, classes: (typeof Ad4mModel)[], query?: Query, options?: CallOptions): Promise<ResultsWithTotalCount<Ad4mModel>>;
382
+ static executeUnionQuery(perspective: PerspectiveProxy, classes: (typeof Ad4mModel)[], query?: Query, options?: CallOptions): Promise<Page<Ad4mModel>>;
383
383
  /**
384
384
  * One query over several model classes (#1238).
385
385
  *
@@ -534,6 +534,23 @@ export declare class Ad4mModel {
534
534
  * ```
535
535
  */
536
536
  static count<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: TypedQuery<T>, options?: CallOptions): Promise<number>;
537
+ /** The `executeAction` write that sets property `key` to `value`; none for an empty value. */
538
+ private planProperty;
539
+ /**
540
+ * The `executeAction` writes of a relation change: one for a set (its
541
+ * `collectionSetter` takes every value), one per value for an add or remove.
542
+ */
543
+ private planRelation;
544
+ /**
545
+ * Sends writes in as few `executeAction` calls as keep their links: the
546
+ * executor runs a call's commands in order, so consecutive writes share one
547
+ * call, each with its own parameter names. A `collectionSetter` takes every
548
+ * parameter of its call as a member, so it goes in a call of its own. A
549
+ * command's `local` flag is per command, so Local and Shared links mix. The
550
+ * executor tries every parameter name at each position of each command, so
551
+ * a call holds at most `MAX_WRITES_PER_CALL` writes.
552
+ */
553
+ private sendWrites;
537
554
  private setProperty;
538
555
  /** Resolve a relation argument to a plain string ID. Accepts either a raw
539
556
  * string ID or an Ad4mModel instance (in which case `.id` is used). */
@@ -546,6 +563,11 @@ export declare class Ad4mModel {
546
563
  private setRelationValues;
547
564
  private addRelationValue;
548
565
  private removeRelationValue;
566
+ /** A relation setter, adder or remover call: on a row read through an
567
+ * abstract class it dispatches through the executor (see
568
+ * {@link relationThroughAbstract}); otherwise its writes go out in as few
569
+ * `executeAction` calls as {@link sendWrites} allows. */
570
+ private writeRelation;
549
571
  /**
550
572
  * Saves the model instance to the perspective.
551
573
  *
@@ -585,6 +607,8 @@ export declare class Ad4mModel {
585
607
  private changedValuesForDispatch;
586
608
  private cleanCopy;
587
609
  private innerUpdate;
610
+ /** The writes of the changed fields, in field order (see {@link sendWrites}). */
611
+ private updateWrites;
588
612
  /**
589
613
  * Evaluate SPARQL getters for a batch of instances on demand.
590
614
  *
@@ -2,7 +2,7 @@ import { Link } from "../links/Links";
2
2
  import { LinkQuery } from "../perspectives/LinkQuery";
3
3
  import { makeRandomId } from "./util";
4
4
  import { getPropertiesMetadata, getRelationsMetadata, setPropertyRegistryEntry, setRelationRegistryEntry, Model } from "./decorators";
5
- import { requireSingleParent, resolveParentPredicate } from "./query-common";
5
+ import { requireSingleParent, requireTotalCount, resolveParentPredicate } from "./query-common";
6
6
  import { isArrayType, determinePredicate, determineNamespace, buildModelFromJSONSchema } from "./json-schema";
7
7
  import { buildSPARQLQuery, valueToLiteralIri, effectiveLiteralStorage } from "./query-sparql";
8
8
  import { ModelQueryBuilder } from "./ModelQueryBuilder";
@@ -51,7 +51,8 @@ const SUBJECT_CLASS_KEY = '__subjectClass';
51
51
  * The walk stops descending *through* a polymorphic relation, because there is
52
52
  * nothing to descend into: its targets are of several classes by definition, so
53
53
  * no single class's metadata could say what a deeper include means. The
54
- * executor resolves those nested includes against each concrete class instead.
54
+ * executor applies each concrete class's declared default from its shape
55
+ * (`ad4m://polymorphic`) to those nested includes instead.
55
56
  */
56
57
  function applyPolymorphicIncludeDefaults(includes, ctor) {
57
58
  const relMeta = getRelationsMetadata(ctor);
@@ -348,6 +349,8 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
348
349
  }
349
350
  return instance;
350
351
  }
352
+ /** The most writes `sendWrites` joins into one `executeAction` call. */
353
+ const MAX_WRITES_PER_CALL = 200;
351
354
  /**
352
355
  * Put `childId` under `parent`. A containment scope `{ id }` writes through the
353
356
  * built-in `Container` (#1446): the executor runs the adder of the parent's own
@@ -1403,8 +1406,8 @@ export class Ad4mModel {
1403
1406
  * ```
1404
1407
  */
1405
1408
  static async findAllAndCount(perspective, query, options) {
1406
- const out = await this.executeModelQuery(perspective, (query ?? {}), undefined, options);
1407
- return out;
1409
+ const answer = await this.executeModelQuery(perspective, { ...(query ?? {}), count: true }, undefined, options);
1410
+ return { results: answer.results, totalCount: requireTotalCount(answer) };
1408
1411
  }
1409
1412
  /**
1410
1413
  * Helper function for pagination with explicit page size and number.
@@ -1425,8 +1428,8 @@ export class Ad4mModel {
1425
1428
  */
1426
1429
  static async paginate(perspective, pageSize, pageNumber, query, options) {
1427
1430
  const paginationQuery = { ...(query ?? {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
1428
- const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery, undefined, options);
1429
- return { results: results, totalCount, pageSize, pageNumber };
1431
+ const answer = await this.executeModelQuery(perspective, paginationQuery, undefined, options);
1432
+ return { results: answer.results, totalCount: requireTotalCount(answer), pageSize, pageNumber };
1430
1433
  }
1431
1434
  /**
1432
1435
  * Generates a SPARQL COUNT query for the model.
@@ -1454,20 +1457,20 @@ export class Ad4mModel {
1454
1457
  * ```
1455
1458
  */
1456
1459
  static async count(perspective, query, options) {
1457
- const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 }, undefined, options);
1458
- return totalCount;
1460
+ return requireTotalCount(await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0, count: true }, undefined, options));
1459
1461
  }
1460
- async setProperty(key, value, batchId) {
1462
+ /** The `executeAction` write that sets property `key` to `value`; none for an empty value. */
1463
+ async planProperty(key, value) {
1461
1464
  const metadata = this.getPropertyMetadata(key);
1462
1465
  if (!metadata) {
1463
1466
  console.warn(`Property "${key}" has no metadata, skipping`);
1464
- return;
1467
+ return [];
1465
1468
  }
1466
1469
  // Generate actions from metadata (replaces Prolog query)
1467
1470
  const actions = this.generatePropertySetterAction(key, metadata);
1468
1471
  // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal:string:)
1469
1472
  if (value === undefined || value === null || value === "") {
1470
- return;
1473
+ return [];
1471
1474
  }
1472
1475
  const mode = effectiveLiteralStorage(metadata);
1473
1476
  if (mode.kind === "custom") {
@@ -1482,7 +1485,77 @@ export class Ad4mModel {
1482
1485
  // Deterministic literal: IRI (POS-index friendly).
1483
1486
  value = valueToLiteralIri(value);
1484
1487
  }
1485
- await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value }], batchId);
1488
+ return [{ commands: actions, parameters: [{ name: "value", value }] }];
1489
+ }
1490
+ /**
1491
+ * The `executeAction` writes of a relation change: one for a set (its
1492
+ * `collectionSetter` takes every value), one per value for an add or remove.
1493
+ */
1494
+ planRelation(key, kind, value) {
1495
+ const metadata = this.getRelationOptions(key);
1496
+ if (!metadata) {
1497
+ console.warn(`Relation "${key}" has no metadata, skipping`);
1498
+ return [];
1499
+ }
1500
+ // Generate actions from metadata (replaces Prolog query)
1501
+ const actions = this.generateRelationAction(key, kind);
1502
+ if (value == null)
1503
+ return [];
1504
+ const values = Array.isArray(value) ? value : [value];
1505
+ const param = (v) => ({ name: "value", value: this.resolveRelationId(v) });
1506
+ if (kind === 'setter')
1507
+ return [{ commands: actions, parameters: values.map(param) }];
1508
+ return values.map(v => ({ commands: actions, parameters: [param(v)] }));
1509
+ }
1510
+ /**
1511
+ * Sends writes in as few `executeAction` calls as keep their links: the
1512
+ * executor runs a call's commands in order, so consecutive writes share one
1513
+ * call, each with its own parameter names. A `collectionSetter` takes every
1514
+ * parameter of its call as a member, so it goes in a call of its own. A
1515
+ * command's `local` flag is per command, so Local and Shared links mix. The
1516
+ * executor tries every parameter name at each position of each command, so
1517
+ * a call holds at most `MAX_WRITES_PER_CALL` writes.
1518
+ */
1519
+ async sendWrites(writes, batchId) {
1520
+ let group = [];
1521
+ const flush = async () => {
1522
+ if (group.length === 1) {
1523
+ await this._perspective.executeAction(group[0].commands, this._baseExpression, group[0].parameters, batchId);
1524
+ }
1525
+ else if (group.length > 1) {
1526
+ const commands = [];
1527
+ const parameters = [];
1528
+ group.forEach((write, i) => {
1529
+ // The executor substitutes a parameter name wherever it occurs in a
1530
+ // command's source, predicate or target; rename `value` the same way.
1531
+ const name = `ad4m-model-write-${i}-value`;
1532
+ const rename = (s) => (typeof s === "string" && write.parameters.length ? s.split("value").join(name) : s);
1533
+ for (const c of write.commands) {
1534
+ commands.push({ ...c, source: rename(c.source), predicate: rename(c.predicate), target: rename(c.target) });
1535
+ }
1536
+ for (const p of write.parameters)
1537
+ parameters.push({ name, value: p.value });
1538
+ });
1539
+ await this._perspective.executeAction(commands, this._baseExpression, parameters, batchId);
1540
+ }
1541
+ group = [];
1542
+ };
1543
+ for (const write of writes) {
1544
+ if (write.commands.some((c) => c.action === "collectionSetter")) {
1545
+ await flush();
1546
+ group = [write];
1547
+ await flush();
1548
+ }
1549
+ else {
1550
+ group.push(write);
1551
+ if (group.length >= MAX_WRITES_PER_CALL)
1552
+ await flush();
1553
+ }
1554
+ }
1555
+ await flush();
1556
+ }
1557
+ async setProperty(key, value, batchId) {
1558
+ await this.sendWrites(await this.planProperty(key, value), batchId);
1486
1559
  }
1487
1560
  /** Resolve a relation argument to a plain string ID. Accepts either a raw
1488
1561
  * string ID or an Ad4mModel instance (in which case `.id` is used). */
@@ -1502,75 +1575,33 @@ export class Ad4mModel {
1502
1575
  await this._perspective.updateSubject(abstractName, this._baseExpression, { [key]: { action, value: ids } }, batchId);
1503
1576
  }
1504
1577
  async setRelationValues(key, value, batchId) {
1505
- const metadata = this.getRelationOptions(key);
1506
- if (!metadata) {
1507
- console.warn(`Relation "${key}" has no metadata, skipping`);
1508
- return;
1509
- }
1510
- this._relationsWritten.add(metadata.predicate);
1511
- const abstractName = this.abstractName();
1512
- if (abstractName) {
1513
- if (value != null)
1514
- await this.relationThroughAbstract(abstractName, key, 'setter', value, batchId);
1515
- return;
1516
- }
1517
- // Generate actions from metadata (replaces Prolog query)
1518
- const actions = this.generateRelationAction(key, 'setter');
1519
- if (value != null) {
1520
- if (Array.isArray(value)) {
1521
- await this._perspective.executeAction(actions, this._baseExpression, value.map((v) => ({ name: "value", value: this.resolveRelationId(v) })), batchId);
1522
- }
1523
- else {
1524
- await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(value) }], batchId);
1525
- }
1526
- }
1578
+ await this.writeRelation(key, 'setter', value, batchId);
1527
1579
  }
1528
1580
  async addRelationValue(key, value, batchId) {
1529
- const metadata = this.getRelationOptions(key);
1530
- if (!metadata) {
1531
- console.warn(`Relation "${key}" has no metadata, skipping`);
1532
- return;
1533
- }
1534
- this._relationsWritten.add(metadata.predicate);
1535
- const abstractName = this.abstractName();
1536
- if (abstractName) {
1537
- if (value != null)
1538
- await this.relationThroughAbstract(abstractName, key, 'adder', value, batchId);
1539
- return;
1540
- }
1541
- // Generate actions from metadata (replaces Prolog query)
1542
- const actions = this.generateRelationAction(key, 'adder');
1543
- if (value != null) {
1544
- if (Array.isArray(value)) {
1545
- await Promise.all(value.map((v) => this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(v) }], batchId)));
1546
- }
1547
- else {
1548
- await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(value) }], batchId);
1549
- }
1550
- }
1581
+ await this.writeRelation(key, 'adder', value, batchId);
1551
1582
  }
1552
1583
  async removeRelationValue(key, value, batchId) {
1553
- const metadata = this.getRelationOptions(key);
1554
- if (!metadata) {
1555
- console.warn(`Relation "${key}" has no metadata, skipping`);
1556
- return;
1557
- }
1584
+ await this.writeRelation(key, 'remover', value, batchId);
1585
+ }
1586
+ /** A relation setter, adder or remover call: on a row read through an
1587
+ * abstract class it dispatches through the executor (see
1588
+ * {@link relationThroughAbstract}); otherwise its writes go out in as few
1589
+ * `executeAction` calls as {@link sendWrites} allows. */
1590
+ async writeRelation(key, kind, value, batchId) {
1591
+ const predicate = this.getRelationOptions(key)?.predicate;
1592
+ if (predicate && kind !== 'remover')
1593
+ this._relationsWritten.add(predicate);
1558
1594
  const abstractName = this.abstractName();
1559
- if (abstractName) {
1560
- if (value != null)
1561
- await this.relationThroughAbstract(abstractName, key, 'remover', value, batchId);
1595
+ if (!abstractName) {
1596
+ await this.sendWrites(this.planRelation(key, kind, value), batchId);
1562
1597
  return;
1563
1598
  }
1564
- // Generate actions from metadata (replaces Prolog query)
1565
- const actions = this.generateRelationAction(key, 'remover');
1566
- if (value != null) {
1567
- if (Array.isArray(value)) {
1568
- await Promise.all(value.map((v) => this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(v) }], batchId)));
1569
- }
1570
- else {
1571
- await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(value) }], batchId);
1572
- }
1599
+ if (!this.getRelationOptions(key)) {
1600
+ console.warn(`Relation "${key}" has no metadata, skipping`);
1601
+ return;
1573
1602
  }
1603
+ if (value != null)
1604
+ await this.relationThroughAbstract(abstractName, key, kind, value, batchId);
1574
1605
  }
1575
1606
  /**
1576
1607
  * Saves the model instance to the perspective.
@@ -1660,13 +1691,14 @@ export class Ad4mModel {
1660
1691
  const className = await this.perspective.stringOrTemplateObjectToSubjectClassName(this);
1661
1692
  await this.perspective.createSubject(className, this._baseExpression, initialValues, batchId);
1662
1693
  // Relations via innerUpdate; createSubject wrote the scalar properties.
1663
- await this.innerUpdate(false, batchId);
1694
+ const writes = await this.updateWrites(false);
1664
1695
  for (const key of deferredExpressionProps) {
1665
1696
  const value = this[key];
1666
1697
  if (value !== undefined && value !== null) {
1667
- await this.setProperty(key, value, batchId);
1698
+ writes.push(...await this.planProperty(key, value));
1668
1699
  }
1669
1700
  }
1701
+ await this.sendWrites(writes, batchId);
1670
1702
  // If we got a batchId passed in, we let the caller decide when to commit.
1671
1703
  // We can't call getData() since the instance won't exist in the perspective
1672
1704
  // until the batch is committed.
@@ -1728,6 +1760,11 @@ export class Ad4mModel {
1728
1760
  return cleanCopy;
1729
1761
  }
1730
1762
  async innerUpdate(setProperties = true, batchId) {
1763
+ await this.sendWrites(await this.updateWrites(setProperties), batchId);
1764
+ }
1765
+ /** The writes of the changed fields, in field order (see {@link sendWrites}). */
1766
+ async updateWrites(setProperties = true) {
1767
+ const writes = [];
1731
1768
  const ctor = this.constructor;
1732
1769
  // Determine which fields actually changed (skip unchanged when snapshot exists)
1733
1770
  const dirty = this._snapshot ? new Set(this.changedFields()) : null;
@@ -1764,18 +1801,21 @@ export class Ad4mModel {
1764
1801
  }
1765
1802
  if (value !== undefined && value !== null) {
1766
1803
  if (value?.action) {
1804
+ const envelopePredicate = this.getRelationOptions(key)?.predicate;
1805
+ if (envelopePredicate && value.action !== "remover")
1806
+ this._relationsWritten.add(envelopePredicate);
1767
1807
  switch (value.action) {
1768
1808
  case "setter":
1769
- await this.setRelationValues(key, value.value, batchId);
1809
+ writes.push(...this.planRelation(key, 'setter', value.value));
1770
1810
  break;
1771
1811
  case "adder":
1772
- await this.addRelationValue(key, value.value, batchId);
1812
+ writes.push(...this.planRelation(key, 'adder', value.value));
1773
1813
  break;
1774
1814
  case "remover":
1775
- await this.removeRelationValue(key, value.value, batchId);
1815
+ writes.push(...this.planRelation(key, 'remover', value.value));
1776
1816
  break;
1777
1817
  default:
1778
- await this.setRelationValues(key, value.value, batchId);
1818
+ writes.push(...this.planRelation(key, 'setter', value.value));
1779
1819
  break;
1780
1820
  }
1781
1821
  }
@@ -1783,9 +1823,11 @@ export class Ad4mModel {
1783
1823
  // Handle all arrays as relations, including empty ones (which clears the relation).
1784
1824
  // A record being created under an id minted here has no links to
1785
1825
  // clear, so an empty relation there costs a round trip and writes nothing.
1786
- if (value.length === 0 && !this._snapshot && this._idMinted && !this._relationsWritten.has(this.getRelationOptions(key)?.predicate ?? key))
1826
+ const predicate = this.getRelationOptions(key)?.predicate ?? key;
1827
+ if (value.length === 0 && !this._snapshot && this._idMinted && !this._relationsWritten.has(predicate))
1787
1828
  continue;
1788
- await this.setRelationValues(key, value, batchId);
1829
+ this._relationsWritten.add(predicate);
1830
+ writes.push(...this.planRelation(key, 'setter', value));
1789
1831
  }
1790
1832
  else if (value !== undefined && value !== null && value !== "") {
1791
1833
  // A scalar handed to a relation field is a single-member relation.
@@ -1814,7 +1856,8 @@ export class Ad4mModel {
1814
1856
  // both paths at once.
1815
1857
  const relationMeta = this.getRelationOptions(key);
1816
1858
  if (relationMeta) {
1817
- await this.setRelationValues(key, [value], batchId);
1859
+ this._relationsWritten.add(relationMeta.predicate);
1860
+ writes.push(...this.planRelation(key, 'setter', [value]));
1818
1861
  continue;
1819
1862
  }
1820
1863
  if (setProperties) {
@@ -1823,11 +1866,12 @@ export class Ad4mModel {
1823
1866
  if (propMeta?.flag) {
1824
1867
  continue;
1825
1868
  }
1826
- await this.setProperty(key, value, batchId);
1869
+ writes.push(...await this.planProperty(key, value));
1827
1870
  }
1828
1871
  }
1829
1872
  }
1830
1873
  }
1874
+ return writes;
1831
1875
  }
1832
1876
  /**
1833
1877
  * Evaluate SPARQL getters for a batch of instances on demand.
@@ -51,6 +51,9 @@ export declare class ModelQueryBuilder<T extends Ad4mModel> {
51
51
  * A failed open ends only its own query: a later call may already own
52
52
  * `currentSubscription`. */
53
53
  private live;
54
+ /** End `live` after its call failed. A later call may already own
55
+ * `currentSubscription`, so only clear it if it is still `live`. */
56
+ private endFailed;
54
57
  /**
55
58
  * Adds where conditions to the query.
56
59
  *
@@ -5,6 +5,7 @@
5
5
  * running them once or subscribing to real-time updates.
6
6
  */
7
7
  import { LiveQuery } from "../perspectives/LiveQuery";
8
+ import { requireTotalCount } from "./query-common";
8
9
  /** What a subscription compares to skip a callback whose results equal the
9
10
  * last ones emitted (a resync or a reconnect re-open of an unchanged result). */
10
11
  const fingerprint = (value) => JSON.stringify(value, (_, v) => (typeof v === 'function' ? undefined : v));
@@ -85,12 +86,17 @@ export class ModelQueryBuilder {
85
86
  return { live, initial: await live.start() };
86
87
  }
87
88
  catch (e) {
88
- live.dispose();
89
- if (this.currentSubscription === live)
90
- this.currentSubscription = undefined;
89
+ this.endFailed(live);
91
90
  throw e;
92
91
  }
93
92
  }
93
+ /** End `live` after its call failed. A later call may already own
94
+ * `currentSubscription`, so only clear it if it is still `live`. */
95
+ endFailed(live) {
96
+ live.dispose();
97
+ if (this.currentSubscription === live)
98
+ this.currentSubscription = undefined;
99
+ }
94
100
  /**
95
101
  * Adds where conditions to the query.
96
102
  *
@@ -477,8 +483,7 @@ export class ModelQueryBuilder {
477
483
  * ```
478
484
  */
479
485
  async count() {
480
- const { totalCount } = await this.execute({ ...this.queryParams, limit: 0 });
481
- return totalCount;
486
+ return requireTotalCount(await this.execute({ ...this.queryParams, limit: 0, count: true }));
482
487
  }
483
488
  /**
484
489
  * Gets the total count of matching entities using SPARQL.
@@ -517,8 +522,23 @@ export class ModelQueryBuilder {
517
522
  */
518
523
  async countSubscribe(callback) {
519
524
  this.dispose();
520
- const { initial } = await this.live({ ...this.queryParams, limit: 0 }, (raw) => callback(raw.totalCount ?? 0));
521
- return initial.totalCount ?? 0;
525
+ // As paginateSubscribe: a push without the asked-for count is logged and
526
+ // skipped, since a throw here would reach the client's update dispatch.
527
+ const { live, initial } = await this.live({ ...this.queryParams, limit: 0, count: true }, (raw) => {
528
+ try {
529
+ callback(requireTotalCount(raw));
530
+ }
531
+ catch (e) {
532
+ console.error('Count subscription error:', e);
533
+ }
534
+ });
535
+ try {
536
+ return requireTotalCount(initial);
537
+ }
538
+ catch (e) {
539
+ this.endFailed(live);
540
+ throw e;
541
+ }
522
542
  }
523
543
  /**
524
544
  * Subscribes to count updates using SPARQL.
@@ -544,8 +564,8 @@ export class ModelQueryBuilder {
544
564
  */
545
565
  async paginate(pageSize, pageNumber) {
546
566
  const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
547
- const { results, totalCount } = await this.execute(paginationQuery);
548
- return { results, totalCount, pageSize, pageNumber };
567
+ const answer = await this.execute(paginationQuery);
568
+ return { results: answer.results, totalCount: requireTotalCount(answer), pageSize, pageNumber };
549
569
  }
550
570
  /**
551
571
  * Gets a page of results using SPARQL.
@@ -608,9 +628,10 @@ export class ModelQueryBuilder {
608
628
  const results = this.parse(raw);
609
629
  const fp = fingerprint([results, raw?.totalCount]);
610
630
  this.takeSnapshots(results);
611
- return { page: { results, totalCount: raw?.totalCount, pageSize, pageNumber }, fp };
631
+ // `count: true` is set above, so the executor sends a total.
632
+ return { page: { results, totalCount: requireTotalCount(raw), pageSize, pageNumber }, fp };
612
633
  };
613
- const { initial } = await this.live(paginatedQuery, (raw) => {
634
+ const { live, initial } = await this.live(paginatedQuery, (raw) => {
614
635
  try {
615
636
  const { page, fp } = toPage(raw);
616
637
  if (fp === lastFingerprint)
@@ -622,9 +643,16 @@ export class ModelQueryBuilder {
622
643
  console.error('Paginate subscription error:', e);
623
644
  }
624
645
  });
625
- const { page, fp } = toPage(initial);
626
- lastFingerprint = fp;
627
- return page;
646
+ let first;
647
+ try {
648
+ first = toPage(initial);
649
+ }
650
+ catch (e) {
651
+ this.endFailed(live);
652
+ throw e;
653
+ }
654
+ lastFingerprint = first.fp;
655
+ return first.page;
628
656
  }
629
657
  /**
630
658
  * Subscribes to paginated results updates using SPARQL.
@@ -16,4 +16,3 @@ export * from "./hydration";
16
16
  export * from "./ModelQueryBuilder";
17
17
  export * from "./sdna";
18
18
  export * from "./shacl-gen";
19
- export * from "./query-cache";
@@ -16,4 +16,3 @@ export * from "./hydration";
16
16
  export * from "./ModelQueryBuilder";
17
17
  export * from "./sdna";
18
18
  export * from "./shacl-gen";
19
- export * from "./query-cache";
@@ -2,6 +2,14 @@
2
2
  * Shared query helpers used by both the Prolog and SPARQL query pipelines.
3
3
  */
4
4
  import type { Scope, TraverseScope } from "./types";
5
+ /**
6
+ * The `totalCount` of a model query sent with `count: true`. The executor
7
+ * answers such a query with a count, so an answer without one is an error,
8
+ * not zero matches.
9
+ */
10
+ export declare function requireTotalCount(answer: {
11
+ totalCount?: number;
12
+ } | null | undefined): number;
5
13
  /**
6
14
  * Resolves the predicate for a parent query.
7
15
  *
@@ -3,6 +3,18 @@
3
3
  */
4
4
  import { isContainedScope, isContainmentTraversal, isTraverseScope } from "./types";
5
5
  import { getRelationsMetadata } from "./decorators";
6
+ /**
7
+ * The `totalCount` of a model query sent with `count: true`. The executor
8
+ * answers such a query with a count, so an answer without one is an error,
9
+ * not zero matches.
10
+ */
11
+ export function requireTotalCount(answer) {
12
+ const totalCount = answer?.totalCount;
13
+ if (typeof totalCount !== "number") {
14
+ throw new Error("model query asked for a count (count: true) but the answer has no totalCount");
15
+ }
16
+ return totalCount;
17
+ }
6
18
  /**
7
19
  * Resolves the predicate for a parent query.
8
20
  *
@@ -292,6 +292,8 @@ isAbstract) {
292
292
  // Encode relation kind so the executor can derive direction and
293
293
  // scalar-vs-collection rendering without consulting the JS class.
294
294
  relShape.relationKind = relMeta.kind;
295
+ if (relMeta.polymorphic)
296
+ relShape.polymorphic = true;
295
297
  // Scalar relations cap at 1.
296
298
  if (relMeta.kind === 'hasOne' || relMeta.kind === 'belongsToOne') {
297
299
  relShape.maxCount = 1;