@coasys/ad4m 0.10.0 → 0.10.1-dev-1
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.
- package/lib/index.cjs +3785 -843
- package/lib/index.js +3777 -839
- package/lib/src/Ad4mClient.js +2 -1
- package/lib/src/Literal.js +4 -1
- package/lib/src/ai/AIClient.d.ts +8 -2
- package/lib/src/ai/AIClient.js +25 -14
- package/lib/src/ai/AIResolver.d.ts +25 -6
- package/lib/src/ai/AIResolver.js +102 -18
- package/lib/src/index.d.ts +4 -3
- package/lib/src/index.js +4 -3
- package/lib/src/model/Ad4mModel.d.ts +730 -0
- package/lib/src/model/Ad4mModel.js +1399 -0
- package/lib/src/{subject → model}/Subject.d.ts +2 -2
- package/lib/src/{subject → model}/Subject.js +18 -18
- package/lib/src/model/decorators.d.ts +502 -0
- package/lib/src/model/decorators.js +683 -0
- package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +2 -2
- package/lib/src/neighbourhood/NeighbourhoodClient.js +13 -10
- package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +2 -2
- package/lib/src/neighbourhood/NeighbourhoodProxy.js +4 -4
- package/lib/src/neighbourhood/NeighbourhoodProxy.test.d.ts +1 -0
- package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +73 -0
- package/lib/src/neighbourhood/NeighbourhoodResolver.d.ts +2 -2
- package/lib/src/neighbourhood/NeighbourhoodResolver.js +6 -4
- package/lib/src/perspectives/PerspectiveClient.d.ts +23 -11
- package/lib/src/perspectives/PerspectiveClient.js +147 -51
- package/lib/src/perspectives/PerspectiveProxy.d.ts +494 -54
- package/lib/src/perspectives/PerspectiveProxy.js +684 -67
- package/lib/src/perspectives/PerspectiveResolver.d.ts +24 -9
- package/lib/src/perspectives/PerspectiveResolver.js +151 -46
- package/lib/src/runtime/RuntimeClient.d.ts +8 -2
- package/lib/src/runtime/RuntimeClient.js +64 -0
- package/lib/src/runtime/RuntimeResolver.d.ts +27 -1
- package/lib/src/runtime/RuntimeResolver.js +138 -0
- package/lib/src/schema.gql +55 -16
- package/lib/src/typeDefs.js +55 -16
- package/package.json +4 -3
- package/src/Ad4mClient.test.ts +51 -19
- package/src/Ad4mClient.ts +3 -1
- package/src/Literal.ts +4 -1
- package/src/ai/AIClient.ts +35 -14
- package/src/ai/AIResolver.ts +78 -16
- package/src/index.ts +4 -3
- package/src/model/Ad4mModel.ts +1651 -0
- package/src/{subject → model}/Subject.ts +16 -16
- package/src/{subject/SDNADecorators.ts → model/decorators.ts} +384 -50
- package/src/neighbourhood/NeighbourhoodClient.ts +13 -10
- package/src/neighbourhood/NeighbourhoodProxy.test.ts +100 -0
- package/src/neighbourhood/NeighbourhoodProxy.ts +4 -4
- package/src/neighbourhood/NeighbourhoodResolver.ts +2 -2
- package/src/perspectives/PerspectiveClient.ts +156 -51
- package/src/perspectives/PerspectiveProxy.ts +766 -82
- package/src/perspectives/PerspectiveResolver.ts +134 -23
- package/src/runtime/RuntimeClient.ts +71 -2
- package/src/runtime/RuntimeResolver.ts +91 -1
- package/lib/src/subject/SDNADecorators.d.ts +0 -188
- package/lib/src/subject/SDNADecorators.js +0 -360
- package/lib/src/subject/SubjectEntity.d.ts +0 -102
- package/lib/src/subject/SubjectEntity.js +0 -267
- package/src/subject/SubjectEntity.ts +0 -315
- package/yarn-error.log +0 -90
- /package/lib/src/{subject → model}/util.d.ts +0 -0
- /package/lib/src/{subject → model}/util.js +0 -0
- /package/src/{subject → model}/util.ts +0 -0
|
@@ -4,11 +4,244 @@ import { LinkQuery } from "./LinkQuery";
|
|
|
4
4
|
import { PerspectiveHandle, PerspectiveState } from './PerspectiveHandle'
|
|
5
5
|
import { Perspective } from "./Perspective";
|
|
6
6
|
import { Literal } from "../Literal";
|
|
7
|
-
import { Subject } from "../
|
|
7
|
+
import { Subject } from "../model/Subject";
|
|
8
8
|
import { ExpressionRendered } from "../expression/Expression";
|
|
9
|
-
import { collectionAdderToName, collectionRemoverToName, collectionSetterToName } from "../
|
|
9
|
+
import { collectionAdderToName, collectionRemoverToName, collectionSetterToName } from "../model/util";
|
|
10
10
|
import { NeighbourhoodProxy } from "../neighbourhood/NeighbourhoodProxy";
|
|
11
11
|
import { NeighbourhoodExpression } from "../neighbourhood/Neighbourhood";
|
|
12
|
+
import { AIClient } from "../ai/AIClient";
|
|
13
|
+
import { PERSPECTIVE_QUERY_SUBSCRIPTION } from "./PerspectiveResolver";
|
|
14
|
+
import { gql } from "@apollo/client/core";
|
|
15
|
+
import { AllInstancesResult } from "../model/Ad4mModel";
|
|
16
|
+
|
|
17
|
+
type QueryCallback = (result: AllInstancesResult) => void;
|
|
18
|
+
|
|
19
|
+
// Generic subscription interface that matches Apollo's Subscription
|
|
20
|
+
interface Unsubscribable {
|
|
21
|
+
unsubscribe(): void;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Proxy object for a subscribed Prolog query that provides real-time updates
|
|
25
|
+
*
|
|
26
|
+
* This class handles:
|
|
27
|
+
* - Keeping the subscription alive by sending periodic keepalive signals
|
|
28
|
+
* - Managing callbacks for result updates
|
|
29
|
+
* - Subscribing to query updates via GraphQL subscriptions
|
|
30
|
+
* - Maintaining the latest query result
|
|
31
|
+
* - Ensuring subscription is fully initialized before allowing access
|
|
32
|
+
* - Cleaning up resources when disposed
|
|
33
|
+
*
|
|
34
|
+
* The subscription will remain active as long as keepalive signals are sent.
|
|
35
|
+
* Make sure to call dispose() when you're done with the subscription to clean up
|
|
36
|
+
* resources, stop keepalive signals, and notify the backend to remove the subscription.
|
|
37
|
+
*
|
|
38
|
+
* The subscription goes through an initialization process where it waits for the first
|
|
39
|
+
* result to come through the subscription channel. You can await the `initialized`
|
|
40
|
+
* promise to ensure the subscription is ready. The initialization will timeout after
|
|
41
|
+
* 30 seconds if no result is received.
|
|
42
|
+
*
|
|
43
|
+
* Example usage:
|
|
44
|
+
* ```typescript
|
|
45
|
+
* const subscription = await perspective.subscribeInfer("my_query(X)");
|
|
46
|
+
* // At this point the subscription is already initialized since subscribeInfer waits
|
|
47
|
+
*
|
|
48
|
+
* // Set up callback for future updates
|
|
49
|
+
* const removeCallback = subscription.onResult(result => {
|
|
50
|
+
* console.log("New result:", result);
|
|
51
|
+
* });
|
|
52
|
+
*
|
|
53
|
+
* // Later: clean up subscription and notify backend
|
|
54
|
+
* subscription.dispose();
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
export class QuerySubscriptionProxy {
|
|
58
|
+
#uuid: string;
|
|
59
|
+
#subscriptionId: string;
|
|
60
|
+
#client: PerspectiveClient;
|
|
61
|
+
#callbacks: Set<QueryCallback>;
|
|
62
|
+
#keepaliveTimer: number;
|
|
63
|
+
#unsubscribe?: () => void;
|
|
64
|
+
#latestResult: AllInstancesResult|null;
|
|
65
|
+
#disposed: boolean = false;
|
|
66
|
+
#initialized: Promise<boolean>;
|
|
67
|
+
#initTimeoutId?: NodeJS.Timeout;
|
|
68
|
+
#query: string;
|
|
69
|
+
|
|
70
|
+
/** Creates a new query subscription
|
|
71
|
+
* @param uuid - The UUID of the perspective
|
|
72
|
+
* @param query - The Prolog query to subscribe to
|
|
73
|
+
* @param client - The PerspectiveClient instance to use for communication
|
|
74
|
+
*/
|
|
75
|
+
constructor(uuid: string, query: string, client: PerspectiveClient) {
|
|
76
|
+
this.#uuid = uuid;
|
|
77
|
+
this.#query = query;
|
|
78
|
+
this.#client = client;
|
|
79
|
+
this.#callbacks = new Set();
|
|
80
|
+
this.#latestResult = null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async subscribe() {
|
|
84
|
+
// initialize the query subscription
|
|
85
|
+
const result = await this.#client.subscribeQuery(this.#uuid, this.#query);
|
|
86
|
+
this.#subscriptionId = result.subscriptionId;
|
|
87
|
+
// Subscribe to query updates
|
|
88
|
+
this.#initialized = new Promise<boolean>((resolve, reject) => {
|
|
89
|
+
// Add timeout to prevent hanging promises
|
|
90
|
+
this.#initTimeoutId = setTimeout(() => {
|
|
91
|
+
reject(new Error('Subscription initialization timed out after 30 seconds. Resubscribing...'));
|
|
92
|
+
this.subscribe();
|
|
93
|
+
}, 30000); // 30 seconds timeout
|
|
94
|
+
|
|
95
|
+
// Subscribe to query updates
|
|
96
|
+
this.#unsubscribe = this.#client.subscribeToQueryUpdates(
|
|
97
|
+
this.#subscriptionId,
|
|
98
|
+
(result) => {
|
|
99
|
+
if (this.#initTimeoutId) {
|
|
100
|
+
clearTimeout(this.#initTimeoutId);
|
|
101
|
+
this.#initTimeoutId = undefined;
|
|
102
|
+
}
|
|
103
|
+
resolve(true);
|
|
104
|
+
|
|
105
|
+
// if the result is one of those repeated initialization results
|
|
106
|
+
// and we got a result before, we don't notify the callbacks
|
|
107
|
+
// so they don't get confused (we could have gotten another
|
|
108
|
+
// more recent result in between)
|
|
109
|
+
if(result.isInit && this.#latestResult) {
|
|
110
|
+
return
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
this.#latestResult = result;
|
|
114
|
+
this.#notifyCallbacks(result);
|
|
115
|
+
}
|
|
116
|
+
);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
// Start keepalive loop using platform-agnostic setTimeout
|
|
120
|
+
const keepaliveLoop = async () => {
|
|
121
|
+
if (this.#disposed) return;
|
|
122
|
+
|
|
123
|
+
try {
|
|
124
|
+
await this.#client.keepAliveQuery(this.#uuid, this.#subscriptionId);
|
|
125
|
+
} catch (e) {
|
|
126
|
+
console.error('Error in keepalive:', e);
|
|
127
|
+
// try to reinitialize the subscription
|
|
128
|
+
console.log('Reinitializing subscription for query:', this.#query);
|
|
129
|
+
await this.subscribe();
|
|
130
|
+
console.log('Subscription reinitialized');
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Schedule next keepalive if not disposed
|
|
134
|
+
if (!this.#disposed) {
|
|
135
|
+
this.#keepaliveTimer = setTimeout(keepaliveLoop, 30000) as unknown as number;
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
// Start the first keepalive loop
|
|
140
|
+
this.#keepaliveTimer = setTimeout(keepaliveLoop, 30000) as unknown as number;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Get the subscription ID for this query subscription
|
|
144
|
+
*
|
|
145
|
+
* This is a unique identifier assigned when the subscription was created.
|
|
146
|
+
* It can be used to reference this specific subscription, for example when
|
|
147
|
+
* sending keepalive signals.
|
|
148
|
+
*
|
|
149
|
+
* @returns The subscription ID string
|
|
150
|
+
*/
|
|
151
|
+
get id(): string {
|
|
152
|
+
return this.#subscriptionId;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Promise that resolves when the subscription has received its first result
|
|
156
|
+
* through the subscription channel. This ensures the subscription is fully
|
|
157
|
+
* set up before allowing access to results or updates.
|
|
158
|
+
*
|
|
159
|
+
* The promise will reject if no result is received within 30 seconds.
|
|
160
|
+
*
|
|
161
|
+
* Note: You typically don't need to await this directly since the subscription
|
|
162
|
+
* creation methods (like subscribeInfer) already wait for initialization.
|
|
163
|
+
*/
|
|
164
|
+
get initialized(): Promise<boolean> {
|
|
165
|
+
return this.#initialized;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Get the latest query result
|
|
169
|
+
*
|
|
170
|
+
* This returns the most recent result from the query, which could be either:
|
|
171
|
+
* - The initial result from when the subscription was created
|
|
172
|
+
* - The latest update received through the subscription
|
|
173
|
+
*
|
|
174
|
+
* @returns The latest query result as a string (usually a JSON array of bindings)
|
|
175
|
+
*/
|
|
176
|
+
get result(): AllInstancesResult {
|
|
177
|
+
return this.#latestResult;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Add a callback that will be called whenever new results arrive
|
|
181
|
+
*
|
|
182
|
+
* The callback will be called immediately with the current result,
|
|
183
|
+
* and then again each time the query results change.
|
|
184
|
+
*
|
|
185
|
+
* @param callback - Function that takes a result string and processes it
|
|
186
|
+
* @returns A function that can be called to remove this callback
|
|
187
|
+
*
|
|
188
|
+
* Example:
|
|
189
|
+
* ```typescript
|
|
190
|
+
* const removeCallback = subscription.onResult(result => {
|
|
191
|
+
* const bindings = JSON.parse(result);
|
|
192
|
+
* console.log("New bindings:", bindings);
|
|
193
|
+
* });
|
|
194
|
+
*
|
|
195
|
+
* // Later: stop receiving updates
|
|
196
|
+
* removeCallback();
|
|
197
|
+
* ```
|
|
198
|
+
*/
|
|
199
|
+
onResult(callback: QueryCallback): () => void {
|
|
200
|
+
this.#callbacks.add(callback);
|
|
201
|
+
return () => this.#callbacks.delete(callback);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Internal method to notify all callbacks of a new result */
|
|
205
|
+
#notifyCallbacks(result: AllInstancesResult) {
|
|
206
|
+
for (const callback of this.#callbacks) {
|
|
207
|
+
try {
|
|
208
|
+
callback(result);
|
|
209
|
+
} catch (e) {
|
|
210
|
+
console.error('Error in query subscription callback:', e);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Clean up the subscription and stop keepalive signals
|
|
216
|
+
*
|
|
217
|
+
* This method:
|
|
218
|
+
* 1. Stops the keepalive timer
|
|
219
|
+
* 2. Unsubscribes from GraphQL subscription updates
|
|
220
|
+
* 3. Clears all registered callbacks
|
|
221
|
+
* 4. Cleans up any pending initialization timeout
|
|
222
|
+
*
|
|
223
|
+
* After calling this method, the subscription is no longer active and
|
|
224
|
+
* will not receive any more updates. The instance should be discarded.
|
|
225
|
+
*/
|
|
226
|
+
dispose() {
|
|
227
|
+
this.#disposed = true;
|
|
228
|
+
clearTimeout(this.#keepaliveTimer);
|
|
229
|
+
if (this.#unsubscribe) {
|
|
230
|
+
this.#unsubscribe();
|
|
231
|
+
}
|
|
232
|
+
this.#callbacks.clear();
|
|
233
|
+
if (this.#initTimeoutId) {
|
|
234
|
+
clearTimeout(this.#initTimeoutId);
|
|
235
|
+
this.#initTimeoutId = undefined;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// Tell the backend to dispose of the subscription
|
|
239
|
+
if (this.#subscriptionId) {
|
|
240
|
+
this.#client.disposeQuerySubscription(this.#uuid, this.#subscriptionId)
|
|
241
|
+
.catch(e => console.error('Error disposing query subscription:', e));
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
12
245
|
|
|
13
246
|
type PerspectiveListenerTypes = "link-added" | "link-removed" | "link-updated"
|
|
14
247
|
|
|
@@ -18,26 +251,59 @@ interface Parameter {
|
|
|
18
251
|
value: string
|
|
19
252
|
}
|
|
20
253
|
|
|
21
|
-
/**
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
* a
|
|
254
|
+
/**
|
|
255
|
+
* PerspectiveProxy provides a high-level interface for working with AD4M Perspectives - agent-centric semantic graphs
|
|
256
|
+
* that store and organize links between expressions.
|
|
257
|
+
*
|
|
258
|
+
* A Perspective is fundamentally a collection of links (subject-predicate-object triples) that represent an agent's view
|
|
259
|
+
* of their digital world. Through PerspectiveProxy, you can:
|
|
260
|
+
* - Add, remove, and query links
|
|
261
|
+
* - Work with Social DNA (subject classes and flows)
|
|
262
|
+
* - Subscribe to real-time updates
|
|
263
|
+
* - Share perspectives as Neighbourhoods
|
|
264
|
+
* - Execute Prolog queries for complex graph patterns
|
|
265
|
+
*
|
|
266
|
+
*
|
|
267
|
+
* @example
|
|
268
|
+
* ```typescript
|
|
269
|
+
* // Create and work with links
|
|
270
|
+
* const perspective = await ad4m.perspective.add("My Space");
|
|
271
|
+
* await perspective.add({
|
|
272
|
+
* source: "did:key:alice",
|
|
273
|
+
* predicate: "knows",
|
|
274
|
+
* target: "did:key:bob"
|
|
275
|
+
* });
|
|
276
|
+
*
|
|
277
|
+
* // Query links
|
|
278
|
+
* const friends = await perspective.get({
|
|
279
|
+
* source: "did:key:alice",
|
|
280
|
+
* predicate: "knows"
|
|
281
|
+
* });
|
|
282
|
+
*
|
|
283
|
+
* // Use Social DNA
|
|
284
|
+
* await perspective.addSdna(todoClass, "subject_class");
|
|
285
|
+
* const todo = await perspective.createSubject("Todo", "expression://123");
|
|
286
|
+
*
|
|
287
|
+
* // Subscribe to changes
|
|
288
|
+
* perspective.addListener("link-added", (link) => {
|
|
289
|
+
* console.log("New link added:", link);
|
|
290
|
+
* });
|
|
291
|
+
* ```
|
|
26
292
|
*/
|
|
27
293
|
export class PerspectiveProxy {
|
|
28
|
-
/** Unique
|
|
294
|
+
/** Unique identifier of this perspective */
|
|
29
295
|
uuid: string;
|
|
30
296
|
|
|
31
|
-
/**
|
|
297
|
+
/** Human-readable name of this perspective */
|
|
32
298
|
name: string;
|
|
33
299
|
|
|
34
|
-
/** If
|
|
300
|
+
/** If this perspective is shared as a Neighbourhood, this is its URL */
|
|
35
301
|
sharedUrl: string|null;
|
|
36
302
|
|
|
37
|
-
/** If
|
|
303
|
+
/** If this perspective is shared, this contains the Neighbourhood metadata */
|
|
38
304
|
neighbourhood: NeighbourhoodExpression|null;
|
|
39
305
|
|
|
40
|
-
/**
|
|
306
|
+
/** Current sync state if this perspective is shared */
|
|
41
307
|
state: PerspectiveState|null;
|
|
42
308
|
|
|
43
309
|
#handle: PerspectiveHandle
|
|
@@ -47,6 +313,10 @@ export class PerspectiveProxy {
|
|
|
47
313
|
#perspectiveLinkUpdatedCallbacks: LinkCallback[]
|
|
48
314
|
#perspectiveSyncStateChangeCallbacks: SyncStateChangeCallback[]
|
|
49
315
|
|
|
316
|
+
/**
|
|
317
|
+
* Creates a new PerspectiveProxy instance.
|
|
318
|
+
* Note: Don't create this directly, use ad4m.perspective.add() instead.
|
|
319
|
+
*/
|
|
50
320
|
constructor(handle: PerspectiveHandle, ad4m: PerspectiveClient) {
|
|
51
321
|
this.#perspectiveLinkAddedCallbacks = []
|
|
52
322
|
this.#perspectiveLinkRemovedCallbacks = []
|
|
@@ -65,64 +335,270 @@ export class PerspectiveProxy {
|
|
|
65
335
|
this.#client.addPerspectiveSyncStateChangeListener(this.#handle.uuid, this.#perspectiveSyncStateChangeCallbacks)
|
|
66
336
|
}
|
|
67
337
|
|
|
68
|
-
|
|
69
|
-
|
|
338
|
+
/**
|
|
339
|
+
* Executes a set of actions on an expression with optional parameters.
|
|
340
|
+
* Used internally by Social DNA flows and subject class operations.
|
|
341
|
+
*
|
|
342
|
+
* Actions are specified as an array of commands that modify links in the perspective.
|
|
343
|
+
* Each action is an object with the following format:
|
|
344
|
+
* ```typescript
|
|
345
|
+
* {
|
|
346
|
+
* action: "addLink" | "removeLink" | "setSingleTarget" | "collectionSetter",
|
|
347
|
+
* source: string, // Usually "this" to reference the current expression
|
|
348
|
+
* predicate: string, // The predicate URI
|
|
349
|
+
* target: string // The target value or "value" for parameters
|
|
350
|
+
* }
|
|
351
|
+
* ```
|
|
352
|
+
*
|
|
353
|
+
* Available commands:
|
|
354
|
+
* - `addLink`: Creates a new link
|
|
355
|
+
* - `removeLink`: Removes an existing link
|
|
356
|
+
* - `setSingleTarget`: Removes all existing links with the same source/predicate and adds a new one
|
|
357
|
+
* - `collectionSetter`: Special command for setting collection properties
|
|
358
|
+
*
|
|
359
|
+
* When used with parameters, the special value "value" in the target field will be
|
|
360
|
+
* replaced with the actual parameter value.
|
|
361
|
+
*
|
|
362
|
+
* @example
|
|
363
|
+
* ```typescript
|
|
364
|
+
* // Add a state link and remove an old one
|
|
365
|
+
* await perspective.executeAction([
|
|
366
|
+
* {
|
|
367
|
+
* action: "addLink",
|
|
368
|
+
* source: "this",
|
|
369
|
+
* predicate: "todo://state",
|
|
370
|
+
* target: "todo://doing"
|
|
371
|
+
* },
|
|
372
|
+
* {
|
|
373
|
+
* action: "removeLink",
|
|
374
|
+
* source: "this",
|
|
375
|
+
* predicate: "todo://state",
|
|
376
|
+
* target: "todo://ready"
|
|
377
|
+
* }
|
|
378
|
+
* ], "expression://123");
|
|
379
|
+
*
|
|
380
|
+
* // Set a property using a parameter
|
|
381
|
+
* await perspective.executeAction([
|
|
382
|
+
* {
|
|
383
|
+
* action: "setSingleTarget",
|
|
384
|
+
* source: "this",
|
|
385
|
+
* predicate: "todo://title",
|
|
386
|
+
* target: "value"
|
|
387
|
+
* }
|
|
388
|
+
* ], "expression://123", [
|
|
389
|
+
* { name: "title", value: "New Title" }
|
|
390
|
+
* ]);
|
|
391
|
+
* ```
|
|
392
|
+
*
|
|
393
|
+
* @param actions - Array of action objects to execute
|
|
394
|
+
* @param expression - Target expression address (replaces "this" in actions)
|
|
395
|
+
* @param parameters - Optional parameters that replace "value" in actions
|
|
396
|
+
* @param batchId - Optional batch ID to group this operation with others
|
|
397
|
+
*/
|
|
398
|
+
async executeAction(actions, expression, parameters: Parameter[], batchId?: string) {
|
|
399
|
+
return await this.#client.executeCommands(this.#handle.uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId)
|
|
70
400
|
}
|
|
71
401
|
|
|
72
|
-
/**
|
|
402
|
+
/**
|
|
403
|
+
* Retrieves links from the perspective that match the given query.
|
|
404
|
+
*
|
|
405
|
+
* @param query - Query parameters to filter links
|
|
406
|
+
* @returns Array of matching LinkExpressions
|
|
407
|
+
*
|
|
408
|
+
* @example
|
|
409
|
+
* ```typescript
|
|
410
|
+
* // Get all links where Alice knows someone
|
|
411
|
+
* const links = await perspective.get({
|
|
412
|
+
* source: "did:key:alice",
|
|
413
|
+
* predicate: "knows"
|
|
414
|
+
* });
|
|
415
|
+
*
|
|
416
|
+
* // Get all comments on a post
|
|
417
|
+
* const comments = await perspective.get({
|
|
418
|
+
* source: "post://123",
|
|
419
|
+
* predicate: "comment"
|
|
420
|
+
* });
|
|
421
|
+
* ```
|
|
422
|
+
*/
|
|
73
423
|
async get(query: LinkQuery): Promise<LinkExpression[]> {
|
|
74
424
|
return await this.#client.queryLinks(this.#handle.uuid, query)
|
|
75
425
|
}
|
|
76
426
|
|
|
77
|
-
/**
|
|
427
|
+
/**
|
|
428
|
+
* Executes a Prolog query against the perspective's knowledge base.
|
|
429
|
+
* This is a powerful way to find complex patterns in the graph.
|
|
430
|
+
*
|
|
431
|
+
* @param query - Prolog query string
|
|
432
|
+
* @returns Query results or false if no results
|
|
433
|
+
*
|
|
434
|
+
* @example
|
|
435
|
+
* ```typescript
|
|
436
|
+
* // Find friends of friends
|
|
437
|
+
* const results = await perspective.infer(`
|
|
438
|
+
* triple(A, "knows", B),
|
|
439
|
+
* triple(B, "knows", C),
|
|
440
|
+
* A \= C
|
|
441
|
+
* `);
|
|
442
|
+
*
|
|
443
|
+
* // Find all active todos
|
|
444
|
+
* const todos = await perspective.infer(`
|
|
445
|
+
* instance(Todo, "Todo"),
|
|
446
|
+
* property_getter("Todo", Todo, "state", "active")
|
|
447
|
+
* `);
|
|
448
|
+
* ```
|
|
449
|
+
*/
|
|
78
450
|
async infer(query: string): Promise<any> {
|
|
79
451
|
return await this.#client.queryProlog(this.#handle.uuid, query)
|
|
80
452
|
}
|
|
81
453
|
|
|
82
|
-
/**
|
|
83
|
-
|
|
84
|
-
|
|
454
|
+
/**
|
|
455
|
+
* Adds a new link to the perspective.
|
|
456
|
+
*
|
|
457
|
+
* @param link - The link to add
|
|
458
|
+
* @param status - Whether the link should be shared in a Neighbourhood
|
|
459
|
+
* @param batchId - Optional batch ID to group this operation with others
|
|
460
|
+
* @returns The created LinkExpression
|
|
461
|
+
*
|
|
462
|
+
* @example
|
|
463
|
+
* ```typescript
|
|
464
|
+
* // Add a simple relationship
|
|
465
|
+
* await perspective.add({
|
|
466
|
+
* source: "did:key:alice",
|
|
467
|
+
* predicate: "follows",
|
|
468
|
+
* target: "did:key:bob"
|
|
469
|
+
* });
|
|
470
|
+
*
|
|
471
|
+
* // Add a local-only link
|
|
472
|
+
* await perspective.add({
|
|
473
|
+
* source: "note://123",
|
|
474
|
+
* predicate: "tag",
|
|
475
|
+
* target: "private"
|
|
476
|
+
* }, "local");
|
|
477
|
+
* ```
|
|
478
|
+
*/
|
|
479
|
+
async add(link: Link, status: LinkStatus = 'shared', batchId?: string): Promise<LinkExpression> {
|
|
480
|
+
return await this.#client.addLink(this.#handle.uuid, link, status, batchId)
|
|
85
481
|
}
|
|
86
482
|
|
|
87
|
-
/**
|
|
88
|
-
|
|
89
|
-
|
|
483
|
+
/**
|
|
484
|
+
* Adds multiple links to the perspective in a single operation.
|
|
485
|
+
* More efficient than adding links one by one.
|
|
486
|
+
*
|
|
487
|
+
* @param links - Array of links to add
|
|
488
|
+
* @param status - Whether the links should be shared
|
|
489
|
+
* @param batchId - Optional batch ID to group this operation with others
|
|
490
|
+
* @returns Array of created LinkExpressions
|
|
491
|
+
*/
|
|
492
|
+
async addLinks(links: Link[], status: LinkStatus = 'shared', batchId?: string): Promise<LinkExpression[]> {
|
|
493
|
+
return await this.#client.addLinks(this.#handle.uuid, links, status, batchId)
|
|
90
494
|
}
|
|
91
495
|
|
|
92
|
-
/**
|
|
93
|
-
|
|
94
|
-
|
|
496
|
+
/**
|
|
497
|
+
* Removes multiple links from the perspective.
|
|
498
|
+
*
|
|
499
|
+
* @param links - Array of links to remove
|
|
500
|
+
* @param batchId - Optional batch ID to group this operation with others
|
|
501
|
+
* @returns Array of removed LinkExpressions
|
|
502
|
+
*/
|
|
503
|
+
async removeLinks(links: LinkExpressionInput[], batchId?: string): Promise<LinkExpression[]> {
|
|
504
|
+
return await this.#client.removeLinks(this.#handle.uuid, links, batchId)
|
|
95
505
|
}
|
|
96
506
|
|
|
97
|
-
/**
|
|
507
|
+
/**
|
|
508
|
+
* Applies a set of link mutations (adds and removes) in a single operation.
|
|
509
|
+
* Useful for atomic updates to the perspective.
|
|
510
|
+
*
|
|
511
|
+
* @param mutations - Object containing links to add and remove
|
|
512
|
+
* @param status - Whether new links should be shared
|
|
513
|
+
* @returns Object containing results of the mutations
|
|
514
|
+
*/
|
|
98
515
|
async linkMutations(mutations: LinkMutations, status: LinkStatus = 'shared'): Promise<LinkExpressionMutations> {
|
|
99
516
|
return await this.#client.linkMutations(this.#handle.uuid, mutations, status)
|
|
100
517
|
}
|
|
101
518
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
519
|
+
/**
|
|
520
|
+
* Adds a pre-signed LinkExpression to the perspective.
|
|
521
|
+
*
|
|
522
|
+
* @param link - The signed LinkExpression to add
|
|
523
|
+
* @param status - Whether the link should be shared
|
|
524
|
+
* @param batchId - Optional batch ID to group this operation with others
|
|
525
|
+
* @returns The added LinkExpression
|
|
526
|
+
*/
|
|
527
|
+
async addLinkExpression(link: LinkExpression, status: LinkStatus = 'shared', batchId?: string): Promise<LinkExpression> {
|
|
528
|
+
return await this.#client.addLinkExpression(this.#handle.uuid, link, status, batchId)
|
|
105
529
|
}
|
|
106
530
|
|
|
107
|
-
|
|
108
|
-
|
|
531
|
+
/**
|
|
532
|
+
* Updates an existing link with new data.
|
|
533
|
+
*
|
|
534
|
+
* @param oldLink - The existing link to update
|
|
535
|
+
* @param newLink - The new link data
|
|
536
|
+
* @param batchId - Optional batch ID to group this operation with others
|
|
537
|
+
*/
|
|
538
|
+
async update(oldLink: LinkExpressionInput, newLink: Link, batchId?: string): Promise<LinkExpression> {
|
|
539
|
+
return await this.#client.updateLink(this.#handle.uuid, oldLink, newLink, batchId)
|
|
109
540
|
}
|
|
110
541
|
|
|
111
|
-
|
|
112
|
-
|
|
542
|
+
/**
|
|
543
|
+
* Removes a link from the perspective.
|
|
544
|
+
*
|
|
545
|
+
* @param link - The link to remove
|
|
546
|
+
* @param batchId - Optional batch ID to group this operation with others
|
|
547
|
+
*/
|
|
548
|
+
async remove(link: LinkExpressionInput, batchId?: string): Promise<boolean> {
|
|
549
|
+
return await this.#client.removeLink(this.#handle.uuid, link, batchId)
|
|
113
550
|
}
|
|
114
551
|
|
|
552
|
+
/** Creates a new batch for grouping operations */
|
|
553
|
+
async createBatch(): Promise<string> {
|
|
554
|
+
return await this.#client.createBatch(this.#handle.uuid)
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/** Commits a batch of operations */
|
|
558
|
+
async commitBatch(batchId: string): Promise<LinkExpressionMutations> {
|
|
559
|
+
return await this.#client.commitBatch(this.#handle.uuid, batchId)
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* Retrieves and renders an Expression referenced in this perspective.
|
|
565
|
+
*
|
|
566
|
+
* @param expressionURI - URI of the Expression to retrieve
|
|
567
|
+
* @returns The rendered Expression
|
|
568
|
+
*/
|
|
115
569
|
async getExpression(expressionURI: string): Promise<ExpressionRendered> {
|
|
116
570
|
return await this.#client.getExpression(expressionURI)
|
|
117
571
|
}
|
|
118
572
|
|
|
573
|
+
/**
|
|
574
|
+
* Creates a new Expression in the specified Language.
|
|
575
|
+
*
|
|
576
|
+
* @param content - Content for the new Expression
|
|
577
|
+
* @param languageAddress - Address of the Language to use
|
|
578
|
+
* @returns URI of the created Expression
|
|
579
|
+
*/
|
|
119
580
|
async createExpression(content: any, languageAddress: string): Promise<string> {
|
|
120
581
|
return await this.#client.createExpression(content, languageAddress)
|
|
121
582
|
}
|
|
122
583
|
|
|
123
|
-
/**
|
|
124
|
-
*
|
|
125
|
-
*
|
|
584
|
+
/**
|
|
585
|
+
* Subscribes to link changes in the perspective.
|
|
586
|
+
*
|
|
587
|
+
* @param type - Type of change to listen for
|
|
588
|
+
* @param cb - Callback function
|
|
589
|
+
*
|
|
590
|
+
* @example
|
|
591
|
+
* ```typescript
|
|
592
|
+
* // Listen for new links
|
|
593
|
+
* perspective.addListener("link-added", (link) => {
|
|
594
|
+
* console.log("New link:", link);
|
|
595
|
+
* });
|
|
596
|
+
*
|
|
597
|
+
* // Listen for removed links
|
|
598
|
+
* perspective.addListener("link-removed", (link) => {
|
|
599
|
+
* console.log("Link removed:", link);
|
|
600
|
+
* });
|
|
601
|
+
* ```
|
|
126
602
|
*/
|
|
127
603
|
async addListener(type: PerspectiveListenerTypes, cb: LinkCallback) {
|
|
128
604
|
if (type === 'link-added') {
|
|
@@ -134,17 +610,27 @@ export class PerspectiveProxy {
|
|
|
134
610
|
}
|
|
135
611
|
}
|
|
136
612
|
|
|
137
|
-
/**
|
|
138
|
-
*
|
|
139
|
-
*
|
|
613
|
+
/**
|
|
614
|
+
* Subscribes to sync state changes if this perspective is shared.
|
|
615
|
+
*
|
|
616
|
+
* @param cb - Callback function
|
|
617
|
+
*
|
|
618
|
+
* @example
|
|
619
|
+
* ```typescript
|
|
620
|
+
* perspective.addSyncStateChangeListener((state) => {
|
|
621
|
+
* console.log("Sync state:", state);
|
|
622
|
+
* });
|
|
623
|
+
* ```
|
|
140
624
|
*/
|
|
141
625
|
async addSyncStateChangeListener(cb: SyncStateChangeCallback) {
|
|
142
626
|
this.#perspectiveSyncStateChangeCallbacks.push(cb)
|
|
143
627
|
}
|
|
144
628
|
|
|
145
|
-
/**
|
|
146
|
-
*
|
|
147
|
-
*
|
|
629
|
+
/**
|
|
630
|
+
* Unsubscribes from link changes.
|
|
631
|
+
*
|
|
632
|
+
* @param type - Type of change to stop listening for
|
|
633
|
+
* @param cb - The callback function to remove
|
|
148
634
|
*/
|
|
149
635
|
async removeListener(type: PerspectiveListenerTypes, cb: LinkCallback) {
|
|
150
636
|
if (type === 'link-added') {
|
|
@@ -162,15 +648,21 @@ export class PerspectiveProxy {
|
|
|
162
648
|
}
|
|
163
649
|
}
|
|
164
650
|
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
*
|
|
651
|
+
/**
|
|
652
|
+
* Creates a snapshot of the current perspective state.
|
|
653
|
+
* Useful for backup or sharing.
|
|
654
|
+
*
|
|
655
|
+
* @returns Perspective object containing all links
|
|
168
656
|
*/
|
|
169
657
|
async snapshot(): Promise<Perspective> {
|
|
170
658
|
return this.#client.snapshotByUUID(this.#handle.uuid)
|
|
171
659
|
}
|
|
172
660
|
|
|
173
|
-
/**
|
|
661
|
+
/**
|
|
662
|
+
* Loads a perspective snapshot, replacing current content.
|
|
663
|
+
*
|
|
664
|
+
* @param snapshot - Perspective snapshot to load
|
|
665
|
+
*/
|
|
174
666
|
async loadSnapshot(snapshot: Perspective) {
|
|
175
667
|
//Clean the input data from __typename
|
|
176
668
|
const cleanedSnapshot = JSON.parse(JSON.stringify(snapshot));
|
|
@@ -184,11 +676,21 @@ export class PerspectiveProxy {
|
|
|
184
676
|
}
|
|
185
677
|
}
|
|
186
678
|
|
|
187
|
-
/**
|
|
188
|
-
*
|
|
189
|
-
*
|
|
190
|
-
*
|
|
191
|
-
*
|
|
679
|
+
/**
|
|
680
|
+
* Gets a single target value matching a query.
|
|
681
|
+
* Useful when you expect only one result.
|
|
682
|
+
*
|
|
683
|
+
* @param query - Query to find the target
|
|
684
|
+
* @returns Target value or void if not found
|
|
685
|
+
*
|
|
686
|
+
* @example
|
|
687
|
+
* ```typescript
|
|
688
|
+
* // Get a user's name
|
|
689
|
+
* const name = await perspective.getSingleTarget({
|
|
690
|
+
* source: "did:key:alice",
|
|
691
|
+
* predicate: "name"
|
|
692
|
+
* });
|
|
693
|
+
* ```
|
|
192
694
|
*/
|
|
193
695
|
async getSingleTarget(query: LinkQuery): Promise<string|void> {
|
|
194
696
|
delete query.target
|
|
@@ -199,12 +701,21 @@ export class PerspectiveProxy {
|
|
|
199
701
|
return null
|
|
200
702
|
}
|
|
201
703
|
|
|
202
|
-
/**
|
|
203
|
-
*
|
|
204
|
-
*
|
|
205
|
-
*
|
|
206
|
-
*
|
|
207
|
-
*
|
|
704
|
+
/**
|
|
705
|
+
* Sets a single target value, removing any existing targets.
|
|
706
|
+
*
|
|
707
|
+
* @param link - Link defining the new target
|
|
708
|
+
* @param status - Whether the link should be shared
|
|
709
|
+
*
|
|
710
|
+
* @example
|
|
711
|
+
* ```typescript
|
|
712
|
+
* // Set a user's status
|
|
713
|
+
* await perspective.setSingleTarget({
|
|
714
|
+
* source: "did:key:alice",
|
|
715
|
+
* predicate: "status",
|
|
716
|
+
* target: "online"
|
|
717
|
+
* });
|
|
718
|
+
* ```
|
|
208
719
|
*/
|
|
209
720
|
async setSingleTarget(link: Link, status: LinkStatus = 'shared') {
|
|
210
721
|
const query = new LinkQuery({source: link.source, predicate: link.predicate})
|
|
@@ -271,11 +782,75 @@ export class PerspectiveProxy {
|
|
|
271
782
|
* This will return all SDNA code elements in an array.
|
|
272
783
|
*/
|
|
273
784
|
async getSdna(): Promise<string[]> {
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
785
|
+
// First, find all the name literals that are linked from ad4m://self with SDNA predicates
|
|
786
|
+
const sdnaPredicates = [
|
|
787
|
+
"ad4m://has_subject_class",
|
|
788
|
+
"ad4m://has_flow",
|
|
789
|
+
"ad4m://has_custom_sdna"
|
|
790
|
+
];
|
|
791
|
+
|
|
792
|
+
const allSdnaCode: string[] = [];
|
|
793
|
+
|
|
794
|
+
for (const predicate of sdnaPredicates) {
|
|
795
|
+
// Find name literals linked from ad4m://self with this predicate
|
|
796
|
+
const nameLinks = await this.get(new LinkQuery({
|
|
797
|
+
source: "ad4m://self",
|
|
798
|
+
predicate: predicate
|
|
799
|
+
}));
|
|
800
|
+
|
|
801
|
+
// For each name literal found, get the actual SDNA code
|
|
802
|
+
for (const nameLink of nameLinks) {
|
|
803
|
+
const nameLiteral = nameLink.data.target;
|
|
804
|
+
|
|
805
|
+
// Now find the SDNA code linked from this name with predicate "ad4m://sdna"
|
|
806
|
+
const sdnaLinks = await this.get(new LinkQuery({
|
|
807
|
+
source: nameLiteral,
|
|
808
|
+
predicate: "ad4m://sdna"
|
|
809
|
+
}));
|
|
810
|
+
|
|
811
|
+
// Extract the SDNA code from each link
|
|
812
|
+
for (const sdnaLink of sdnaLinks) {
|
|
813
|
+
const code = Literal.fromUrl(sdnaLink.data.target).get();
|
|
814
|
+
if (typeof code === 'string') {
|
|
815
|
+
allSdnaCode.push(code);
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
return allSdnaCode;
|
|
822
|
+
}
|
|
277
823
|
|
|
278
|
-
|
|
824
|
+
/** Returns the Social DNA code for a specific class
|
|
825
|
+
* This will return the SDNA code for the specified class, or null if not found.
|
|
826
|
+
*/
|
|
827
|
+
async getSdnaForClass(className: string): Promise<string | null> {
|
|
828
|
+
// First, find the name literal for this class that is linked from ad4m://self
|
|
829
|
+
const nameLiteral = Literal.from(className);
|
|
830
|
+
|
|
831
|
+
const links = await this.get(new LinkQuery({
|
|
832
|
+
source: "ad4m://self",
|
|
833
|
+
target: nameLiteral.toUrl(),
|
|
834
|
+
predicate: "ad4m://has_subject_class"
|
|
835
|
+
}));
|
|
836
|
+
|
|
837
|
+
if (links.length === 0) {
|
|
838
|
+
return null;
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
// Now find the SDNA code linked from this name with predicate "ad4m://sdna"
|
|
842
|
+
const sdnaLinks = await this.get(new LinkQuery({
|
|
843
|
+
source: nameLiteral.toUrl(),
|
|
844
|
+
predicate: "ad4m://sdna"
|
|
845
|
+
}));
|
|
846
|
+
|
|
847
|
+
if (sdnaLinks.length === 0) {
|
|
848
|
+
return null;
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
// Extract the SDNA code from the first link
|
|
852
|
+
const code = Literal.fromUrl(sdnaLinks[0].data.target).get();
|
|
853
|
+
return typeof code === 'string' ? code : null;
|
|
279
854
|
}
|
|
280
855
|
|
|
281
856
|
/** Adds the given Social DNA code to the perspective's SDNA code */
|
|
@@ -292,7 +867,7 @@ export class PerspectiveProxy {
|
|
|
292
867
|
}
|
|
293
868
|
}
|
|
294
869
|
|
|
295
|
-
async
|
|
870
|
+
async stringOrTemplateObjectToSubjectClassName<T>(subjectClass: T): Promise<string> {
|
|
296
871
|
if(typeof subjectClass === "string")
|
|
297
872
|
return subjectClass
|
|
298
873
|
else {
|
|
@@ -306,28 +881,58 @@ export class PerspectiveProxy {
|
|
|
306
881
|
}
|
|
307
882
|
}
|
|
308
883
|
|
|
309
|
-
/**
|
|
310
|
-
*
|
|
311
|
-
*
|
|
312
|
-
*
|
|
884
|
+
/**
|
|
885
|
+
* Creates a new subject instance of the given subject class
|
|
886
|
+
*
|
|
313
887
|
* @param subjectClass Either a string with the name of the subject class, or an object
|
|
314
|
-
* with the properties of the subject class.
|
|
315
|
-
* that matches the given properties will be used.
|
|
888
|
+
* with the properties of the subject class.
|
|
316
889
|
* @param exprAddr The address of the expression to be turned into a subject instance
|
|
890
|
+
* @param initialValues Optional initial values for properties. If provided, these will be
|
|
891
|
+
* merged with constructor actions for better performance.
|
|
892
|
+
* @param batchId Optional batch ID for grouping operations. If provided, returns the expression address
|
|
893
|
+
* instead of the subject proxy since the subject won't exist until the batch is committed.
|
|
894
|
+
* @returns A proxy object for the created subject, or just the expression address if in batch mode
|
|
317
895
|
*/
|
|
318
|
-
async createSubject<T
|
|
896
|
+
async createSubject<T, B extends string | undefined = undefined>(
|
|
897
|
+
subjectClass: T,
|
|
898
|
+
exprAddr: string,
|
|
899
|
+
initialValues?: Record<string, any>,
|
|
900
|
+
batchId?: B
|
|
901
|
+
): Promise<B extends undefined ? T : string> {
|
|
319
902
|
let className: string;
|
|
320
903
|
|
|
321
904
|
if(typeof subjectClass === "string") {
|
|
322
|
-
className = subjectClass
|
|
323
|
-
|
|
324
|
-
|
|
905
|
+
className = subjectClass;
|
|
906
|
+
await this.#client.createSubject(
|
|
907
|
+
this.#handle.uuid,
|
|
908
|
+
JSON.stringify({
|
|
909
|
+
className,
|
|
910
|
+
initialValues
|
|
911
|
+
}),
|
|
912
|
+
exprAddr,
|
|
913
|
+
initialValues ? JSON.stringify(initialValues) : undefined,
|
|
914
|
+
batchId
|
|
915
|
+
);
|
|
325
916
|
} else {
|
|
326
|
-
let query = this.buildQueryFromTemplate(subjectClass as object)
|
|
327
|
-
await this.#client.createSubject(
|
|
917
|
+
let query = this.buildQueryFromTemplate(subjectClass as object);
|
|
918
|
+
await this.#client.createSubject(
|
|
919
|
+
this.#handle.uuid,
|
|
920
|
+
JSON.stringify({
|
|
921
|
+
query,
|
|
922
|
+
initialValues
|
|
923
|
+
}),
|
|
924
|
+
exprAddr,
|
|
925
|
+
initialValues ? JSON.stringify(initialValues) : undefined,
|
|
926
|
+
batchId
|
|
927
|
+
);
|
|
328
928
|
}
|
|
329
929
|
|
|
330
|
-
|
|
930
|
+
// Skip subject proxy creation when in batch mode since the subject won't exist until batch is committed
|
|
931
|
+
if (batchId) {
|
|
932
|
+
return exprAddr as B extends undefined ? T : string;
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
return this.getSubjectProxy(exprAddr, subjectClass) as Promise<B extends undefined ? T : string>;
|
|
331
936
|
}
|
|
332
937
|
|
|
333
938
|
async getSubjectData<T>(subjectClass: T, exprAddr: string): Promise<T> {
|
|
@@ -345,16 +950,18 @@ export class PerspectiveProxy {
|
|
|
345
950
|
* with the properties of the subject class. In the latter case, the first subject class
|
|
346
951
|
* that matches the given properties will be used.
|
|
347
952
|
* @param exprAddr The address of the expression to be turned into a subject instance
|
|
953
|
+
* @param batchId Optional batch ID for grouping operations. If provided, the removal will be part of the batch
|
|
954
|
+
* and won't be executed until the batch is committed.
|
|
348
955
|
*/
|
|
349
|
-
async removeSubject<T>(subjectClass: T, exprAddr: string) {
|
|
350
|
-
let className = await this.
|
|
956
|
+
async removeSubject<T>(subjectClass: T, exprAddr: string, batchId?: string) {
|
|
957
|
+
let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass)
|
|
351
958
|
let result = await this.infer(`subject_class("${className}", C), destructor(C, Actions)`)
|
|
352
959
|
if(!result.length) {
|
|
353
|
-
throw "No
|
|
960
|
+
throw "No destructor found for given subject class: " + className
|
|
354
961
|
}
|
|
355
962
|
|
|
356
963
|
let actions = result.map(x => eval(x.Actions))
|
|
357
|
-
await this.executeAction(actions[0], exprAddr, undefined)
|
|
964
|
+
await this.executeAction(actions[0], exprAddr, undefined, batchId)
|
|
358
965
|
}
|
|
359
966
|
|
|
360
967
|
/** Checks if the given expression is a subject instance of the given subject class
|
|
@@ -364,7 +971,7 @@ export class PerspectiveProxy {
|
|
|
364
971
|
* that matches the given properties will be used.
|
|
365
972
|
*/
|
|
366
973
|
async isSubjectInstance<T>(expression: string, subjectClass: T): Promise<boolean> {
|
|
367
|
-
let className = await this.
|
|
974
|
+
let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass)
|
|
368
975
|
let isInstance = false;
|
|
369
976
|
const maxAttempts = 5;
|
|
370
977
|
let attempts = 0;
|
|
@@ -391,7 +998,7 @@ export class PerspectiveProxy {
|
|
|
391
998
|
if(!await this.isSubjectInstance(base, subjectClass)) {
|
|
392
999
|
throw `Expression ${base} is not a subject instance of given class: ${JSON.stringify(subjectClass)}`
|
|
393
1000
|
}
|
|
394
|
-
let className = await this.
|
|
1001
|
+
let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass)
|
|
395
1002
|
let subject = new Subject(this, base, className)
|
|
396
1003
|
await subject.init()
|
|
397
1004
|
return subject as unknown as T
|
|
@@ -459,7 +1066,11 @@ export class PerspectiveProxy {
|
|
|
459
1066
|
|
|
460
1067
|
// Collect all collections of the object in a list
|
|
461
1068
|
if (Object.getPrototypeOf(obj).__collections) {
|
|
462
|
-
Object.keys(Object.getPrototypeOf(obj).__collections).filter(key => key !== 'isSubjectInstance').forEach(c =>
|
|
1069
|
+
Object.keys(Object.getPrototypeOf(obj).__collections).filter(key => key !== 'isSubjectInstance').forEach(c => {
|
|
1070
|
+
if (!collections.includes(c)) {
|
|
1071
|
+
collections.push(c);
|
|
1072
|
+
}
|
|
1073
|
+
});
|
|
463
1074
|
} else {
|
|
464
1075
|
collections.push(...Object.keys(obj).filter(key => Array.isArray(obj[key])).filter(key => key !== 'isSubjectInstance'))
|
|
465
1076
|
}
|
|
@@ -571,4 +1182,77 @@ export class PerspectiveProxy {
|
|
|
571
1182
|
return this.#client.getNeighbourhoodProxy(this.#handle.uuid)
|
|
572
1183
|
}
|
|
573
1184
|
|
|
1185
|
+
/**
|
|
1186
|
+
* Returns a proxy object for working with AI capabilities.
|
|
1187
|
+
*
|
|
1188
|
+
* @returns AIClient instance
|
|
1189
|
+
*
|
|
1190
|
+
* @example
|
|
1191
|
+
* ```typescript
|
|
1192
|
+
* // Use AI to analyze perspective content
|
|
1193
|
+
* const summary = await perspective.ai.summarize();
|
|
1194
|
+
*
|
|
1195
|
+
* // Generate new content
|
|
1196
|
+
* const suggestion = await perspective.ai.suggest("next action");
|
|
1197
|
+
* ```
|
|
1198
|
+
*/
|
|
1199
|
+
get ai(): AIClient {
|
|
1200
|
+
return this.#client.aiClient
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
/**
|
|
1204
|
+
* Creates a subscription for a Prolog query that updates in real-time.
|
|
1205
|
+
*
|
|
1206
|
+
* This method:
|
|
1207
|
+
* 1. Creates the subscription on the Rust side
|
|
1208
|
+
* 2. Sets up the subscription callback
|
|
1209
|
+
* 3. Waits for the initial result to come through the subscription channel
|
|
1210
|
+
* 4. Returns a fully initialized QuerySubscriptionProxy
|
|
1211
|
+
*
|
|
1212
|
+
* The returned subscription is guaranteed to be ready to receive updates,
|
|
1213
|
+
* as this method waits for the initialization process to complete.
|
|
1214
|
+
*
|
|
1215
|
+
* The subscription will be automatically cleaned up on both frontend and backend
|
|
1216
|
+
* when dispose() is called. Make sure to call dispose() when you're done to
|
|
1217
|
+
* prevent memory leaks and ensure proper cleanup of resources.
|
|
1218
|
+
*
|
|
1219
|
+
* @param query - Prolog query string
|
|
1220
|
+
* @returns Initialized QuerySubscriptionProxy instance
|
|
1221
|
+
*
|
|
1222
|
+
* @example
|
|
1223
|
+
* ```typescript
|
|
1224
|
+
* // Subscribe to active todos
|
|
1225
|
+
* const subscription = await perspective.subscribeInfer(`
|
|
1226
|
+
* instance(Todo, "Todo"),
|
|
1227
|
+
* property_getter("Todo", Todo, "state", "active")
|
|
1228
|
+
* `);
|
|
1229
|
+
*
|
|
1230
|
+
* // Subscription is already initialized here
|
|
1231
|
+
* console.log("Initial result:", subscription.result);
|
|
1232
|
+
*
|
|
1233
|
+
* // Set up callback for future updates
|
|
1234
|
+
* subscription.onResult((todos) => {
|
|
1235
|
+
* console.log("Active todos:", todos);
|
|
1236
|
+
* });
|
|
1237
|
+
*
|
|
1238
|
+
* // Clean up subscription when done
|
|
1239
|
+
* subscription.dispose();
|
|
1240
|
+
* ```
|
|
1241
|
+
*/
|
|
1242
|
+
async subscribeInfer(query: string): Promise<QuerySubscriptionProxy> {
|
|
1243
|
+
const subscriptionProxy = new QuerySubscriptionProxy(
|
|
1244
|
+
this.uuid,
|
|
1245
|
+
query,
|
|
1246
|
+
this.#client
|
|
1247
|
+
);
|
|
1248
|
+
|
|
1249
|
+
// Start the subscription on the Rust side first to get the real subscription ID
|
|
1250
|
+
await subscriptionProxy.subscribe();
|
|
1251
|
+
|
|
1252
|
+
// Wait for the initial result
|
|
1253
|
+
await subscriptionProxy.initialized;
|
|
1254
|
+
|
|
1255
|
+
return subscriptionProxy;
|
|
1256
|
+
}
|
|
1257
|
+
|
|
574
1258
|
}
|