@coasys/ad4m 0.13.1-staging.2 → 0.13.1-staging.3

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 (43) hide show
  1. package/lib/index.cjs +584 -203
  2. package/lib/index.js +581 -204
  3. package/lib/src/Ad4mClient.d.ts +7 -0
  4. package/lib/src/Ad4mClient.js +9 -0
  5. package/lib/src/apiClient.d.ts +13 -0
  6. package/lib/src/apiClient.js +67 -12
  7. package/lib/src/generated/api/AuthInfo.d.ts +4 -0
  8. package/lib/src/generated/api/RuntimeInfo.d.ts +5 -0
  9. package/lib/src/index.d.ts +1 -0
  10. package/lib/src/index.js +1 -0
  11. package/lib/src/model/Ad4mModel.js +45 -18
  12. package/lib/src/model/ModelQueryBuilder.d.ts +7 -3
  13. package/lib/src/model/ModelQueryBuilder.js +9 -4
  14. package/lib/src/model/query-common.js +7 -1
  15. package/lib/src/model/types.d.ts +45 -2
  16. package/lib/src/model/types.js +8 -0
  17. package/lib/src/perspectives/Container.d.ts +41 -0
  18. package/lib/src/perspectives/Container.js +62 -0
  19. package/lib/src/perspectives/PerspectiveProxy.d.ts +6 -3
  20. package/lib/src/perspectives/PerspectiveProxy.js +10 -4
  21. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +94 -12
  22. package/lib/src/perspectives/WakerSubscriptionManager.js +273 -72
  23. package/lib/src/runtime/RuntimeTypes.d.ts +2 -0
  24. package/package.json +2 -2
  25. package/src/Ad4mClient.test.ts +1 -1
  26. package/src/Ad4mClient.ts +10 -0
  27. package/src/apiClient.test.ts +128 -2
  28. package/src/apiClient.ts +64 -11
  29. package/src/generated/api/AuthInfo.ts +6 -1
  30. package/src/generated/api/RuntimeInfo.ts +6 -1
  31. package/src/index.ts +1 -0
  32. package/src/model/Ad4mModel.ts +51 -19
  33. package/src/model/ModelQueryBuilder.ts +9 -6
  34. package/src/model/containment-scope.test.ts +104 -0
  35. package/src/model/query-common.ts +10 -1
  36. package/src/model/types.ts +56 -2
  37. package/src/perspectives/Container.test.ts +65 -0
  38. package/src/perspectives/Container.ts +46 -0
  39. package/src/perspectives/PerspectiveProxy.test.ts +11 -0
  40. package/src/perspectives/PerspectiveProxy.ts +10 -4
  41. package/src/perspectives/WakerSubscriptionManager.test.ts +398 -80
  42. package/src/perspectives/WakerSubscriptionManager.ts +318 -82
  43. package/src/runtime/RuntimeTypes.ts +2 -0
@@ -103,11 +103,43 @@ export type Order = { [propertyName: string]: "ASC" | "DESC" };
103
103
  * **Traverse form** — bounded traversal from one or more anchors, for reading
104
104
  * a tree rather than one node's children. Read-only: AutoProcessor's write
105
105
  * scopes reject it, because it names no single parent to write under.
106
+ *
107
+ * **Containment form** — `{ id }` alone: everything contained in `id`, through
108
+ * the built-in `Container`. That is the targets of `id`'s `ad4m://has_child`
109
+ * links, whatever `id` is, and the targets of the `children` relation (by name,
110
+ * or aliased to `children`) of every class `id` is an instance of. The caller
111
+ * names no class and no predicate; the executor resolves them from the
112
+ * installed classes. See {@link ContainedScope}.
106
113
  */
107
114
  export type Scope =
108
115
  | { model: typeof Ad4mModel; id: string; field?: string }
109
116
  | { id: string; predicate: string }
