@coasys/ad4m 0.8.0-fix

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 (167) hide show
  1. package/README.md +229 -0
  2. package/jest-setup.ts +1 -0
  3. package/jest.config.js +6 -0
  4. package/jsdoc.json +28 -0
  5. package/lib/index.cjs +8165 -0
  6. package/lib/index.js +8130 -0
  7. package/lib/shims/reflect-metadata.d.ts +0 -0
  8. package/lib/shims/reflect-metadata.js +0 -0
  9. package/lib/shims/type-graphql.d.ts +32 -0
  10. package/lib/shims/type-graphql.js +70 -0
  11. package/lib/src/Ad4mClient.d.ts +26 -0
  12. package/lib/src/Ad4mClient.js +66 -0
  13. package/lib/src/Address.d.ts +1 -0
  14. package/lib/src/Address.js +1 -0
  15. package/lib/src/DID.d.ts +1 -0
  16. package/lib/src/DID.js +1 -0
  17. package/lib/src/Exception.d.ts +6 -0
  18. package/lib/src/Exception.js +7 -0
  19. package/lib/src/Literal.d.ts +7 -0
  20. package/lib/src/Literal.js +76 -0
  21. package/lib/src/PubSub.d.ts +14 -0
  22. package/lib/src/PubSub.js +14 -0
  23. package/lib/src/SmartLiteral.d.ts +12 -0
  24. package/lib/src/SmartLiteral.js +74 -0
  25. package/lib/src/agent/Agent.d.ts +104 -0
  26. package/lib/src/agent/Agent.js +337 -0
  27. package/lib/src/agent/AgentClient.d.ts +57 -0
  28. package/lib/src/agent/AgentClient.js +431 -0
  29. package/lib/src/agent/AgentResolver.d.ts +30 -0
  30. package/lib/src/agent/AgentResolver.js +325 -0
  31. package/lib/src/agent/AgentStatus.d.ts +8 -0
  32. package/lib/src/agent/AgentStatus.js +61 -0
  33. package/lib/src/buildSchema.d.ts +1 -0
  34. package/lib/src/buildSchema.js +36 -0
  35. package/lib/src/expression/Expression.d.ts +28 -0
  36. package/lib/src/expression/Expression.js +143 -0
  37. package/lib/src/expression/ExpressionClient.d.ts +13 -0
  38. package/lib/src/expression/ExpressionClient.js +102 -0
  39. package/lib/src/expression/ExpressionRef.d.ts +9 -0
  40. package/lib/src/expression/ExpressionRef.js +67 -0
  41. package/lib/src/expression/ExpressionResolver.d.ts +10 -0
  42. package/lib/src/expression/ExpressionResolver.js +106 -0
  43. package/lib/src/index.d.ts +30 -0
  44. package/lib/src/index.js +30 -0
  45. package/lib/src/jestSetup.d.ts +1 -0
  46. package/lib/src/jestSetup.js +1 -0
  47. package/lib/src/language/Icon.d.ts +4 -0
  48. package/lib/src/language/Icon.js +24 -0
  49. package/lib/src/language/Language.d.ts +195 -0
  50. package/lib/src/language/Language.js +79 -0
  51. package/lib/src/language/LanguageClient.d.ts +17 -0
  52. package/lib/src/language/LanguageClient.js +137 -0
  53. package/lib/src/language/LanguageContext.d.ts +37 -0
  54. package/lib/src/language/LanguageContext.js +2 -0
  55. package/lib/src/language/LanguageHandle.d.ts +9 -0
  56. package/lib/src/language/LanguageHandle.js +41 -0
  57. package/lib/src/language/LanguageMeta.d.ts +35 -0
  58. package/lib/src/language/LanguageMeta.js +89 -0
  59. package/lib/src/language/LanguageRef.d.ts +6 -0
  60. package/lib/src/language/LanguageRef.js +30 -0
  61. package/lib/src/language/LanguageResolver.d.ts +19 -0
  62. package/lib/src/language/LanguageResolver.js +143 -0
  63. package/lib/src/links/Links.d.ts +39 -0
  64. package/lib/src/links/Links.js +148 -0
  65. package/lib/src/links/Links.test.d.ts +1 -0
  66. package/lib/src/links/Links.test.js +33 -0
  67. package/lib/src/neighbourhood/Neighbourhood.d.ts +10 -0
  68. package/lib/src/neighbourhood/Neighbourhood.js +38 -0
  69. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +25 -0
  70. package/lib/src/neighbourhood/NeighbourhoodClient.js +256 -0
  71. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +19 -0
  72. package/lib/src/neighbourhood/NeighbourhoodProxy.js +54 -0
  73. package/lib/src/neighbourhood/NeighbourhoodResolver.d.ts +24 -0
  74. package/lib/src/neighbourhood/NeighbourhoodResolver.js +180 -0
  75. package/lib/src/perspectives/LinkQuery.d.ts +11 -0
  76. package/lib/src/perspectives/LinkQuery.js +80 -0
  77. package/lib/src/perspectives/Perspective.d.ts +38 -0
  78. package/lib/src/perspectives/Perspective.js +144 -0
  79. package/lib/src/perspectives/Perspective.test.d.ts +1 -0
  80. package/lib/src/perspectives/Perspective.test.js +20 -0
  81. package/lib/src/perspectives/PerspectiveClient.d.ts +54 -0
  82. package/lib/src/perspectives/PerspectiveClient.js +410 -0
  83. package/lib/src/perspectives/PerspectiveDiff.d.ts +9 -0
  84. package/lib/src/perspectives/PerspectiveDiff.js +33 -0
  85. package/lib/src/perspectives/PerspectiveHandle.d.ts +16 -0
  86. package/lib/src/perspectives/PerspectiveHandle.js +59 -0
  87. package/lib/src/perspectives/PerspectiveProxy.d.ts +178 -0
  88. package/lib/src/perspectives/PerspectiveProxy.js +540 -0
  89. package/lib/src/perspectives/PerspectiveResolver.d.ts +37 -0
  90. package/lib/src/perspectives/PerspectiveResolver.js +362 -0
  91. package/lib/src/runtime/RuntimeClient.d.ts +33 -0
  92. package/lib/src/runtime/RuntimeClient.js +263 -0
  93. package/lib/src/runtime/RuntimeResolver.d.ts +47 -0
  94. package/lib/src/runtime/RuntimeResolver.js +328 -0
  95. package/lib/src/schema.gql +382 -0
  96. package/lib/src/subject/SDNADecorators.d.ts +45 -0
  97. package/lib/src/subject/SDNADecorators.js +250 -0
  98. package/lib/src/subject/Subject.d.ts +7 -0
  99. package/lib/src/subject/Subject.js +160 -0
  100. package/lib/src/subject/SubjectEntity.d.ts +31 -0
  101. package/lib/src/subject/SubjectEntity.js +250 -0
  102. package/lib/src/subject/util.d.ts +12 -0
  103. package/lib/src/subject/util.js +73 -0
  104. package/lib/src/typeDefs.d.ts +1 -0
  105. package/lib/src/typeDefs.js +379 -0
  106. package/lib/src/unwrapApolloResult.d.ts +2 -0
  107. package/lib/src/unwrapApolloResult.js +12 -0
  108. package/lib/src/utils.d.ts +2 -0
  109. package/lib/src/utils.js +21 -0
  110. package/package.json +61 -0
  111. package/rollup.config.js +27 -0
  112. package/shims/reflect-metadata.ts +0 -0
  113. package/shims/type-graphql.ts +75 -0
  114. package/src/Ad4mClient.test.ts +1085 -0
  115. package/src/Ad4mClient.ts +63 -0
  116. package/src/Address.ts +1 -0
  117. package/src/DID.ts +1 -0
  118. package/src/Exception.ts +6 -0
  119. package/src/Literal.test.ts +31 -0
  120. package/src/Literal.ts +81 -0
  121. package/src/PubSub.ts +14 -0
  122. package/src/SmartLiteral.ts +75 -0
  123. package/src/agent/Agent.ts +293 -0
  124. package/src/agent/AgentClient.ts +531 -0
  125. package/src/agent/AgentResolver.ts +263 -0
  126. package/src/agent/AgentStatus.ts +44 -0
  127. package/src/buildSchema.ts +41 -0
  128. package/src/expression/Expression.ts +99 -0
  129. package/src/expression/ExpressionClient.ts +99 -0
  130. package/src/expression/ExpressionRef.ts +63 -0
  131. package/src/expression/ExpressionResolver.ts +64 -0
  132. package/src/index.ts +30 -0
  133. package/src/jestSetup.ts +1 -0
  134. package/src/language/Icon.ts +11 -0
  135. package/src/language/Language.ts +266 -0
  136. package/src/language/LanguageClient.ts +160 -0
  137. package/src/language/LanguageContext.ts +37 -0
  138. package/src/language/LanguageHandle.ts +23 -0
  139. package/src/language/LanguageMeta.ts +70 -0
  140. package/src/language/LanguageRef.ts +18 -0
  141. package/src/language/LanguageResolver.ts +98 -0
  142. package/src/links/Links.test.ts +40 -0
  143. package/src/links/Links.ts +107 -0
  144. package/src/neighbourhood/Neighbourhood.ts +22 -0
  145. package/src/neighbourhood/NeighbourhoodClient.ts +276 -0
  146. package/src/neighbourhood/NeighbourhoodProxy.ts +58 -0
  147. package/src/neighbourhood/NeighbourhoodResolver.ts +100 -0
  148. package/src/perspectives/LinkQuery.ts +66 -0
  149. package/src/perspectives/Perspective.test.ts +23 -0
  150. package/src/perspectives/Perspective.ts +118 -0
  151. package/src/perspectives/PerspectiveClient.ts +444 -0
  152. package/src/perspectives/PerspectiveDiff.ts +15 -0
  153. package/src/perspectives/PerspectiveHandle.ts +39 -0
  154. package/src/perspectives/PerspectiveProxy.ts +611 -0
  155. package/src/perspectives/PerspectiveResolver.ts +220 -0
  156. package/src/runtime/RuntimeClient.ts +283 -0
  157. package/src/runtime/RuntimeResolver.ts +193 -0
  158. package/src/subject/SDNADecorators.ts +334 -0
  159. package/src/subject/Subject.ts +153 -0
  160. package/src/subject/SubjectEntity.ts +292 -0
  161. package/src/subject/util.ts +85 -0
  162. package/src/typeDefs.ts +6 -0
  163. package/src/unwrapApolloResult.ts +14 -0
  164. package/src/utils.ts +25 -0
  165. package/tsconfig-browser.json +82 -0
  166. package/tsconfig.json +80 -0
  167. package/yarn-error.log +22814 -0
