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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/lib/index.cjs +548 -477
  2. package/lib/index.js +548 -473
  3. package/lib/src/agent/AgentClient.d.ts +9 -8
  4. package/lib/src/agent/AgentClient.js +46 -67
  5. package/lib/src/cache/KeyedCache.d.ts +51 -0
  6. package/lib/src/cache/KeyedCache.js +142 -0
  7. package/lib/src/expression/ExpressionClient.d.ts +14 -3
  8. package/lib/src/expression/ExpressionClient.js +49 -111
  9. package/lib/src/generated/api/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 +125 -82
  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/types.d.ts +12 -3
  26. package/lib/src/perspectives/FlowModels.js +1 -1
  27. package/lib/src/perspectives/LiveQuery.d.ts +1 -1
  28. package/lib/src/perspectives/PerspectiveClient.d.ts +17 -6
  29. package/lib/src/perspectives/PerspectiveClient.js +83 -44
  30. package/lib/src/perspectives/PerspectiveProxy.d.ts +19 -10
  31. package/lib/src/perspectives/PerspectiveProxy.js +31 -69
  32. package/package.json +2 -2
  33. package/src/Ad4mClient.test.ts +17 -6
  34. package/src/agent/AgentClient.ts +46 -74
  35. package/src/cache/KeyedCache.test.ts +162 -0
  36. package/src/cache/KeyedCache.ts +179 -0
  37. package/src/cache/cache.test.ts +294 -71
  38. package/src/expression/ExpressionClient.ts +46 -131
  39. package/src/generated/api/ExpressionLookupError.ts +6 -0
  40. package/src/generated/api/ExpressionManyEntry.ts +8 -0
  41. package/src/generated/api/FlowFiredEntry.ts +11 -0
  42. package/src/generated/api/PerspectiveFlowFiredParams.ts +3 -3
  43. package/src/generated/api/RpcMethods.ts +4 -2
  44. package/src/model/Ad4mModel.test.ts +237 -43
  45. package/src/model/Ad4mModel.ts +132 -98
  46. package/src/model/ModelQueryBuilder.ts +41 -15
  47. package/src/model/count-result-type.test.ts +72 -0
  48. package/src/model/index.ts +0 -1
  49. package/src/model/query-common.ts +13 -0
  50. package/src/model/relation-filtering.test.ts +3 -5
  51. package/src/model/types.ts +9 -3
  52. package/src/model/write-round-trips.test.ts +30 -6
  53. package/src/perspectives/FlowModels.ts +1 -1
  54. package/src/perspectives/LiveQuery.ts +1 -1
  55. package/src/perspectives/PerspectiveClient.test.ts +287 -0
  56. package/src/perspectives/PerspectiveClient.ts +101 -66
  57. package/src/perspectives/PerspectiveProxy.test.ts +6 -14
  58. package/src/perspectives/PerspectiveProxy.ts +33 -67
  59. package/src/perspectives/TextContent.test.ts +0 -16
  60. package/src/perspectives/shacl-rpc.test.ts +1 -1
  61. package/lib/src/model/query-cache.d.ts +0 -30
  62. package/lib/src/model/query-cache.js +0 -66
  63. package/src/model/query-cache.test.ts +0 -54
  64. 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";
@@ -348,6 +348,8 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
348
348
  }
349
349
  return instance;
350
350
  }
351
+ /** The most writes `sendWrites` joins into one `executeAction` call. */
352
+ const MAX_WRITES_PER_CALL = 200;
351
353
  /**
352
354
  * Put `childId` under `parent`. A containment scope `{ id }` writes through the
353
355
  * built-in `Container` (#1446): the executor runs the adder of the parent's own
@@ -1403,8 +1405,8 @@ export class Ad4mModel {
1403
1405
  * ```
1404
1406
  */
1405
1407
  static async findAllAndCount(perspective, query, options) {
1406
- const out = await this.executeModelQuery(perspective, (query ?? {}), undefined, options);
1407
- return out;
1408
+ const answer = await this.executeModelQuery(perspective, { ...(query ?? {}), count: true }, undefined, options);
1409
+ return { results: answer.results, totalCount: requireTotalCount(answer) };
1408
1410
  }