110
- | TraverseScope;
117
+ | TraverseScope
118
+ | ContainedScope;
119
+
120
+ /**
121
+ * Contained in `id`, through `Container`: `{ id }` and nothing else. A
122
+ * misspelt extra field (`{ id, predicat }`) is an error in the executor,
123
+ * never a containment read.
124
+ */
125
+ export interface ContainedScope {
126
+ id: string;
127
+ // Never set: they make the other forms. Declared so the type does not
128
+ // also describe `{ id, predicate }` or `{ id, model }`.
129
+ predicate?: never;
130
+ model?: never;
131
+ field?: never;
132
+ }
133
+
134
+ /** Whether this traversal follows containment rather than a named predicate. */
135
+ export function isContainmentTraversal(scope: Scope): scope is TraverseByContainment {
136
+ return isTraverseScope(scope) && !('predicate' in scope && scope.predicate) && !('model' in scope && scope.model);
137
+ }
138
+
139
+ /** Whether this scope is the containment form, `{ id }` alone. */
140
+ export function isContainedScope(scope: Scope): scope is ContainedScope {
141
+ return !isTraverseScope(scope) && !('predicate' in scope) && !('model' in scope);
142
+ }
111
143
 
112
144
  /**
113
145
  * Walk a predicate from several anchors at once, and optionally all the way
@@ -121,7 +153,24 @@ export type Scope =
121
153
  * or by the model and relation that own it. See {@link TraverseByPredicate} and
122
154
  * {@link TraverseByModel}.
123
155
  */
124
- export type TraverseScope = TraverseByPredicate | TraverseByModel;
156
+ export type TraverseScope = TraverseByPredicate | TraverseByModel | TraverseByContainment;
157
+
158
+ /**
159
+ * A traversal over containment, through the built-in `Container`: it names no
160
+ * predicate, and follows every edge the executor resolves from the installed
161
+ * classes — `ad4m://has_child` on any node, and each class's own `children`
162
+ * relation on its instances. `direction: 'in'` from a record reaches whatever
163
+ * holds it: `Container.findAll(p, { parent: { ids: [x], direction: 'in' } })`.
164
+ *
165
+ * The rows are the queried class; the nodes a transitive walk passes through
166
+ * are any container. With no `order`, a transitive walk's rows come nearest
167
+ * first. `levels` is refused on it, and so is `limitPerAnchor` on a
168
+ * transitive one; bound it with `maxDepth`.
169
+ */
170
+ export interface TraverseByContainment extends TraverseOptions {
171
+ predicate?: never;
172
+ model?: never;
173
+ }
125
174
 
126
175
  /** A traversal naming its predicate literally, as the Raw scope does. */