@@ -0,0 +1,611 @@
1
+ import { LinkCallback, PerspectiveClient, SyncStateChangeCallback } from "./PerspectiveClient";
2
+ import { Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkMutations } from "../links/Links";
3
+ import { LinkQuery } from "./LinkQuery";
4
+ import { PerspectiveHandle, PerspectiveState } from './PerspectiveHandle'
5
+ import { Perspective } from "./Perspective";
6
+ import { Literal } from "../Literal";
7
+ import { Subject } from "../subject/Subject";
8
+ import { ExpressionRendered } from "../expression/Expression";
9
+ import { collectionAdderToName, collectionRemoverToName, collectionSetterToName } from "../subject/util";
10
+ import { NeighbourhoodProxy } from "../neighbourhood/NeighbourhoodProxy";
11
+ import { NeighbourhoodExpression } from "../neighbourhood/Neighbourhood";
12
+
13
+ type PerspectiveListenerTypes = "link-added" | "link-removed" | "link-updated"
14
+
15
+ export type LinkStatus = "shared" | "local"
16
+ interface Parameter {
17
+ name: string
18
+ value: string
19
+ }
20
+
21
+ /** Perspective UI proxy object
22
+ *
23
+ * Convenience object for UIs to interact with a perspective.
24
+ * It is created by some of the methods in the PerspectiveClient class and includes
25
+ * a reference to the PerspectiveClient object that created it.
26
+ */
27
+ export class PerspectiveProxy {
28
+ #handle: PerspectiveHandle
29
+ #client: PerspectiveClient
30
+ #perspectiveLinkAddedCallbacks: LinkCallback[]
31
+ #perspectiveLinkRemovedCallbacks: LinkCallback[]
32
+ #perspectiveLinkUpdatedCallbacks: LinkCallback[]
33
+ #perspectiveSyncStateChangeCallbacks: SyncStateChangeCallback[]
34
+
35
+ constructor(handle: PerspectiveHandle, ad4m: PerspectiveClient) {
36
+ this.#perspectiveLinkAddedCallbacks = []
37
+ this.#perspectiveLinkRemovedCallbacks = []
38
+ this.#perspectiveLinkUpdatedCallbacks = []
39
+ this.#perspectiveSyncStateChangeCallbacks = []
40
+ this.#handle = handle
41
+ this.#client = ad4m
42
+ this.#client.addPerspectiveLinkAddedListener(this.#handle.uuid, this.#perspectiveLinkAddedCallbacks)
43
+ this.#client.addPerspectiveLinkRemovedListener(this.#handle.uuid, this.#perspectiveLinkRemovedCallbacks)
44
+ this.#client.addPerspectiveLinkUpdatedListener(this.#handle.uuid, this.#perspectiveLinkUpdatedCallbacks)
45
+ this.#client.addPerspectiveSyncStateChangeListener(this.#handle.uuid, this.#perspectiveSyncStateChangeCallbacks)
46
+ }
47
+
48
+ async executeAction(actions, expression, parameters: Parameter[]) {
49
+ const replaceThis = (input: string|undefined) => {
50
+ if(input) {
51
+ if (input === 'this') {
52
+ return expression
53
+ } else {
54
+ return input
55
+ }
56
+ } else {
57
+ return undefined
58
+ }
59
+ }
60
+
61
+ const replaceParameters = (input: string|undefined) => {
62
+ if(parameters) {
63
+ let output = input
64
+ for(const parameter of parameters) {
65
+ output = output.replace(parameter.name, parameter.value)
66
+ }
67
+ return output
68
+ } else
69
+ return input
70
+ }
71
+
72
+ for(let command of actions) {
73
+ let source = replaceThis(replaceParameters(command.source))
74
+ let predicate = replaceThis(replaceParameters(command.predicate))
75
+ let target = replaceThis(replaceParameters(command.target))
76
+ let local = command?.local ?? false
77
+
78
+ switch(command.action) {
79
+ case 'addLink':
80
+ await this.add(new Link({source, predicate, target}), local ? 'local' : 'shared')
81
+ break;
82
+ case 'removeLink':
83
+ const linkExpressions = await this.get(new LinkQuery({source, predicate, target}))
84
+ for (const linkExpression of linkExpressions) {
85
+ await this.remove(linkExpression)
86
+ }
87
+ break;
88
+ case 'setSingleTarget':
89
+ await this.setSingleTarget(new Link({source, predicate, target}), local ? 'local' : 'shared')
90
+ break;
91
+ case 'collectionSetter':
92
+ const links = await this.get(new LinkQuery({ source, predicate }))
93
+ await this.removeLinks(links);
94
+ await this.addLinks(parameters.map(p => new Link({source, predicate, target: p.value})), local ? 'local' : 'shared')
95
+ break;
96
+ }
97
+ }
98
+ }
99
+
100
+ /** Unique ID of the perspective */
101
+ get uuid(): string {
102
+ return this.#handle.uuid
103
+ }
104
+
105
+ /** Given name of the perspective */
106
+ get name(): string {
107
+ return this.#handle.name
108
+ }
109
+
110
+ /** If the perspective is shared as a Neighbourhood, this is the Neighbourhood URL */
111
+ get sharedUrl(): string|void {
112
+ return this.#handle.sharedUrl
113
+ }
114
+
115
+ /** If the perspective is shared as a Neighbourhood, this is the Neighbourhood Expression */
116
+ get neighbourhood(): NeighbourhoodExpression|void {
117
+ return this.#handle.neighbourhood
118
+ }
119
+
120
+ /** Returns the state of the perspective **/
121
+ get state(): PerspectiveState {
122
+ return this.#handle.state
123
+ }
124
+
125
+ /** Returns all the links of this perspective that matches the LinkQuery */
126
+ async get(query: LinkQuery): Promise<LinkExpression[]> {
127
+ return await this.#client.queryLinks(this.#handle.uuid, query)
128
+ }
129
+
130
+ /** Runs a Prolog query on the perspective's Prolog engine */
131
+ async infer(query: string): Promise<any> {
132
+ return await this.#client.queryProlog(this.#handle.uuid, query)
133
+ }
134
+
135
+ /** Adds a link to this perspective */
136
+ async add(link: Link, status: LinkStatus = 'shared'): Promise<LinkExpression> {
137
+ return await this.#client.addLink(this.#handle.uuid, link, status)
138
+ }
139
+
140
+ /** Adds multiple links to this perspective **/
141
+ async addLinks(links: Link[], status: LinkStatus = 'shared'): Promise<LinkExpression[]> {
142
+ return await this.#client.addLinks(this.#handle.uuid, links, status)
143
+ }
144
+
145
+ /** Removes multiple links from this perspective **/
146
+ async removeLinks(links: LinkExpressionInput[]): Promise<LinkExpression[]> {
147
+ return await this.#client.removeLinks(this.#handle.uuid, links)
148
+ }
149
+
150
+ /** Adds and removes multiple links from this perspective **/
151
+ async linkMutations(mutations: LinkMutations, status: LinkStatus = 'shared'): Promise<LinkExpressionMutations> {
152
+ return await this.#client.linkMutations(this.#handle.uuid, mutations, status)
153
+ }
154
+
155
+ /** Adds a linkExpression to this perspective */
156
+ async addLinkExpression(link: LinkExpression, status: LinkStatus = 'shared'): Promise<LinkExpression> {
157
+ return await this.#client.addLinkExpression(this.#handle.uuid, link, status)
158
+ }
159
+
160
+ async update(oldLink: LinkExpressionInput, newLink: Link) {
161
+ return await this.#client.updateLink(this.#handle.uuid, oldLink, newLink)
162
+ }
163
+
164
+ async remove(link: LinkExpressionInput) {
165
+ return await this.#client.removeLink(this.#handle.uuid, link)
166
+ }
167
+
168
+ async getExpression(expressionURI: string): Promise<ExpressionRendered> {
169
+ return await this.#client.getExpression(expressionURI)
170
+ }
171
+
172
+ async createExpression(content: any, languageAddress: string): Promise<string> {
173
+ return await this.#client.createExpression(content, languageAddress)
174
+ }
175
+
176
+ /** Adds a link listener
177
+ * @param type Can be 'link-added' or 'link-removed'
178
+ * @param cb Callback function that is called when a link is added to the perspective
179
+ */
180
+ async addListener(type: PerspectiveListenerTypes, cb: LinkCallback) {
181
+ if (type === 'link-added') {
182
+ this.#perspectiveLinkAddedCallbacks.push(cb);
183
+ } else if (type === 'link-removed') {
184
+ this.#perspectiveLinkRemovedCallbacks.push(cb);
185
+ } else if (type === 'link-updated') {
186
+ this.#perspectiveLinkUpdatedCallbacks.push(cb);
187
+ }
188
+ }
189
+
190
+ /** Adds a sync state listener
191
+ * @param cb Callback function that is called when the sync state of the perspective changes
192
+ * @returns A function that can be called to remove the listener
193
+ */
194
+ async addSyncStateChangeListener(cb: SyncStateChangeCallback) {
195
+ this.#perspectiveSyncStateChangeCallbacks.push(cb)
196
+ }
197
+
198
+ /** Removes a previously added link listener
199
+ * @param type Can be 'link-added' or 'link-removed'
200
+ * @param cb Callback function that is called when a link is added to the perspective
201
+ */
202
+ async removeListener(type: PerspectiveListenerTypes, cb: LinkCallback) {
203
+ if (type === 'link-added') {
204
+ const index = this.#perspectiveLinkAddedCallbacks.indexOf(cb);
205
+
206
+ this.#perspectiveLinkAddedCallbacks.splice(index, 1);
207
+ } else if (type === 'link-removed') {
208
+ const index = this.#perspectiveLinkRemovedCallbacks.indexOf(cb);
209
+
210
+ this.#perspectiveLinkRemovedCallbacks.splice(index, 1);
211
+ } else if (type === 'link-updated') {
212
+ const index = this.#perspectiveLinkUpdatedCallbacks.indexOf(cb);
213
+
214
+ this.#perspectiveLinkUpdatedCallbacks.splice(index, 1);
215
+ }
216
+ }
217
+
218
+
219
+ /** Create and return a snapshot of this perspective
220
+ * A snapshot is a rendered Perspectie object that contains all the links of the perspective.
221
+ */
222
+ async snapshot(): Promise<Perspective> {
223
+ return this.#client.snapshotByUUID(this.#handle.uuid)
224
+ }
225
+
226
+ /** Take and load all the links from the given snapshot */
227
+ async loadSnapshot(snapshot: Perspective) {
228
+ //Clean the input data from __typename
229
+ const cleanedSnapshot = JSON.parse(JSON.stringify(snapshot));
230
+ delete cleanedSnapshot.__typename;
231
+ cleanedSnapshot.links.forEach(link => {
232
+ delete link.data.__typename;
233
+ });
234
+
235
+ for(const link of cleanedSnapshot.links) {
236
+ await this.addLinkExpression(link)
237
+ }
238
+ }
239
+
240
+ /** Convenience function to get the target of the first link that matches the given query
241
+ * This makes sense when the query is expected to return only one link
242
+ * and the target of that link is what you are looking for.
243
+ *
244
+ * Works best together with @member setSingelTarget()
245
+ */
246
+ async getSingleTarget(query: LinkQuery): Promise<string|void> {
247
+ delete query.target
248
+ const foundLinks = await this.get(query)
249
+ if(foundLinks.length)
250
+ return foundLinks[0].data.target
251
+ else
252
+ return null
253
+ }
254
+
255
+ /** Convenience function to ensure there is only one link with given source and predicate
256
+ * This function will remove all links with the same source and predicate as the given link,
257
+ * and then add the given link.
258
+ * This ensures there is only one target for the given source and predicate.
259
+ *
260
+ * Works best together with @member getSingleTarget()
261
+ */
262
+ async setSingleTarget(link: Link, status: LinkStatus = 'shared') {
263
+ const query = new LinkQuery({source: link.source, predicate: link.predicate})
264
+ const foundLinks = await this.get(query)
265
+ const removals = [];
266
+ for(const l of foundLinks){
267
+ delete l.__typename
268
+ delete l.data.__typename
269
+ delete l.proof.__typename
270
+ removals.push(l);
271
+ }
272
+ const additions = [link];
273
+
274
+ await this.linkMutations({additions, removals}, status)
275
+ }
276
+
277
+ /** Returns all the Social DNA flows defined in this perspective */
278
+ async sdnaFlows(): Promise<string[]> {
279
+ const allFlows = await this.infer("register_sdna_flow(X, _)")
280
+ return allFlows.map(x => x.X)
281
+ }
282
+
283
+ /** Returns all Social DNA flows that can be started from the given expression */
284
+ async availableFlows(exprAddr: string): Promise<string[]> {
285
+ const availableFlows = await this.infer(`flowable("${exprAddr}", F), register_sdna_flow(X, F)`)
286
+ return availableFlows.map(x => x.X)
287
+ }
288
+
289
+ /** Starts the Social DNA flow @param flowName on the expression @param exprAddr */
290
+ async startFlow(flowName: string, exprAddr: string) {
291
+ let startAction = await this.infer(`start_action(Action, F), register_sdna_flow("${flowName}", F)`)
292
+ // should always return one solution...
293
+ startAction = eval(startAction[0].Action)
294
+ await this.executeAction(startAction, exprAddr, undefined)
295
+ }
296
+
297
+ /** Returns all expressions in the given state of given Social DNA flow */
298
+ async expressionsInFlowState(flowName: string, flowState: number): Promise<string[]> {
299
+ let expressions = await this.infer(`register_sdna_flow("${flowName}", F), flow_state(X, ${flowState}, F)`)
300
+ return expressions.map(r => r.X)
301
+ }
302
+
303
+ /** Returns the given expression's flow state with regard to given Social DNA flow */
304
+ async flowState(flowName: string, exprAddr: string): Promise<number> {
305
+ let state = await this.infer(`register_sdna_flow("${flowName}", F), flow_state("${exprAddr}", X, F)`)
306
+ return state[0].X
307
+ }
308
+
309
+ /** Returns available action names, with regard to Social DNA flow and expression's flow state */
310
+ async flowActions(flowName: string, exprAddr: string): Promise<string[]> {
311
+ let actionNames = await this.infer(`register_sdna_flow("${flowName}", Flow), flow_state("${exprAddr}", State, Flow), action(State, Name, _, _)`)
312
+ return actionNames.map(r => r.Name)
313
+ }
314
+
315
+ /** Runs given Social DNA flow action */
316
+ async runFlowAction(flowName: string, exprAddr: string, actionName: string) {
317
+ let action = await this.infer(`register_sdna_flow("${flowName}", Flow), flow_state("${exprAddr}", State, Flow), action(State, "${actionName}", _, Action)`)
318
+ // should find only one
319
+ action = eval(action[0].Action)
320
+ await this.executeAction(action, exprAddr, undefined)
321
+ }
322
+
323
+ /** Returns the perspective's Social DNA code
324
+ * This will return all SDNA code elements in an array.
325
+ */
326
+ async getSdna(): Promise<string[]> {
327
+ let links = await this.get(new LinkQuery({
328
+ predicate: "ad4m://sdna"
329
+ }))
330
+
331
+ return links.map(link => link.data.target).map(t => Literal.fromUrl(t).get())
332
+ }
333
+
334
+ /** Adds the given Social DNA code to the perspective's SDNA code */
335
+ async addSdna(name: string, sdnaCode: string, type: "subject_class" | "flow" | "custom") {
336
+ let predicate = "ad4m://has_custom_sdna";
337
+
338
+ if (type === 'subject_class') predicate = "ad4m://has_subject_class"
339
+ else if (type === 'flow') predicate = "ad4m://has_flow"
340
+
341
+ const literalName = Literal.from(name).toUrl();
342
+
343
+ const links = await this.get(new LinkQuery({
344
+ source: "ad4m://self",
345
+ predicate,
346
+ target: literalName
347
+ }))
348
+
349
+ const sdnaLinks: any[] = []
350
+
351
+ if (links.length === 0) {
352
+ sdnaLinks.push(new Link({
353
+ source: "ad4m://self",
354
+ predicate,
355
+ target: literalName
356
+ }));
357
+ }
358
+
359
+ sdnaLinks.push(new Link({
360
+ source: literalName,
361
+ predicate: "ad4m://sdna",
362
+ target: Literal.from(sdnaCode).toUrl()
363
+ }))
364
+
365
+ await this.addLinks(sdnaLinks);
366
+ }
367
+
368
+ /** Returns all the Subject classes defined in this perspectives SDNA */
369
+ async subjectClasses(): Promise<string[]> {
370
+ try {
371
+ return (await this.infer("subject_class(X, _)")).map(x => x.X)
372
+ }catch(e) {
373
+ return []
374
+ }
375
+ }
376
+
377
+ async stringOrTemplateObjectToSubjectClass<T>(subjectClass: T): Promise<string> {
378
+ if(typeof subjectClass === "string")
379
+ return subjectClass
380
+ else {
381
+ let subjectClasses = await this.subjectClassesByTemplate(subjectClass as object)
382
+ if(subjectClasses[0]) {
383
+ return subjectClasses[0]
384
+ } else {
385
+ //@ts-ignore
386
+ return subjectClass.className
387
+ }
388
+ }
389
+ }
390
+
391
+ /** Creates a new subject instance by running its (SDNA defined) constructor,
392
+ * which means adding links around the given expression address so that it
393
+ * conforms to the given subject class.
394
+ *
395
+ * @param subjectClass Either a string with the name of the subject class, or an object
396
+ * with the properties of the subject class. In the latter case, the first subject class
397
+ * that matches the given properties will be used.
398
+ * @param exprAddr The address of the expression to be turned into a subject instance
399
+ */
400
+ async createSubject<T>(subjectClass: T, exprAddr: string): Promise<T> {
401
+ let className = await this.stringOrTemplateObjectToSubjectClass(subjectClass)
402
+ let result = await this.infer(`subject_class("${className}", C), constructor(C, Actions)`)
403
+ if(!result.length) {
404
+ throw "No constructor found for given subject class: " + className
405
+ }
406
+
407
+ let actions = result.map(x => eval(x.Actions))
408
+ await this.executeAction(actions[0], exprAddr, undefined)
409
+ return this.getSubjectProxy(exprAddr, subjectClass)
410
+ }
411
+
412
+ /** Removes a subject instance by running its (SDNA defined) destructor,
413
+ * which means removing links around the given expression address
414
+ *
415
+ * @param subjectClass Either a string with the name of the subject class, or an object
416
+ * with the properties of the subject class. In the latter case, the first subject class
417
+ * that matches the given properties will be used.
418
+ * @param exprAddr The address of the expression to be turned into a subject instance
419
+ */
420
+ async removeSubject<T>(subjectClass: T, exprAddr: string) {
421
+ let className = await this.stringOrTemplateObjectToSubjectClass(subjectClass)
422
+ let result = await this.infer(`subject_class("${className}", C), destructor(C, Actions)`)
423
+ if(!result.length) {
424
+ throw "No constructor found for given subject class: " + className
425
+ }
426
+
427
+ let actions = result.map(x => eval(x.Actions))
428
+ await this.executeAction(actions[0], exprAddr, undefined)
429
+ }
430
+
431
+ /** Checks if the given expression is a subject instance of the given subject class
432
+ * @param expression The expression to be checked
433
+ * @param subjectClass Either a string with the name of the subject class, or an object
434
+ * with the properties of the subject class. In the latter case, the first subject class
435
+ * that matches the given properties will be used.
436
+ */
437
+ async isSubjectInstance<T>(expression: string, subjectClass: T): Promise<boolean> {
438
+ let className = await this.stringOrTemplateObjectToSubjectClass(subjectClass)
439
+ return await this.infer(`subject_class("${className}", C), instance(C, "${expression}")`)
440
+ }
441
+
442
+
443
+ /** For an existing subject instance (existing in the perspective's links)
444
+ * this function returns a proxy object that can be used to access the subject's
445
+ * properties and methods.
446
+ *
447
+ * @param base URI of the subject's root expression
448
+ * @param subjectClass Either a string with the name of the subject class, or an object
449
+ * with the properties of the subject class. In the latter case, the first subject class
450
+ * that matches the given properties will be used.
451
+ */
452
+ async getSubjectProxy<T>(base: string, subjectClass: T): Promise<T> {
453
+ if(!await this.isSubjectInstance(base, subjectClass)) {
454
+ throw `Expression ${base} is not a subject instance of given class: ${JSON.stringify(subjectClass)}`
455
+ }
456
+ let className = await this.stringOrTemplateObjectToSubjectClass(subjectClass)
457
+ let subject = new Subject(this, base, className)
458
+ await subject.init()
459
+ return subject as unknown as T
460
+ }
461
+
462
+ /** Returns all subject instances of the given subject class as proxy objects.
463
+ * @param subjectClass Either a string with the name of the subject class, or an object
464
+ * with the properties of the subject class. In the latter case, all subject classes
465
+ * that match the given properties will be used.
466
+ */
467
+ async getAllSubjectInstances<T>(subjectClass: T): Promise<T[]> {
468
+ let classes = []
469
+ if(typeof subjectClass === "string") {
470
+ classes = [subjectClass]
471
+ } else {
472
+ classes = await this.subjectClassesByTemplate(subjectClass as object)
473
+ }
474
+
475
+ let instances = []
476
+ for(let className of classes) {
477
+ let instanceBaseExpressions = await this.infer(`subject_class("${className}", C), instance(C, X)`)
478
+ let newInstances = await Promise.all(instanceBaseExpressions.map(async x => await this.getSubjectProxy(x.X, className) as unknown as T))
479
+ instances = instances.concat(newInstances)
480
+ }
481
+ return instances
482
+ }
483
+
484
+ async getAllSubjectProxies<T>(subjectClass: T): Promise<T[]> {
485
+ let classes = []
486
+ if(typeof subjectClass === "string") {
487
+ classes = [subjectClass]
488
+ } else {
489
+ classes = await this.subjectClassesByTemplate(subjectClass as object)
490
+ }
491
+
492
+ let instances = []
493
+ for(let className of classes) {
494
+ instances = await this.infer(`subject_class("${className}", C), instance(C, X)`)
495
+ }
496
+ return instances
497
+ }
498
+
499
+
500
+ /** Returns all subject classes that match the given template object.
501
+ * This function looks at the properties of the template object and
502
+ * its setters and collections to create a Prolog query that finds
503
+ * all subject classes that would be converted to a proxy object
504
+ * with exactly the same properties and collections.
505
+ *
506
+ * Since there could be multiple subject classes that match the given
507
+ * criteria, this function returns a list of class names.
508
+ *
509
+ * @param obj The template object
510
+ */
511
+ async subjectClassesByTemplate(obj: object): Promise<string[]> {
512
+ // Collect all string properties of the object in a list
513
+ let properties = []
514
+
515
+ // Collect all collections of the object in a list
516
+ let collections = []
517
+
518
+ // Collect all string properties of the object in a list
519
+ if(Object.getPrototypeOf(obj).__properties) {
520
+ Object.keys(Object.getPrototypeOf(obj).__properties).forEach(p => properties.push(p))
521
+ } else {
522
+ properties.push(...Object.keys(obj).filter(key => !Array.isArray(obj[key])))
523
+ }
524
+
525
+ // Collect all collections of the object in a list
526
+ if (Object.getPrototypeOf(obj).__collections) {
527
+ Object.keys(Object.getPrototypeOf(obj).__collections).filter(key => key !== 'isSubjectInstance').forEach(c => !collections.includes(c) ?? collections.push(c))
528
+ } else {
529
+ collections.push(...Object.keys(obj).filter(key => Array.isArray(obj[key])).filter(key => key !== 'isSubjectInstance'))
530
+ }
531
+
532
+ // Collect all set functions of the object in a list
533
+ let setFunctions = Object.getOwnPropertyNames(obj).filter(key => (typeof obj[key] === "function") && key.startsWith("set") && !key.startsWith("setCollection"))
534
+ // Add all set functions of the object's prototype to that list
535
+ setFunctions = setFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(key => (typeof obj[key] === "function") && key.startsWith("set") && !key.startsWith("setCollection")))
536
+
537
+ // Collect all add functions of the object in a list
538
+ let addFunctions = Object.getOwnPropertyNames(obj).filter(key => (typeof obj[key] === "function") && key.startsWith("add"))
539
+ // Add all add functions of the object's prototype to that list
540
+ addFunctions = addFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(key => (typeof obj[key] === "function") && key.startsWith("add")))
541
+
542
+ // Collect all remove functions of the object in a list
543
+ let removeFunctions = Object.getOwnPropertyNames(obj).filter(key => (typeof obj[key] === "function") && key.startsWith("remove"))
544
+ // Add all remove functions of the object's prototype to that list
545
+ removeFunctions = removeFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(key => (typeof obj[key] === "function") && key.startsWith("remove")))
546
+
547
+ // Collect all add functions of the object in a list
548
+ let setCollectionFunctions = Object.getOwnPropertyNames(obj).filter(key => (typeof obj[key] === "function") && key.startsWith("setCollection"))
549
+ // Add all add functions of the object's prototype to that list
550
+ setCollectionFunctions = setCollectionFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(key => (typeof obj[key] === "function") && key.startsWith("setCollection")))
551
+
552
+ // Construct query to find all subject classes that have the given properties and collections
553
+ let query = `subject_class(Class, C)`
554
+
555
+ for(let property of properties) {
556
+ query += `, property(C, "${property}")`
557
+ }
558
+ for(let collection of collections) {
559
+ query += `, collection(C, "${collection}")`
560
+ }
561
+
562
+ for(let setFunction of setFunctions) {
563
+ // e.g. "setState" -> "state"
564
+ let property = setFunction.substring(3)
565
+ property = property.charAt(0).toLowerCase() + property.slice(1)
566
+ query += `, property_setter(C, "${property}", _)`
567
+ }
568
+ for(let addFunction of addFunctions) {
569
+ query += `, collection_adder(C, "${collectionAdderToName(addFunction)}", _)`
570
+ }
571
+
572
+ for(let removeFunction of removeFunctions) {
573
+ query += `, collection_remover(C, "${collectionRemoverToName(removeFunction)}", _)`
574
+ }
575
+
576
+ for(let setCollectionFunction of setCollectionFunctions) {
577
+ query += `, collection_setter(C, "${collectionSetterToName(setCollectionFunction)}", _)`
578
+ }
579
+
580
+
581
+ query += "."
582
+ let result = await this.infer(query)
583
+ if(!result) {
584
+ return []
585
+ } else {
586
+ return result.map(x => x.Class)
587
+ }
588
+ }
589
+
590
+ /** Takes a JS class (its constructor) and assumes that it was decorated by
591
+ * the @subjectClass etc. decorators. It then tests if there is a subject class
592
+ * already present in the perspective's SDNA that matches the given class.
593
+ * If there is no such class, it gets the JS class's SDNA by calling its
594
+ * static generateSDNA() function and adds it to the perspective's SDNA.
595
+ */
596
+ async ensureSDNASubjectClass(jsClass: any): Promise<void> {
597
+ const subjectClass = await this.subjectClassesByTemplate(new jsClass)
598
+ if(subjectClass.length > 0) {
599
+ return
600
+ }
601
+
602
+ const { name, sdna } = jsClass.generateSDNA();
603
+
604
+ await this.addSdna(name, sdna, 'subject_class');
605
+ }
606
+
607
+ getNeighbourhoodProxy(): NeighbourhoodProxy {
608
+ return this.#client.getNeighbourhoodProxy(this.#handle.uuid)
609
+ }
610
+
611
+ }