@coasys/ad4m 0.10.1-rc9-dev → 0.10.1-release-candidate-2

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 (61) hide show
  1. package/lib/index.cjs +3179 -811
  2. package/lib/index.js +3171 -807
  3. package/lib/src/Literal.js +4 -1
  4. package/lib/src/ai/AIClient.d.ts +1 -1
  5. package/lib/src/ai/AIClient.js +6 -6
  6. package/lib/src/ai/AIResolver.d.ts +1 -1
  7. package/lib/src/ai/AIResolver.js +7 -4
  8. package/lib/src/index.d.ts +4 -3
  9. package/lib/src/index.js +4 -3
  10. package/lib/src/model/Ad4mModel.d.ts +609 -0
  11. package/lib/src/model/Ad4mModel.js +1048 -0
  12. package/lib/src/{subject → model}/Subject.d.ts +2 -2
  13. package/lib/src/{subject → model}/Subject.js +18 -18
  14. package/lib/src/model/decorators.d.ts +502 -0
  15. package/lib/src/model/decorators.js +683 -0
  16. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +2 -2
  17. package/lib/src/neighbourhood/NeighbourhoodClient.js +16 -10
  18. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +2 -2
  19. package/lib/src/neighbourhood/NeighbourhoodProxy.js +4 -4
  20. package/lib/src/neighbourhood/NeighbourhoodProxy.test.d.ts +1 -0
  21. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +31 -0
  22. package/lib/src/neighbourhood/NeighbourhoodResolver.d.ts +2 -2
  23. package/lib/src/neighbourhood/NeighbourhoodResolver.js +6 -4
  24. package/lib/src/perspectives/PerspectiveClient.d.ts +18 -11
  25. package/lib/src/perspectives/PerspectiveClient.js +116 -49
  26. package/lib/src/perspectives/PerspectiveProxy.d.ts +471 -54
  27. package/lib/src/perspectives/PerspectiveProxy.js +579 -64
  28. package/lib/src/perspectives/PerspectiveResolver.d.ts +23 -9
  29. package/lib/src/perspectives/PerspectiveResolver.js +140 -46
  30. package/lib/src/runtime/RuntimeClient.d.ts +5 -1
  31. package/lib/src/runtime/RuntimeClient.js +48 -0
  32. package/lib/src/runtime/RuntimeResolver.d.ts +24 -0
  33. package/lib/src/runtime/RuntimeResolver.js +117 -0
  34. package/lib/src/schema.gql +25 -11
  35. package/lib/src/typeDefs.js +25 -11
  36. package/package.json +2 -1
  37. package/src/Literal.ts +4 -1
  38. package/src/ai/AIClient.ts +6 -6
  39. package/src/ai/AIResolver.ts +6 -3
  40. package/src/index.ts +4 -3
  41. package/src/model/Ad4mModel.ts +1206 -0
  42. package/src/{subject → model}/Subject.ts +16 -16
  43. package/src/{subject/SDNADecorators.ts → model/decorators.ts} +384 -50
  44. package/src/neighbourhood/NeighbourhoodClient.ts +16 -10
  45. package/src/neighbourhood/NeighbourhoodProxy.test.ts +45 -0
  46. package/src/neighbourhood/NeighbourhoodProxy.ts +4 -4
  47. package/src/neighbourhood/NeighbourhoodResolver.ts +2 -2
  48. package/src/perspectives/PerspectiveClient.ts +122 -51
  49. package/src/perspectives/PerspectiveProxy.ts +642 -77
  50. package/src/perspectives/PerspectiveResolver.ts +126 -23
  51. package/src/runtime/RuntimeClient.ts +52 -1
  52. package/src/runtime/RuntimeResolver.ts +77 -0
  53. package/lib/src/subject/SDNADecorators.d.ts +0 -188
  54. package/lib/src/subject/SDNADecorators.js +0 -360
  55. package/lib/src/subject/SubjectEntity.d.ts +0 -110
  56. package/lib/src/subject/SubjectEntity.js +0 -288
  57. package/src/subject/SubjectEntity.ts +0 -336
  58. package/yarn-error.log +0 -90
  59. /package/lib/src/{subject → model}/util.d.ts +0 -0
  60. /package/lib/src/{subject → model}/util.js +0 -0
  61. /package/src/{subject → model}/util.ts +0 -0
@@ -9,18 +9,225 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks;
12
+ var _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks;
13
13
  import { LinkQuery } from "./LinkQuery";
14
14
  import { Literal } from "../Literal";