127
176
  export interface TraverseByPredicate extends TraverseOptions {
@@ -194,6 +243,11 @@ export interface TraverseOptions {
194
243
  * every depth.
195
244
  */
196
245
  limitPerAnchor?: number;
246
+ /**
247
+ * With `transitive`, stop the walk after this many hops (`1` is the direct
248
+ * neighbours). Refused without `transitive` and alongside `levels`.
249
+ */
250
+ maxDepth?: number;
197
251
  /**
198
252
  * Walk the relation level by level, keeping this many results per anchor at each depth —
199
253
  * `[10, 5, 3]` is "ten replies, five under each of those, three under each of *those*".
@@ -0,0 +1,65 @@
1
+ /**
2
+ * The SDK's Container mirrors the executor's built-in
3
+ * (`hardwired_sdna/container.json`), is read by its URI, and is never
4
+ * registered in a perspective (#1446).
5
+ */
6
+ import * as fs from "fs";
7
+ import * as path from "path";
8
+ import { Container } from "./Container";
9
+ import { Ad4mModel } from "../model/Ad4mModel";
10
+ import { HasMany, Model } from "../model/decorators";
11
+
12
+ const SDNA = JSON.parse(
13
+ fs.readFileSync(
14
+ path.resolve(__dirname, "../../../rust-executor/src/perspectives/hardwired_sdna/container.json"),
15
+ "utf-8",
16
+ ),
17
+ );
18
+
19
+ describe("Container", () => {
20
+ it("matches the executor's built-in shape", () => {
21
+ const { shape } = (Container as any).generateSHACL();
22
+ expect(shape.targetClass).toBe(SDNA.target_class);
23
+ expect(shape.isAbstract).toBe(SDNA.abstract);
24
+ expect(shape.properties.map((p: any) => [p.path, p.name])).toEqual(
25
+ SDNA.properties.map((p: any) => [p.path, p.name]),
26
+ );
27
+ });
28
+
29
+ it("is queried by its URI", () => {
30
+ expect((Container as any).prepareModelQueryParams({}).className).toBe("ad4m://Container");
31
+ });
32
+
33
+ it("is implemented through a class's own relation, aliased to children", () => {
34
+ @Model({ name: "ImplBlock", implements: [Container] })
35
+ class ImplBlock extends Ad4mModel {
36
+ @HasMany({ through: "we://child", alias: { Container: "children" } })
37
+ blocks: string[] = [];
38
+ }
39
+ // The executor finds the relation by the alias in the shape, not by `implements`.
40
+ const { shape } = (ImplBlock as any).generateSHACL();
41
+ const blocks = shape.properties.find((p: any) => p.name === "blocks");
42
+ expect([blocks.path, blocks.alias]).toEqual(["we://child", { Container: "children" }]);
43
+ });
44
+
45
+ it("is not implemented by a relation that answers to another name", () => {
46
+ expect(() => {
47
+ @Model({ name: "UnaliasedBlock", implements: [Container] })
48
+ class UnaliasedBlock extends Ad4mModel {
49
+ @HasMany({ through: "we://child" })
50
+ blocks: string[] = [];
51
+ }
52
+ }).toThrow("UnaliasedBlock implements Container but has no relation or alias named `children`");
53
+ });
54
+
55
+ it("register() writes nothing", async () => {
56
+ const { PerspectiveProxy } = await import("./PerspectiveProxy");
57
+ const calls: string[] = [];
58
+ const proxy = Object.create(PerspectiveProxy.prototype);
59
+ Object.defineProperty(proxy, "addSdna", { value: () => { calls.push("addSdna"); } });
60
+ Object.defineProperty(proxy, "addSdnaAll", { value: () => { calls.push("addSdnaAll"); } });
61
+ await expect(proxy.ensureSubjectClasses([Container])).resolves.toBeUndefined();
62
+ await expect(proxy.ensureSubjectClass(Container)).resolves.toBeUndefined();
63
+ expect(calls).toEqual([]);
64
+ });
65
+ });
@@ -0,0 +1,46 @@
1
+ import { Ad4mModel } from "../model/Ad4mModel";
2
+ import { HasMany, Model } from "../model/decorators";
3
+
4
+ /**
5
+ * The built-in abstract class `Container { children }` (#1446): what holds
6
+ * other records — a channel, a thread, a post, a call, a document, a board.
7
+ *
8
+ * X is contained in P when `P ad4m://has_child X` exists, whatever P is (an
9
+ * instance of any class, or a node no class describes, such as
10
+ * `ad4m://self`), or when P is an instance of a class whose `children`
11
+ * relation (by name, or aliased to `children`) links X:
12
+ *
13
+ * ```typescript
14
+ * @Model({ name: "Block", implements: [Container] })
15
+ * class Block extends Ad4mModel {
16
+ * @HasMany({ through: "we://child", alias: { Container: "children" } })
17
+ * blocks: string[] = [];
18
+ * }
19
+ *
20
+ * // Messages held by P, through has_child or a Block's we://child:
21
+ * await Message.findAll(perspective, { parent: { id: P } });
22
+ * // Everything that holds X:
23
+ * await Container.findAll(perspective, { parent: { ids: [X], direction: "in" } });
24
+ * ```
25
+ *
26
+ * A row's `children` is everything it holds, merged across its classes. A
27
+ * node no class describes is a row of its own when it holds something by
28
+ * `has_child`. Always scope a `Container` query (`where: { id }`, a
29
+ * `children` filter or `parent`): unscoped, it reads every holder in the
30
+ * perspective.
31
+ *
32
+ * Built in: the executor declares it (mirrors
33
+ * `rust-executor/src/perspectives/hardwired_sdna/container.json`) and reads
34
+ * it by its URI, `ad4m://Container`, so a perspective never stores it and an
35
+ * app class named `Container` does not replace it. `register()` on it writes
36
+ * nothing.
37
+ */
38
+ @Model({ name: "Container", abstract: true })
39
+ export class Container extends Ad4mModel {
40
+ /** The URI the executor reads it by. */
41
+ static readonly builtinUri = "ad4m://Container";
42
+
43
+ /** What it holds, whatever their class. */
44
+ @HasMany({ through: "ad4m://has_child" })
45
+ children: string[] = [];
46
+ }
@@ -33,6 +33,17 @@ describe('QuerySubscriptionProxy', () => {
33
33
  expect(client.subscribeQuery).toHaveBeenCalledWith('perspective-1', 'SELECT * WHERE { ?s ?p ?o }');
34
34
  });
35
35
 
36
+ it('opens a model query over a class when given one', async () => {
37
+ const modelSubscribe = jest.fn().mockResolvedValue({ subscriptionId: 'sub-2', result: { instances: [{ id: 'a' }], totalCount: 1 }, revision: 0 });
38
+ const { client } = liveClient(jest.fn());
39
+ client.modelSubscribe = modelSubscribe;
40
+ const subscription = new QuerySubscriptionProxy('perspective-1', '{"limit":1}', client, 'ad4m://TextContent');
41
+ await subscription.subscribe();
42
+ expect(modelSubscribe).toHaveBeenCalledWith('perspective-1', 'ad4m://TextContent', '{"limit":1}');
43
+ expect(client.subscribeQuery).not.toHaveBeenCalled();
44
+ expect(subscription.result).toEqual({ instances: [{ id: 'a' }], totalCount: 1 });
45
+ });
46
+
36
47
  it('rejects initialized when the subscribe call fails', async () => {
37
48
  const { client } = liveClient(jest.fn().mockRejectedValue(new Error('locked')));
38
49
  const subscription = new QuerySubscriptionProxy('p', 'SELECT ?x WHERE { ?x ?p ?o }', client);
@@ -41,7 +41,7 @@ function extractNamespaceFromUri(uri: string): string {
41
41
  }
42
42
 
43
43
 
44
- /** A live SPARQL query with its latest result.
44
+ /** A live SPARQL or model query with its latest result.
45
45
  *
46
46
  * `subscribe()` opens the query and resolves once the first result is in;
47
47
  * `onResult()` callbacks then get every later result. The executor sends
@@ -61,8 +61,14 @@ export class QuerySubscriptionProxy {
61
61
  #initResolve?: (value: boolean) => void;
62
62
  #initReject?: (reason?: any) => void;
63
63
 
64
- constructor(uuid: string, query: string, client: PerspectiveClient) {
65
- this.#live = new LiveQuery(client, uuid, () => client.subscribeQuery(uuid, query), result => this.#deliver(result));
64
+ /** With `className`, `query` is a model query (JSON) over that class or
65
+ * union of classes, opened with `modelSubscribe`; results are
66
+ * `{ instances, totalCount }`. Without it, `query` is SPARQL. */
67
+ constructor(uuid: string, query: string, client: PerspectiveClient, className?: string | string[]) {
68
+ const open = className === undefined
69
+ ? () => client.subscribeQuery(uuid, query)
70
+ : () => client.modelSubscribe(uuid, className, query);
71
+ this.#live = new LiveQuery(client, uuid, open, result => this.#deliver(result));
66
72
  this.#initialized = new Promise<boolean>((resolve, reject) => {
67
73
  this.#initResolve = resolve;
68
74
  this.#initReject = reject;
@@ -567,7 +573,7 @@ export class PerspectiveProxy {
567
573
  *
568
574
  * The state is not stored on the graph: the engine derives it from the
569
575
  * signed proposals and keeps what it derived per agent, outside the
570
- * perspective. So no other agent — a co-owner on the same node included —
576
+ * perspective. So no other agent — a co-owner on the same executor included —
571
577
  * can read or write your entries, and a link query never sees them.
572
578
  * `FlowInstance.findAll` / `start` call this for you.
573
579
  */