1409
1411
  /**
1410
1412
  * Helper function for pagination with explicit page size and number.
@@ -1425,8 +1427,8 @@ export class Ad4mModel {
1425
1427
  */
1426
1428
  static async paginate(perspective, pageSize, pageNumber, query, options) {
1427
1429
  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 };
1430
+ const answer = await this.executeModelQuery(perspective, paginationQuery, undefined, options);
1431
+ return { results: answer.results, totalCount: requireTotalCount(answer), pageSize, pageNumber };
1430
1432
  }
1431
1433
  /**
1432
1434
  * Generates a SPARQL COUNT query for the model.
@@ -1454,20 +1456,20 @@ export class Ad4mModel {
1454
1456
  * ```
1455
1457
  */
1456
1458
  static async count(perspective, query, options) {
1457
- const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 }, undefined, options);
1458
- return totalCount;
1459
+ return requireTotalCount(await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0, count: true }, undefined, options));
1459
1460
  }
1460
- async setProperty(key, value, batchId) {
1461
+ /** The `executeAction` write that sets property `key` to `value`; none for an empty value. */
1462
+ async planProperty(key, value) {
1461
1463
  const metadata = this.getPropertyMetadata(key);
1462
1464
  if (!metadata) {
1463
1465
  console.warn(`Property "${key}" has no metadata, skipping`);
1464
- return;
1466
+ return [];
1465
1467
  }
1466
1468
  // Generate actions from metadata (replaces Prolog query)
1467
1469
  const actions = this.generatePropertySetterAction(key, metadata);
1468
1470
  // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal:string:)
1469
1471
  if (value === undefined || value === null || value === "") {
1470
- return;
1472
+ return [];
1471
1473
  }
1472
1474
  const mode = effectiveLiteralStorage(metadata);
1473
1475
  if (mode.kind === "custom") {
@@ -1482,7 +1484,77 @@ export class Ad4mModel {
1482
1484
  // Deterministic literal: IRI (POS-index friendly).
1483
1485
  value = valueToLiteralIri(value);
1484
1486
  }
1485
- await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value }], batchId);
1487
+ return [{ commands: actions, parameters: [{ name: "value", value }] }];
1488
+ }
1489
+ /**
1490
+ * The `executeAction` writes of a relation change: one for a set (its
1491
+ * `collectionSetter` takes every value), one per value for an add or remove.
1492
+ */
1493
+ planRelation(key, kind, value) {
1494
+ const metadata = this.getRelationOptions(key);
1495
+ if (!metadata) {
1496
+ console.warn(`Relation "${key}" has no metadata, skipping`);
1497
+ return [];
1498
+ }
1499
+ // Generate actions from metadata (replaces Prolog query)
1500
+ const actions = this.generateRelationAction(key, kind);
1501
+ if (value == null)
1502
+ return [];
1503
+ const values = Array.isArray(value) ? value : [value];
1504
+ const param = (v) => ({ name: "value", value: this.resolveRelationId(v) });
1505
+ if (kind === 'setter')
1506
+ return [{ commands: actions, parameters: values.map(param) }];
1507
+ return values.map(v => ({ commands: actions, parameters: [param(v)] }));
1508
+ }
1509
+ /**
1510
+ * Sends writes in as few `executeAction` calls as keep their links: the
1511
+ * executor runs a call's commands in order, so consecutive writes share one
1512
+ * call, each with its own parameter names. A `collectionSetter` takes every
1513
+ * parameter of its call as a member, so it goes in a call of its own. A
1514
+ * command's `local` flag is per command, so Local and Shared links mix. The
1515
+ * executor tries every parameter name at each position of each command, so
1516
+ * a call holds at most `MAX_WRITES_PER_CALL` writes.
1517
+ */
1518
+ async sendWrites(writes, batchId) {
1519
+ let group = [];
1520
+ const flush = async () => {
1521
+ if (group.length === 1) {
1522
+ await this._perspective.executeAction(group[0].commands, this._baseExpression, group[0].parameters, batchId);
1523
+ }
1524
+ else if (group.length > 1) {
1525
+ const commands = [];
1526
+ const parameters = [];
1527
+ group.forEach((write, i) => {
1528
+ // The executor substitutes a parameter name wherever it occurs in a
1529
+ // command's source, predicate or target; rename `value` the same way.
1530
+ const name = `ad4m-model-write-${i}-value`;
1531
+ const rename = (s) => (typeof s === "string" && write.parameters.length ? s.split("value").join(name) : s);
1532
+ for (const c of write.commands) {
1533
+ commands.push({ ...c, source: rename(c.source), predicate: rename(c.predicate), target: rename(c.target) });
1534
+ }
1535
+ for (const p of write.parameters)
1536
+ parameters.push({ name, value: p.value });
1537
+ });
1538
+ await this._perspective.executeAction(commands, this._baseExpression, parameters, batchId);
1539
+ }
1540
+ group = [];
1541
+ };
1542
+ for (const write of writes) {
1543
+ if (write.commands.some((c) => c.action === "collectionSetter")) {
1544
+ await flush();
1545
+ group = [write];
1546
+ await flush();
1547
+ }
1548
+ else {
1549
+ group.push(write);
1550
+ if (group.length >= MAX_WRITES_PER_CALL)
1551
+ await flush();
1552
+ }
1553
+ }
1554
+ await flush();
1555
+ }
1556
+ async setProperty(key, value, batchId) {
1557
+ await this.sendWrites(await this.planProperty(key, value), batchId);
1486
1558
  }