15
- import { Subject } from "../subject/Subject";
16
- import { collectionAdderToName, collectionRemoverToName, collectionSetterToName } from "../subject/util";
17
- /** Perspective UI proxy object
15
+ import { Subject } from "../model/Subject";
16
+ import { collectionAdderToName, collectionRemoverToName, collectionSetterToName } from "../model/util";
17
+ /** Proxy object for a subscribed Prolog query that provides real-time updates
18
18
  *
19
- * Convenience object for UIs to interact with a perspective.
20
- * It is created by some of the methods in the PerspectiveClient class and includes
21
- * a reference to the PerspectiveClient object that created it.
19
+ * This class handles:
20
+ * - Keeping the subscription alive by sending periodic keepalive signals
21
+ * - Managing callbacks for result updates
22
+ * - Subscribing to query updates via GraphQL subscriptions
23
+ * - Maintaining the latest query result
24
+ * - Ensuring subscription is fully initialized before allowing access
25
+ *
26
+ * The subscription will remain active as long as keepalive signals are sent.
27
+ * Make sure to call dispose() when you're done with the subscription to clean up
28
+ * resources and stop keepalive signals.
29
+ *
30
+ * The subscription goes through an initialization process where it waits for the first
31
+ * result to come through the subscription channel. You can await the `initialized`
32
+ * promise to ensure the subscription is ready. The initialization will timeout after
33
+ * 30 seconds if no result is received.
34
+ *
35
+ * Example usage:
36
+ * ```typescript
37
+ * const subscription = await perspective.subscribeInfer("my_query(X)");
38
+ * // At this point the subscription is already initialized since subscribeInfer waits
39
+ *
40
+ * // Set up callback for future updates
41
+ * const removeCallback = subscription.onResult(result => {
42
+ * console.log("New result:", result);
43
+ * });
44
+ *
45
+ * // Later: clean up
46
+ * subscription.dispose();
47
+ * ```
48
+ */
49
+ export class QuerySubscriptionProxy {
50
+ /** Creates a new query subscription
51
+ * @param uuid - The UUID of the perspective
52
+ * @param subscriptionId - The ID returned by the subscription mutation
53
+ * @param initialResult - The initial query result
54
+ * @param client - The PerspectiveClient instance to use for communication
55
+ */
56
+ constructor(uuid, subscriptionId, initialResult, client) {
57
+ _QuerySubscriptionProxy_instances.add(this);
58
+ _QuerySubscriptionProxy_uuid.set(this, void 0);
59
+ _QuerySubscriptionProxy_subscriptionId.set(this, void 0);
60
+ _QuerySubscriptionProxy_client.set(this, void 0);
61
+ _QuerySubscriptionProxy_callbacks.set(this, void 0);
62
+ _QuerySubscriptionProxy_keepaliveTimer.set(this, void 0);
63
+ _QuerySubscriptionProxy_unsubscribe.set(this, void 0);
64
+ _QuerySubscriptionProxy_latestResult.set(this, void 0);
65
+ _QuerySubscriptionProxy_disposed.set(this, false);
66
+ _QuerySubscriptionProxy_initialized.set(this, void 0);
67
+ _QuerySubscriptionProxy_initTimeoutId.set(this, void 0);
68
+ __classPrivateFieldSet(this, _QuerySubscriptionProxy_uuid, uuid, "f");
69
+ __classPrivateFieldSet(this, _QuerySubscriptionProxy_subscriptionId, subscriptionId, "f");
70
+ __classPrivateFieldSet(this, _QuerySubscriptionProxy_client, client, "f");
71
+ __classPrivateFieldSet(this, _QuerySubscriptionProxy_callbacks, new Set(), "f");
72
+ __classPrivateFieldSet(this, _QuerySubscriptionProxy_latestResult, initialResult, "f");
73
+ __classPrivateFieldSet(this, _QuerySubscriptionProxy_initialized, new Promise((resolve, reject) => {
74
+ // Add timeout to prevent hanging promises
75
+ __classPrivateFieldSet(this, _QuerySubscriptionProxy_initTimeoutId, setTimeout(() => {
76
+ reject(new Error('Subscription initialization timed out after 30 seconds'));
77
+ }, 30000), "f"); // 30 seconds timeout
78
+ // Subscribe to query updates
79
+ __classPrivateFieldSet(this, _QuerySubscriptionProxy_unsubscribe, __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").subscribeToQueryUpdates(__classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f"), (result) => {
80
+ if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
81
+ clearTimeout(__classPrivateFieldGet(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
82
+ __classPrivateFieldSet(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
83
+ }
84
+ resolve(true);
85
+ __classPrivateFieldSet(this, _QuerySubscriptionProxy_latestResult, result, "f");
86
+ __classPrivateFieldGet(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, result);
87
+ }), "f");
88
+ }), "f");
89
+ // Start keepalive loop using platform-agnostic setTimeout
90
+ const keepaliveLoop = async () => {
91
+ if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_disposed, "f"))
92
+ return;
93
+ try {
94
+ await __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f"));
95
+ }
96
+ catch (e) {
97
+ console.error('Error in keepalive:', e);
98
+ }
99
+ // Schedule next keepalive if not disposed
100
+ if (!__classPrivateFieldGet(this, _QuerySubscriptionProxy_disposed, "f")) {
101
+ __classPrivateFieldSet(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
102
+ }
103
+ };
104
+ // Start the first keepalive loop
105
+ __classPrivateFieldSet(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
106
+ }
107
+ /** Promise that resolves when the subscription has received its first result
108
+ * through the subscription channel. This ensures the subscription is fully
109
+ * set up before allowing access to results or updates.
110
+ *
111
+ * The promise will reject if no result is received within 30 seconds.
112
+ *
113
+ * Note: You typically don't need to await this directly since the subscription
114
+ * creation methods (like subscribeInfer) already wait for initialization.
115
+ */
116
+ get initialized() {
117
+ return __classPrivateFieldGet(this, _QuerySubscriptionProxy_initialized, "f");
118
+ }
119
+ /** Get the latest query result
120
+ *
121
+ * This returns the most recent result from the query, which could be either:
122
+ * - The initial result from when the subscription was created
123
+ * - The latest update received through the subscription
124
+ *
125
+ * @returns The latest query result as a string (usually a JSON array of bindings)
126
+ */
127
+ get result() {
128
+ return __classPrivateFieldGet(this, _QuerySubscriptionProxy_latestResult, "f");
129
+ }
130
+ /** Add a callback that will be called whenever new results arrive
131
+ *
132
+ * The callback will be called immediately with the current result,
133
+ * and then again each time the query results change.
134
+ *
135
+ * @param callback - Function that takes a result string and processes it
136
+ * @returns A function that can be called to remove this callback
137
+ *
138
+ * Example:
139
+ * ```typescript
140
+ * const removeCallback = subscription.onResult(result => {
141
+ * const bindings = JSON.parse(result);
142
+ * console.log("New bindings:", bindings);
143
+ * });
144
+ *
145
+ * // Later: stop receiving updates
146
+ * removeCallback();
147
+ * ```
148
+ */
149
+ onResult(callback) {
150
+ __classPrivateFieldGet(this, _QuerySubscriptionProxy_callbacks, "f").add(callback);
151
+ return () => __classPrivateFieldGet(this, _QuerySubscriptionProxy_callbacks, "f").delete(callback);
152
+ }
153
+ /** Clean up the subscription and stop keepalive signals
154
+ *
155
+ * This method:
156
+ * 1. Stops the keepalive timer
157
+ * 2. Unsubscribes from GraphQL subscription updates
158
+ * 3. Clears all registered callbacks
159
+ * 4. Cleans up any pending initialization timeout
160
+ *
161
+ * After calling this method, the subscription is no longer active and
162
+ * will not receive any more updates. The instance should be discarded.
163
+ */
164
+ dispose() {
165
+ __classPrivateFieldSet(this, _QuerySubscriptionProxy_disposed, true, "f");
166
+ clearTimeout(__classPrivateFieldGet(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
167
+ if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_unsubscribe, "f")) {
168
+ __classPrivateFieldGet(this, _QuerySubscriptionProxy_unsubscribe, "f").call(this);
169
+ }
170
+ if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
171
+ clearTimeout(__classPrivateFieldGet(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
172
+ __classPrivateFieldSet(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
173
+ }
174
+ __classPrivateFieldGet(this, _QuerySubscriptionProxy_callbacks, "f").clear();
175
+ }
176
+ }
177
+ _QuerySubscriptionProxy_uuid = new WeakMap(), _QuerySubscriptionProxy_subscriptionId = new WeakMap(), _QuerySubscriptionProxy_client = new WeakMap(), _QuerySubscriptionProxy_callbacks = new WeakMap(), _QuerySubscriptionProxy_keepaliveTimer = new WeakMap(), _QuerySubscriptionProxy_unsubscribe = new WeakMap(), _QuerySubscriptionProxy_latestResult = new WeakMap(), _QuerySubscriptionProxy_disposed = new WeakMap(), _QuerySubscriptionProxy_initialized = new WeakMap(), _QuerySubscriptionProxy_initTimeoutId = new WeakMap(), _QuerySubscriptionProxy_instances = new WeakSet(), _QuerySubscriptionProxy_notifyCallbacks = function _QuerySubscriptionProxy_notifyCallbacks(result) {
178
+ for (const callback of __classPrivateFieldGet(this, _QuerySubscriptionProxy_callbacks, "f")) {
179
+ try {
180
+ callback(result);
181
+ }
182
+ catch (e) {
183
+ console.error('Error in query subscription callback:', e);
184
+ }
185
+ }
186
+ };
187
+ /**
188
+ * PerspectiveProxy provides a high-level interface for working with AD4M Perspectives - agent-centric semantic graphs
189
+ * that store and organize links between expressions.
190
+ *
191
+ * A Perspective is fundamentally a collection of links (subject-predicate-object triples) that represent an agent's view
192
+ * of their digital world. Through PerspectiveProxy, you can:
193
+ * - Add, remove, and query links
194
+ * - Work with Social DNA (subject classes and flows)
195
+ * - Subscribe to real-time updates
196
+ * - Share perspectives as Neighbourhoods
197
+ * - Execute Prolog queries for complex graph patterns
198
+ *
199
+ *
200
+ * @example
201
+ * ```typescript
202
+ * // Create and work with links
203
+ * const perspective = await ad4m.perspective.add("My Space");
204
+ * await perspective.add({
205
+ * source: "did:key:alice",
206
+ * predicate: "knows",
207
+ * target: "did:key:bob"
208
+ * });
209
+ *
210
+ * // Query links
211
+ * const friends = await perspective.get({
212
+ * source: "did:key:alice",
213
+ * predicate: "knows"
214
+ * });
215
+ *
216
+ * // Use Social DNA
217
+ * await perspective.addSdna(todoClass, "subject_class");
218
+ * const todo = await perspective.createSubject("Todo", "expression://123");
219
+ *
220
+ * // Subscribe to changes
221
+ * perspective.addListener("link-added", (link) => {
222
+ * console.log("New link added:", link);
223
+ * });
224
+ * ```
22
225
  */
23
226
  export class PerspectiveProxy {
227
+ /**
228
+ * Creates a new PerspectiveProxy instance.
229
+ * Note: Don't create this directly, use ad4m.perspective.add() instead.
230
+ */
24
231
  constructor(handle, ad4m) {
25
232
  _PerspectiveProxy_handle.set(this, void 0);
26
233
  _PerspectiveProxy_client.set(this, void 0);
@@ -44,52 +251,255 @@ export class PerspectiveProxy {
44
251
  __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addPerspectiveLinkUpdatedListener(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f"));
45
252
  __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addPerspectiveSyncStateChangeListener(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, "f"));
46
253
  }
47
- async executeAction(actions, expression, parameters) {
48
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").executeCommands(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify(actions), expression, JSON.stringify(parameters));
254
+ /**
255
+ * Executes a set of actions on an expression with optional parameters.
256
+ * Used internally by Social DNA flows and subject class operations.
257
+ *
258
+ * Actions are specified as an array of commands that modify links in the perspective.
259
+ * Each action is an object with the following format:
260
+ * ```typescript
261
+ * {
262
+ * action: "addLink" | "removeLink" | "setSingleTarget" | "collectionSetter",
263
+ * source: string, // Usually "this" to reference the current expression
264
+ * predicate: string, // The predicate URI
265
+ * target: string // The target value or "value" for parameters
266
+ * }
267
+ * ```
268
+ *
269
+ * Available commands:
270
+ * - `addLink`: Creates a new link
271
+ * - `removeLink`: Removes an existing link
272
+ * - `setSingleTarget`: Removes all existing links with the same source/predicate and adds a new one
273
+ * - `collectionSetter`: Special command for setting collection properties
274
+ *
275
+ * When used with parameters, the special value "value" in the target field will be
276
+ * replaced with the actual parameter value.
277
+ *
278
+ * @example
279
+ * ```typescript
280
+ * // Add a state link and remove an old one
281
+ * await perspective.executeAction([
282
+ * {
283
+ * action: "addLink",
284
+ * source: "this",
285
+ * predicate: "todo://state",
286
+ * target: "todo://doing"
287
+ * },
288
+ * {
289
+ * action: "removeLink",
290
+ * source: "this",
291
+ * predicate: "todo://state",
292
+ * target: "todo://ready"
293
+ * }
294
+ * ], "expression://123");
295
+ *
296
+ * // Set a property using a parameter
297
+ * await perspective.executeAction([
298
+ * {
299
+ * action: "setSingleTarget",
300
+ * source: "this",
301
+ * predicate: "todo://title",
302
+ * target: "value"
303
+ * }
304
+ * ], "expression://123", [
305
+ * { name: "title", value: "New Title" }
306
+ * ]);
307
+ * ```
308
+ *
309
+ * @param actions - Array of action objects to execute
310
+ * @param expression - Target expression address (replaces "this" in actions)
311
+ * @param parameters - Optional parameters that replace "value" in actions
312
+ * @param batchId - Optional batch ID to group this operation with others
313
+ */
314
+ async executeAction(actions, expression, parameters, batchId) {
315
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").executeCommands(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId);
49
316
  }
50
- /** Returns all the links of this perspective that matches the LinkQuery */
317
+ /**
318
+ * Retrieves links from the perspective that match the given query.
319
+ *
320
+ * @param query - Query parameters to filter links
321
+ * @returns Array of matching LinkExpressions
322
+ *
323
+ * @example
324
+ * ```typescript
325
+ * // Get all links where Alice knows someone
326
+ * const links = await perspective.get({
327
+ * source: "did:key:alice",
328
+ * predicate: "knows"
329
+ * });
330
+ *
331
+ * // Get all comments on a post
332
+ * const comments = await perspective.get({
333
+ * source: "post://123",
334
+ * predicate: "comment"
335
+ * });
336
+ * ```
337
+ */
51
338
  async get(query) {
52
339
  return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").queryLinks(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, query);
53
340
  }
54
- /** Runs a Prolog query on the perspective's Prolog engine */
341
+ /**
342
+ * Executes a Prolog query against the perspective's knowledge base.
343
+ * This is a powerful way to find complex patterns in the graph.
344
+ *
345
+ * @param query - Prolog query string
346
+ * @returns Query results or false if no results
347
+ *
348
+ * @example
349
+ * ```typescript
350
+ * // Find friends of friends
351
+ * const results = await perspective.infer(`
352
+ * triple(A, "knows", B),
353
+ * triple(B, "knows", C),
354
+ * A \= C
355
+ * `);
356
+ *
357
+ * // Find all active todos
358
+ * const todos = await perspective.infer(`
359
+ * instance(Todo, "Todo"),
360
+ * property_getter("Todo", Todo, "state", "active")
361
+ * `);
362
+ * ```
363
+ */
55
364
  async infer(query) {
56
365
  return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").queryProlog(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, query);
57
366
  }
58
- /** Adds a link to this perspective */
59
- async add(link, status = 'shared') {
60
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, link, status);
367
+ /**
368
+ * Adds a new link to the perspective.
369
+ *
370
+ * @param link - The link to add
371
+ * @param status - Whether the link should be shared in a Neighbourhood
372
+ * @param batchId - Optional batch ID to group this operation with others
373
+ * @returns The created LinkExpression
374
+ *
375
+ * @example
376
+ * ```typescript
377
+ * // Add a simple relationship
378
+ * await perspective.add({
379
+ * source: "did:key:alice",
380
+ * predicate: "follows",
381
+ * target: "did:key:bob"
382
+ * });
383
+ *
384
+ * // Add a local-only link
385
+ * await perspective.add({
386
+ * source: "note://123",
387
+ * predicate: "tag",
388
+ * target: "private"
389
+ * }, "local");
390
+ * ```
391
+ */
392
+ async add(link, status = 'shared', batchId) {
393
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
61
394
  }
62
- /** Adds multiple links to this perspective **/
63
- async addLinks(links, status = 'shared') {
64
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addLinks(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, links, status);
395
+ /**
396
+ * Adds multiple links to the perspective in a single operation.
397
+ * More efficient than adding links one by one.
398
+ *
399
+ * @param links - Array of links to add
400
+ * @param status - Whether the links should be shared
401
+ * @param batchId - Optional batch ID to group this operation with others
402
+ * @returns Array of created LinkExpressions
403
+ */
404
+ async addLinks(links, status = 'shared', batchId) {
405
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addLinks(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, links, status, batchId);
65
406
  }
66
- /** Removes multiple links from this perspective **/
67
- async removeLinks(links) {
68
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeLinks(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, links);
407
+ /**
408
+ * Removes multiple links from the perspective.
409
+ *
410
+ * @param links - Array of links to remove
411
+ * @param batchId - Optional batch ID to group this operation with others
412
+ * @returns Array of removed LinkExpressions
413
+ */
414
+ async removeLinks(links, batchId) {
415
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeLinks(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, links, batchId);
69
416
  }
70
- /** Adds and removes multiple links from this perspective **/
417
+ /**
418
+ * Applies a set of link mutations (adds and removes) in a single operation.
419
+ * Useful for atomic updates to the perspective.
420
+ *
421
+ * @param mutations - Object containing links to add and remove
422
+ * @param status - Whether new links should be shared
423
+ * @returns Object containing results of the mutations
424
+ */
71
425
  async linkMutations(mutations, status = 'shared') {
72
426
  return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").linkMutations(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, mutations, status);
73
427
  }
74
- /** Adds a linkExpression to this perspective */
75
- async addLinkExpression(link, status = 'shared') {
76
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addLinkExpression(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, link, status);
428
+ /**
429
+ * Adds a pre-signed LinkExpression to the perspective.
430
+ *
431
+ * @param link - The signed LinkExpression to add
432
+ * @param status - Whether the link should be shared
433
+ * @param batchId - Optional batch ID to group this operation with others
434
+ * @returns The added LinkExpression
435
+ */
436
+ async addLinkExpression(link, status = 'shared', batchId) {
437
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addLinkExpression(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
77
438
  }
78
- async update(oldLink, newLink) {
79
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").updateLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, oldLink, newLink);
439
+ /**
440
+ * Updates an existing link with new data.
441
+ *
442
+ * @param oldLink - The existing link to update
443
+ * @param newLink - The new link data
444
+ * @param batchId - Optional batch ID to group this operation with others
445
+ */
446
+ async update(oldLink, newLink, batchId) {
447
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").updateLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, oldLink, newLink, batchId);
80
448
  }
81
- async remove(link) {
82
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, link);
449
+ /**
450
+ * Removes a link from the perspective.
451
+ *
452
+ * @param link - The link to remove
453
+ * @param batchId - Optional batch ID to group this operation with others
454
+ */
455
+ async remove(link, batchId) {
456
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, link, batchId);
457
+ }
458
+ /** Creates a new batch for grouping operations */
459
+ async createBatch() {
460
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").createBatch(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
461
+ }
462
+ /** Commits a batch of operations */
463
+ async commitBatch(batchId) {
464
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").commitBatch(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, batchId);
83
465
  }
466
+ /**
467
+ * Retrieves and renders an Expression referenced in this perspective.
468
+ *
469
+ * @param expressionURI - URI of the Expression to retrieve
470
+ * @returns The rendered Expression
471
+ */
84
472
  async getExpression(expressionURI) {
85
473
  return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").getExpression(expressionURI);
86
474
  }
475
+ /**
476
+ * Creates a new Expression in the specified Language.
477
+ *
478
+ * @param content - Content for the new Expression
479
+ * @param languageAddress - Address of the Language to use
480
+ * @returns URI of the created Expression
481
+ */
87
482
  async createExpression(content, languageAddress) {
88
483
  return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").createExpression(content, languageAddress);
89
484
  }
90
- /** Adds a link listener
91
- * @param type Can be 'link-added' or 'link-removed'
92
- * @param cb Callback function that is called when a link is added to the perspective
485
+ /**
486
+ * Subscribes to link changes in the perspective.
487
+ *
488
+ * @param type - Type of change to listen for
489
+ * @param cb - Callback function
490
+ *
491
+ * @example
492
+ * ```typescript
493
+ * // Listen for new links
494
+ * perspective.addListener("link-added", (link) => {
495
+ * console.log("New link:", link);
496
+ * });
497
+ *
498
+ * // Listen for removed links
499
+ * perspective.addListener("link-removed", (link) => {
500
+ * console.log("Link removed:", link);
501
+ * });
502
+ * ```
93
503
  */
94
504
  async addListener(type, cb) {
95
505
  if (type === 'link-added') {
@@ -102,16 +512,26 @@ export class PerspectiveProxy {
102
512
  __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").push(cb);
103
513
  }
104
514
  }
105
- /** Adds a sync state listener
106
- * @param cb Callback function that is called when the sync state of the perspective changes
107
- * @returns A function that can be called to remove the listener
515
+ /**
516
+ * Subscribes to sync state changes if this perspective is shared.
517
+ *
518
+ * @param cb - Callback function
519
+ *
520
+ * @example
521
+ * ```typescript
522
+ * perspective.addSyncStateChangeListener((state) => {
523
+ * console.log("Sync state:", state);
524
+ * });
525
+ * ```
108
526
  */
109
527
  async addSyncStateChangeListener(cb) {
110
528
  __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, "f").push(cb);
111
529
  }
112
- /** Removes a previously added link listener
113
- * @param type Can be 'link-added' or 'link-removed'
114
- * @param cb Callback function that is called when a link is added to the perspective
530
+ /**
531
+ * Unsubscribes from link changes.
532
+ *
533
+ * @param type - Type of change to stop listening for
534
+ * @param cb - The callback function to remove
115
535
  */
116
536
  async removeListener(type, cb) {
117
537
  if (type === 'link-added') {
@@ -127,13 +547,20 @@ export class PerspectiveProxy {
127
547
  __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").splice(index, 1);
128
548
  }
129
549
  }
130
- /** Create and return a snapshot of this perspective
131
- * A snapshot is a rendered Perspectie object that contains all the links of the perspective.
550
+ /**
551
+ * Creates a snapshot of the current perspective state.
552
+ * Useful for backup or sharing.
553
+ *
554
+ * @returns Perspective object containing all links
132
555
  */
133
556
  async snapshot() {
134
557
  return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").snapshotByUUID(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
135
558
  }
136
- /** Take and load all the links from the given snapshot */
559
+ /**
560
+ * Loads a perspective snapshot, replacing current content.
561
+ *
562
+ * @param snapshot - Perspective snapshot to load
563
+ */
137
564
  async loadSnapshot(snapshot) {
138
565
  //Clean the input data from __typename
139
566
  const cleanedSnapshot = JSON.parse(JSON.stringify(snapshot));
@@ -145,11 +572,21 @@ export class PerspectiveProxy {
145
572
  await this.addLinkExpression(link);
146
573
  }
147
574
  }
148
- /** Convenience function to get the target of the first link that matches the given query
149
- * This makes sense when the query is expected to return only one link
150
- * and the target of that link is what you are looking for.
575
+ /**
576
+ * Gets a single target value matching a query.
577
+ * Useful when you expect only one result.
578
+ *
579
+ * @param query - Query to find the target
580
+ * @returns Target value or void if not found
151
581
  *
152
- * Works best together with @member setSingelTarget()
582
+ * @example
583
+ * ```typescript
584
+ * // Get a user's name
585
+ * const name = await perspective.getSingleTarget({
586
+ * source: "did:key:alice",
587
+ * predicate: "name"
588
+ * });
589
+ * ```
153
590
  */
154
591
  async getSingleTarget(query) {
155
592
  delete query.target;
@@ -159,12 +596,21 @@ export class PerspectiveProxy {
159
596
  else
160
597
  return null;
161
598
  }
162
- /** Convenience function to ensure there is only one link with given source and predicate
163
- * This function will remove all links with the same source and predicate as the given link,
164
- * and then add the given link.
165
- * This ensures there is only one target for the given source and predicate.
599
+ /**
600
+ * Sets a single target value, removing any existing targets.
166
601
  *
167
- * Works best together with @member getSingleTarget()
602
+ * @param link - Link defining the new target
603
+ * @param status - Whether the link should be shared
604
+ *
605
+ * @example
606
+ * ```typescript
607
+ * // Set a user's status
608
+ * await perspective.setSingleTarget({
609
+ * source: "did:key:alice",
610
+ * predicate: "status",
611
+ * target: "online"
612
+ * });
613
+ * ```
168
614
  */
169
615
  async setSingleTarget(link, status = 'shared') {
170
616
  const query = new LinkQuery({ source: link.source, predicate: link.predicate });
@@ -240,7 +686,7 @@ export class PerspectiveProxy {
240
686
  return [];
241
687
  }
242
688
  }
243
- async stringOrTemplateObjectToSubjectClass(subjectClass) {
689
+ async stringOrTemplateObjectToSubjectClassName(subjectClass) {
244
690
  if (typeof subjectClass === "string")
245
691
  return subjectClass;
246
692
  else {
@@ -254,24 +700,37 @@ export class PerspectiveProxy {
254
700
  }
255
701
  }
256
702
  }
257
- /** Creates a new subject instance by running its (SDNA defined) constructor,
258
- * which means adding links around the given expression address so that it
259
- * conforms to the given subject class.
703
+ /**
704
+ * Creates a new subject instance of the given subject class
260
705
  *
261
706
  * @param subjectClass Either a string with the name of the subject class, or an object
262
- * with the properties of the subject class. In the latter case, the first subject class
263
- * that matches the given properties will be used.
707
+ * with the properties of the subject class.
264
708
  * @param exprAddr The address of the expression to be turned into a subject instance
709
+ * @param initialValues Optional initial values for properties. If provided, these will be
710
+ * merged with constructor actions for better performance.
711
+ * @param batchId Optional batch ID for grouping operations. If provided, returns the expression address
712
+ * instead of the subject proxy since the subject won't exist until the batch is committed.
713
+ * @returns A proxy object for the created subject, or just the expression address if in batch mode
265
714
  */
266
- async createSubject(subjectClass, exprAddr) {
715
+ async createSubject(subjectClass, exprAddr, initialValues, batchId) {
267
716
  let className;
268
717
  if (typeof subjectClass === "string") {
269
718
  className = subjectClass;
270
- await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").createSubject(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({ className }), exprAddr);
719
+ await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").createSubject(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({
720
+ className,
721
+ initialValues
722
+ }), exprAddr, initialValues ? JSON.stringify(initialValues) : undefined, batchId);
271
723
  }
272
724
  else {
273
725
  let query = this.buildQueryFromTemplate(subjectClass);
274
- await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").createSubject(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({ query }), exprAddr);
726
+ await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").createSubject(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({
727
+ query,
728
+ initialValues
729
+ }), exprAddr, initialValues ? JSON.stringify(initialValues) : undefined, batchId);
730
+ }
731
+ // Skip subject proxy creation when in batch mode since the subject won't exist until batch is committed
732
+ if (batchId) {
733
+ return exprAddr;
275
734
  }
276
735
  return this.getSubjectProxy(exprAddr, subjectClass);
277
736
  }
@@ -289,15 +748,17 @@ export class PerspectiveProxy {
289
748
  * with the properties of the subject class. In the latter case, the first subject class
290
749
  * that matches the given properties will be used.
291
750
  * @param exprAddr The address of the expression to be turned into a subject instance
751
+ * @param batchId Optional batch ID for grouping operations. If provided, the removal will be part of the batch
752
+ * and won't be executed until the batch is committed.
292
753
  */
293
- async removeSubject(subjectClass, exprAddr) {
294
- let className = await this.stringOrTemplateObjectToSubjectClass(subjectClass);
754
+ async removeSubject(subjectClass, exprAddr, batchId) {
755
+ let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);
295
756
  let result = await this.infer(`subject_class("${className}", C), destructor(C, Actions)`);
296
757
  if (!result.length) {
297
- throw "No constructor found for given subject class: " + className;
758
+ throw "No destructor found for given subject class: " + className;
298
759
  }
299
760
  let actions = result.map(x => eval(x.Actions));
300
- await this.executeAction(actions[0], exprAddr, undefined);
761
+ await this.executeAction(actions[0], exprAddr, undefined, batchId);
301
762
  }
302
763
  /** Checks if the given expression is a subject instance of the given subject class
303
764
  * @param expression The expression to be checked
@@ -306,7 +767,7 @@ export class PerspectiveProxy {
306
767
  * that matches the given properties will be used.
307
768
  */
308
769
  async isSubjectInstance(expression, subjectClass) {
309
- let className = await this.stringOrTemplateObjectToSubjectClass(subjectClass);
770
+ let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);
310
771
  let isInstance = false;
311
772
  const maxAttempts = 5;
312
773
  let attempts = 0;
@@ -329,7 +790,7 @@ export class PerspectiveProxy {
329
790
  if (!await this.isSubjectInstance(base, subjectClass)) {
330
791
  throw `Expression ${base} is not a subject instance of given class: ${JSON.stringify(subjectClass)}`;
331
792
  }
332
- let className = await this.stringOrTemplateObjectToSubjectClass(subjectClass);
793
+ let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);
333
794
  let subject = new Subject(this, base, className);
334
795
  await subject.init();
335
796
  return subject;
@@ -490,8 +951,62 @@ export class PerspectiveProxy {
490
951
  getNeighbourhoodProxy() {
491
952
  return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").getNeighbourhoodProxy(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
492
953
  }
954
+ /**
955
+ * Returns a proxy object for working with AI capabilities.
956
+ *
957
+ * @returns AIClient instance
958
+ *
959
+ * @example
960
+ * ```typescript
961
+ * // Use AI to analyze perspective content
962
+ * const summary = await perspective.ai.summarize();
963
+ *
964
+ * // Generate new content
965
+ * const suggestion = await perspective.ai.suggest("next action");
966
+ * ```
967
+ */
493
968
  get ai() {
494
969
  return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").aiClient;
495
970
  }
971
+ /**
972
+ * Creates a subscription for a Prolog query that updates in real-time.
973
+ *
974
+ * This method:
975
+ * 1. Creates the subscription on the Rust side
976
+ * 2. Sets up the subscription callback
977
+ * 3. Waits for the initial result to come through the subscription channel
978
+ * 4. Returns a fully initialized QuerySubscriptionProxy
979
+ *
980
+ * The returned subscription is guaranteed to be ready to receive updates,
981
+ * as this method waits for the initialization process to complete.
982
+ *
983
+ * @param query - Prolog query string
984
+ * @returns Initialized QuerySubscriptionProxy instance
985
+ *
986
+ * @example
987
+ * ```typescript
988
+ * // Subscribe to active todos
989
+ * const subscription = await perspective.subscribeInfer(`
990
+ * instance(Todo, "Todo"),
991
+ * property_getter("Todo", Todo, "state", "active")
992
+ * `);
993
+ *
994
+ * // Subscription is already initialized here
995
+ * console.log("Initial result:", subscription.result);
996
+ *
997
+ * // Set up callback for future updates
998
+ * subscription.onResult((todos) => {
999
+ * console.log("Active todos:", todos);
1000
+ * });
1001
+ * ```
1002
+ */
1003
+ async subscribeInfer(query) {
1004
+ // Start the subscription on the Rust side first to get the real subscription ID
1005
+ const result = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").subscribeQuery(this.uuid, query);
1006
+ const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, result.subscriptionId, result.result, __classPrivateFieldGet(this, _PerspectiveProxy_client, "f"));
1007
+ // Wait for the initial result
1008
+ await subscriptionProxy.initialized;
1009
+ return subscriptionProxy;
1010
+ }
496
1011
  }
497
1012
  _PerspectiveProxy_handle = new WeakMap(), _PerspectiveProxy_client = new WeakMap(), _PerspectiveProxy_perspectiveLinkAddedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkRemovedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkUpdatedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveSyncStateChangeCallbacks = new WeakMap();