1487
1559
  /** Resolve a relation argument to a plain string ID. Accepts either a raw
1488
1560
  * string ID or an Ad4mModel instance (in which case `.id` is used). */
@@ -1502,75 +1574,33 @@ export class Ad4mModel {
1502
1574
  await this._perspective.updateSubject(abstractName, this._baseExpression, { [key]: { action, value: ids } }, batchId);
1503
1575
  }
1504
1576
  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
- }
1577
+ await this.writeRelation(key, 'setter', value, batchId);
1527
1578
  }
1528
1579
  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
- }
1580
+ await this.writeRelation(key, 'adder', value, batchId);
1551
1581
  }
1552
1582
  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
- }
1583
+ await this.writeRelation(key, 'remover', value, batchId);
1584
+ }
1585
+ /** A relation setter, adder or remover call: on a row read through an
1586
+ * abstract class it dispatches through the executor (see
1587
+ * {@link relationThroughAbstract}); otherwise its writes go out in as few
1588
+ * `executeAction` calls as {@link sendWrites} allows. */
1589
+ async writeRelation(key, kind, value, batchId) {
1590
+ const predicate = this.getRelationOptions(key)?.predicate;
1591
+ if (predicate && kind !== 'remover')
1592
+ this._relationsWritten.add(predicate);
1558
1593
  const abstractName = this.abstractName();
1559
- if (abstractName) {
1560
- if (value != null)
1561
- await this.relationThroughAbstract(abstractName, key, 'remover', value, batchId);
1594
+ if (!abstractName) {
1595
+ await this.sendWrites(this.planRelation(key, kind, value), batchId);
1562
1596
  return;
1563
1597
  }
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
- }
1598
+ if (!this.getRelationOptions(key)) {
1599
+ console.warn(`Relation "${key}" has no metadata, skipping`);
1600
+ return;
1573
1601
  }
1602
+ if (value != null)
1603
+ await this.relationThroughAbstract(abstractName, key, kind, value, batchId);
1574
1604
  }
1575
1605
  /**
1576
1606
  * Saves the model instance to the perspective.
@@ -1660,13 +1690,14 @@ export class Ad4mModel {
1660
1690
  const className = await this.perspective.stringOrTemplateObjectToSubjectClassName(this);
1661
1691
  await this.perspective.createSubject(className, this._baseExpression, initialValues, batchId);
1662
1692
  // Relations via innerUpdate; createSubject wrote the scalar properties.
1663
- await this.innerUpdate(false, batchId);
1693
+ const writes = await this.updateWrites(false);
1664
1694
  for (const key of deferredExpressionProps) {
1665
1695
  const value = this[key];
1666
1696
  if (value !== undefined && value !== null) {
1667
- await this.setProperty(key, value, batchId);
1697
+ writes.push(...await this.planProperty(key, value));
1668
1698
  }
1669
1699
  }
1700
+ await this.sendWrites(writes, batchId);
1670
1701
  // If we got a batchId passed in, we let the caller decide when to commit.
1671
1702
  // We can't call getData() since the instance won't exist in the perspective
1672
1703
  // until the batch is committed.
@@ -1728,6 +1759,11 @@ export class Ad4mModel {
1728
1759
  return cleanCopy;
1729
1760
  }
1730
1761
  async innerUpdate(setProperties = true, batchId) {
1762
+ await this.sendWrites(await this.updateWrites(setProperties), batchId);
1763
+ }
1764
+ /** The writes of the changed fields, in field order (see {@link sendWrites}). */
1765
+ async updateWrites(setProperties = true) {
1766
+ const writes = [];
1731
1767
  const ctor = this.constructor;
1732
1768
  // Determine which fields actually changed (skip unchanged when snapshot exists)
1733
1769
  const dirty = this._snapshot ? new Set(this.changedFields()) : null;
@@ -1764,18 +1800,21 @@ export class Ad4mModel {
1764
1800
  }
1765
1801
  if (value !== undefined && value !== null) {
1766
1802
  if (value?.action) {
1803
+ const envelopePredicate = this.getRelationOptions(key)?.predicate;
1804
+ if (envelopePredicate && value.action !== "remover")
1805
+ this._relationsWritten.add(envelopePredicate);
1767
1806
  switch (value.action) {
1768
1807
  case "setter":
1769
- await this.setRelationValues(key, value.value, batchId);
1808
+ writes.push(...this.planRelation(key, 'setter', value.value));
1770
1809
  break;
1771
1810
  case "adder":
1772
- await this.addRelationValue(key, value.value, batchId);
1811
+ writes.push(...this.planRelation(key, 'adder', value.value));
1773
1812
  break;
1774
1813
  case "remover":
1775
- await this.removeRelationValue(key, value.value, batchId);
1814
+ writes.push(...this.planRelation(key, 'remover', value.value));
1776
1815
  break;
1777
1816
  default:
1778
- await this.setRelationValues(key, value.value, batchId);
1817
+ writes.push(...this.planRelation(key, 'setter', value.value));
1779
1818
  break;
1780
1819
  }
1781
1820
  }
@@ -1783,9 +1822,11 @@ export class Ad4mModel {
1783
1822
  // Handle all arrays as relations, including empty ones (which clears the relation).
1784
1823
  // A record being created under an id minted here has no links to
1785
1824
  // 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))
1825
+ const predicate = this.getRelationOptions(key)?.predicate ?? key;
1826
+ if (value.length === 0 && !this._snapshot && this._idMinted && !this._relationsWritten.has(predicate))
1787
1827
  continue;
1788
- await this.setRelationValues(key, value, batchId);
1828
+ this._relationsWritten.add(predicate);
1829
+ writes.push(...this.planRelation(key, 'setter', value));
1789
1830
  }
1790
1831
  else if (value !== undefined && value !== null && value !== "") {
1791
1832
  // A scalar handed to a relation field is a single-member relation.
@@ -1814,7 +1855,8 @@ export class Ad4mModel {
1814
1855
  // both paths at once.
1815
1856
  const relationMeta = this.getRelationOptions(key);
1816
1857
  if (relationMeta) {
1817
- await this.setRelationValues(key, [value], batchId);
1858
+ this._relationsWritten.add(relationMeta.predicate);
1859
+ writes.push(...this.planRelation(key, 'setter', [value]));
1818
1860
  continue;
1819
1861
  }
1820
1862
  if (setProperties) {
@@ -1823,11 +1865,12 @@ export class Ad4mModel {
1823
1865
  if (propMeta?.flag) {
1824
1866
  continue;
1825
1867
  }
1826
- await this.setProperty(key, value, batchId);
1868
+ writes.push(...await this.planProperty(key, value));
1827
1869
  }
1828
1870
  }
1829
1871
  }
1830
1872
  }
1873
+ return writes;
1831
1874
  }
1832
1875
  /**
1833
1876
  * 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
  *