@coasys/ad4m 0.13.0-test-1 → 0.13.0-test-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 (94) hide show
  1. package/lib/index.cjs +1392 -777
  2. package/lib/index.js +1376 -775
  3. package/lib/src/Literal.js +6 -5
  4. package/lib/src/agent/AgentClient.d.ts +5 -1
  5. package/lib/src/agent/AgentClient.js +48 -2
  6. package/lib/src/expression/ExpressionRef.js +2 -2
  7. package/lib/src/language/Language.d.ts +41 -3
  8. package/lib/src/model/Ad4mModel.d.ts +28 -28
  9. package/lib/src/model/Ad4mModel.js +129 -101
  10. package/lib/src/model/Ad4mModel.test.js +1543 -535
  11. package/lib/src/model/ModelQueryBuilder.d.ts +48 -34
  12. package/lib/src/model/ModelQueryBuilder.js +163 -78
  13. package/lib/src/model/Subject.js +6 -6
  14. package/lib/src/model/decorators.d.ts +14 -8
  15. package/lib/src/model/decorators.js +41 -14
  16. package/lib/src/model/hydration-batch.d.ts +34 -0
  17. package/lib/src/model/hydration-batch.js +147 -0
  18. package/lib/src/model/hydration.d.ts +3 -3
  19. package/lib/src/model/hydration.js +106 -36
  20. package/lib/src/model/index.d.ts +4 -1
  21. package/lib/src/model/index.js +4 -1
  22. package/lib/src/model/json-schema.js +2 -2
  23. package/lib/src/model/query-cache.d.ts +30 -0
  24. package/lib/src/model/query-cache.js +66 -0
  25. package/lib/src/model/query-cache.test.d.ts +1 -0
  26. package/lib/src/model/query-cache.test.js +43 -0
  27. package/lib/src/model/query-common.d.ts +1 -1
  28. package/lib/src/model/query-common.js +1 -1
  29. package/lib/src/model/query-sparql-batch.d.ts +17 -0
  30. package/lib/src/model/query-sparql-batch.js +260 -0
  31. package/lib/src/model/query-sparql.d.ts +47 -0
  32. package/lib/src/model/query-sparql.js +336 -0
  33. package/lib/src/model/query-utils.d.ts +45 -0
  34. package/lib/src/model/query-utils.js +140 -0
  35. package/lib/src/model/relation-filtering.test.js +15 -15
  36. package/lib/src/model/sdna.js +1 -1
  37. package/lib/src/model/shacl-gen.js +42 -18
  38. package/lib/src/model/subscription-pool.d.ts +39 -0
  39. package/lib/src/model/subscription-pool.js +119 -0
  40. package/lib/src/model/types.d.ts +3 -3
  41. package/lib/src/model/types.js +1 -1
  42. package/lib/src/perspectives/PerspectiveClient.d.ts +1 -17
  43. package/lib/src/perspectives/PerspectiveClient.js +5 -57
  44. package/lib/src/perspectives/PerspectiveProxy.d.ts +51 -30
  45. package/lib/src/perspectives/PerspectiveProxy.js +224 -177
  46. package/lib/src/perspectives/PerspectiveResolver.d.ts +0 -1
  47. package/lib/src/perspectives/PerspectiveResolver.js +0 -11
  48. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +3 -3
  49. package/lib/src/perspectives/WakerSubscriptionManager.js +7 -8
  50. package/lib/src/runtime/RuntimeResolver.d.ts +11 -0
  51. package/lib/src/runtime/RuntimeResolver.js +56 -0
  52. package/lib/src/schema.gql +11 -1
  53. package/lib/src/shacl/SHACLFlow.d.ts +1 -1
  54. package/lib/src/shacl/SHACLFlow.js +9 -9
  55. package/lib/src/shacl/SHACLShape.d.ts +1 -1
  56. package/lib/src/shacl/SHACLShape.js +38 -38
  57. package/lib/src/typeDefs.js +11 -1
  58. package/lib/src/utils.d.ts +6 -6
  59. package/lib/src/utils.js +6 -6
  60. package/package.json +1 -1
  61. package/src/Literal.test.ts +10 -5
  62. package/src/Literal.ts +6 -5
  63. package/src/agent/AgentClient.ts +53 -1
  64. package/src/expression/ExpressionRef.ts +2 -2
  65. package/src/language/Language.ts +48 -3
  66. package/src/model/Ad4mModel.test.ts +1515 -565
  67. package/src/model/Ad4mModel.ts +142 -102
  68. package/src/model/ModelQueryBuilder.ts +185 -86
  69. package/src/model/Subject.ts +6 -6
  70. package/src/model/decorators.ts +51 -22
  71. package/src/model/hydration-batch.ts +205 -0
  72. package/src/model/hydration.ts +102 -39
  73. package/src/model/index.ts +4 -1
  74. package/src/model/json-schema.ts +2 -2
  75. package/src/model/query-cache.test.ts +54 -0
  76. package/src/model/query-cache.ts +79 -0
  77. package/src/model/query-common.ts +1 -1
  78. package/src/model/query-sparql-batch.ts +301 -0
  79. package/src/model/query-sparql.ts +363 -0
  80. package/src/model/{surreal-utils.ts → query-utils.ts} +40 -27
  81. package/src/model/relation-filtering.test.ts +15 -15
  82. package/src/model/sdna.ts +1 -1
  83. package/src/model/shacl-gen.ts +42 -17
  84. package/src/model/subscription-pool.ts +163 -0
  85. package/src/model/types.ts +3 -3
  86. package/src/perspectives/PerspectiveClient.ts +5 -61
  87. package/src/perspectives/PerspectiveProxy.ts +226 -181
  88. package/src/perspectives/PerspectiveResolver.ts +0 -8
  89. package/src/perspectives/WakerSubscriptionManager.ts +8 -9
  90. package/src/runtime/RuntimeResolver.ts +43 -0
  91. package/src/shacl/SHACLFlow.ts +9 -9
  92. package/src/shacl/SHACLShape.ts +39 -39
  93. package/src/utils.ts +6 -6
  94. package/src/model/query-surreal.ts +0 -280
@@ -1,25 +1,25 @@
1
1
  export declare function formatList(list: any): any;
2
2
  export declare function capSentence(cap: any): string;
3
3
  /**
4
- * Escapes a string value for safe use in SurrealQL queries.
4
+ * Escapes a string value for safe use in query strings.
5
5
  *
6
6
  * @description
7
7
  * Prevents SQL injection by properly escaping special characters in string values
8
- * that will be interpolated into SurrealQL queries. This handles the most common
8
+ * that will be interpolated into query strings. This handles the most common
9
9
  * special characters that could break SQL queries or enable injection attacks.
10
10
  *
11
11
  * Single quotes, backslashes, and other special characters are escaped using
12
- * backslash notation, which is the standard escaping mechanism for SurrealQL.
12
+ * backslash notation, which is the standard escaping mechanism for query.
13
13
  *
14
14
  * @param value - The string value to escape
15
- * @returns The escaped string safe for SurrealQL interpolation (without surrounding quotes)
15
+ * @returns The escaped string safe for query interpolation (without surrounding quotes)
16
16
  *
17
17
  * @example
18
18
  * ```typescript
19
19
  * const userInput = "user's input with 'quotes'";
20
- * const escaped = escapeSurrealString(userInput);
20
+ * const escaped = escapeQueryString(userInput);
21
21
  * const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
22
22
  * // Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''
23
23
  * ```
24
24
  */
25
- export declare function escapeSurrealString(value: string): string;
25
+ export declare function escapeQueryString(value: string): string;
package/lib/src/utils.js CHANGED
@@ -20,28 +20,28 @@ export function capSentence(cap) {
20
20
  return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
21
21
  }
22
22
  /**
23
- * Escapes a string value for safe use in SurrealQL queries.
23
+ * Escapes a string value for safe use in query strings.
24
24
  *
25
25
  * @description
26
26
  * Prevents SQL injection by properly escaping special characters in string values
27
- * that will be interpolated into SurrealQL queries. This handles the most common
27
+ * that will be interpolated into query strings. This handles the most common
28
28
  * special characters that could break SQL queries or enable injection attacks.
29
29
  *
30
30
  * Single quotes, backslashes, and other special characters are escaped using
31
- * backslash notation, which is the standard escaping mechanism for SurrealQL.
31
+ * backslash notation, which is the standard escaping mechanism for query.
32
32
  *
33
33
  * @param value - The string value to escape
34
- * @returns The escaped string safe for SurrealQL interpolation (without surrounding quotes)
34
+ * @returns The escaped string safe for query interpolation (without surrounding quotes)
35
35
  *
36
36
  * @example
37
37
  * ```typescript
38
38
  * const userInput = "user's input with 'quotes'";
39
- * const escaped = escapeSurrealString(userInput);
39
+ * const escaped = escapeQueryString(userInput);
40
40
  * const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
41
41
  * // Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''
42
42
  * ```
43
43
  */
44
- export function escapeSurrealString(value) {
44
+ export function escapeQueryString(value) {
45
45
  return value
46
46
  .replace(/\\/g, '\\\\') // Backslash -> \\
47
47
  .replace(/'/g, "\\'") // Single quote -> \'
package/package.json CHANGED
@@ -69,5 +69,5 @@
69
69
  "graphql@15.7.2": "patches/graphql@15.7.2.patch"
70
70
  }
71
71
  },
72
- "version": "0.13.0-test-1"
72
+ "version": "0.13.0-test-2"
73
73
  }
@@ -3,29 +3,34 @@ import { Literal } from './Literal'
3
3
  describe("Literal", () => {
4
4
  it("can handle strings", () => {
5
5
  const testString = "test string"
6
- const testUrl = "literal://string:test%20string"
6
+ const testUrl = "literal:string:test%20string"
7
7
  expect(Literal.from(testString).toUrl()).toBe(testUrl)
8
8
  expect(Literal.fromUrl(testUrl).get()).toBe(testString)
9
9
  })
10
10
 
11
11
  it("can handle numbers", () => {
12
12
  const testNumber = 3.1415
13
- const testUrl = "literal://number:3.1415"
13
+ const testUrl = "literal:number:3.1415"
14
14
  expect(Literal.from(testNumber).toUrl()).toBe(testUrl)
15
15
  expect(Literal.fromUrl(testUrl).get()).toBe(testNumber)
16
16
  })
17
17
 
18
18
  it("can handle objects", () => {
19
19
  const testObject = {testNumber: "1337", testString: "test"}
20
- const testUrl = "literal://json:%7B%22testNumber%22%3A%221337%22%2C%22testString%22%3A%22test%22%7D"
20
+ const testUrl = "literal:json:%7B%22testNumber%22%3A%221337%22%2C%22testString%22%3A%22test%22%7D"
21
21
  expect(Literal.from(testObject).toUrl()).toBe(testUrl)
22
22
  expect(Literal.fromUrl(testUrl).get()).toStrictEqual(testObject)
23
23
  })
24
24
 
25
25
  it("can handle special characters", () => {
26
26
  const testString = "message(X) :- triple('ad4m://self', _, X)."
27
- const testUrl = "literal://string:message%28X%29%20%3A-%20triple%28%27ad4m%3A%2F%2Fself%27%2C%20_%2C%20X%29."
27
+ const testUrl = "literal:string:message%28X%29%20%3A-%20triple%28%27ad4m%3A%2F%2Fself%27%2C%20_%2C%20X%29."
28
28
  expect(Literal.from(testString).toUrl()).toBe(testUrl)
29
29
  expect(Literal.fromUrl(testUrl).get()).toBe(testString)
30
30
  })
31
- })
31
+
32
+ it("rejects legacy literal:// URLs", () => {
33
+ expect(() => Literal.fromUrl("literal://string:hello")).toThrow("literal:// format is no longer supported")
34
+ expect(() => Literal.fromUrl("literal://number:42")).toThrow("literal:// format is no longer supported")
35
+ })
36
+ })
package/src/Literal.ts CHANGED
@@ -11,8 +11,10 @@ export class Literal {
11
11
  #url?: string
12
12
 
13
13
  public static fromUrl(url: string) {
14
- if(!url || !url.startsWith("literal://"))
14
+ if(!url || !url.startsWith("literal:"))
15
15
  throw new Error("Can't create Literal from non-literal URL")
16
+ if(url.startsWith("literal://"))
17
+ throw new Error("literal:// format is no longer supported. Use literal: instead.")
16
18
  const l = new Literal()
17
19
  l.#url = url
18
20
  return l
@@ -46,7 +48,7 @@ export class Literal {
46
48
  break;
47
49
  }
48
50
 
49
- return `literal://${encoded}`
51
+ return `literal:${encoded}`
50
52
  }
51
53
 
52
54
  get(): any {
@@ -56,11 +58,10 @@ export class Literal {
56
58
  if(!this.#url)
57
59
  throw new Error("Can't render empty Literal")
58
60
 
59
- if(!this.#url.startsWith("literal://"))
61
+ if(!this.#url.startsWith("literal:"))
60
62
  throw new Error("Can't render Literal from non-literal URL")
61
63
 
62
- // get rid of "literal://"
63
- const body = this.#url.substring(10)
64
+ const body = this.#url.substring(8)
64
65
 
65
66
 
66
67
  if(body.startsWith("string:")) {
@@ -10,7 +10,7 @@ import {
10
10
  EntanglementProofInput,
11
11
  UserCreationResult,
12
12
  } from "./Agent";
13
- import { HostingUserInfo, PaymentRequestResult } from "../runtime/RuntimeResolver";
13
+ import { HostingUserInfo, PaymentRequestResult, ComputeLogEntry } from "../runtime/RuntimeResolver";
14
14
  import { AgentStatus } from "./AgentStatus";
15
15
  import { LinkMutations } from "../links/Links";
16
16
  import { PerspectiveClient } from "../perspectives/PerspectiveClient";
@@ -83,6 +83,7 @@ export type AgentUpdatedCallback = (agent: Agent) => null;
83
83
  export type AgentStatusChangedCallback = (agent: Agent) => null;
84
84
  export type AgentAppsUpdatedCallback = () => null;
85
85
  export type HostingUserInfoChangedCallback = (info: HostingUserInfo) => void;
86
+ export type ComputeLogUpdatedCallback = (entry: ComputeLogEntry) => void;
86
87
  /**
87
88
  * Provides access to all functions regarding the local agent,
88
89
  * such as generating, locking, unlocking, importing the DID keystore,
@@ -94,6 +95,7 @@ export class AgentClient {
94
95
  #updatedCallbacks: AgentUpdatedCallback[];
95
96
  #agentStatusChangedCallbacks: AgentStatusChangedCallback[];
96
97
  #hostingUserInfoChangedCallbacks: HostingUserInfoChangedCallback[];
98
+ #computeLogUpdatedCallbacks: ComputeLogUpdatedCallback[];
97
99
 
98
100
  constructor(client: ApolloClient<any>, subscribe: boolean = true) {
99
101
  this.#apolloClient = client;
@@ -101,6 +103,7 @@ export class AgentClient {
101
103
  this.#agentStatusChangedCallbacks = [];
102
104
  this.#appsChangedCallback = [];
103
105
  this.#hostingUserInfoChangedCallbacks = [];
106
+ this.#computeLogUpdatedCallbacks = [];
104
107
 
105
108
  if (subscribe) {
106
109
  this.subscribeAgentUpdated();
@@ -450,6 +453,34 @@ export class AgentClient {
450
453
  });
451
454
  }
452
455
 
456
+ addComputeLogUpdatedListener(listener: ComputeLogUpdatedCallback) {
457
+ this.#computeLogUpdatedCallbacks.push(listener);
458
+ }
459
+
460
+ subscribeComputeLogUpdated() {
461
+ this.#apolloClient
462
+ .subscribe({
463
+ query: gql`subscription {
464
+ runtimeComputeLogUpdated {
465
+ id
466
+ userEmail
467
+ timestamp
468
+ operation
469
+ summary
470
+ cost
471
+ creditsAfter
472
+ }
473
+ }`,
474
+ })
475
+ .subscribe({
476
+ next: (result) => {
477
+ const entry = result.data.runtimeComputeLogUpdated;
478
+ this.#computeLogUpdatedCallbacks.forEach((cb) => cb(entry));
479
+ },
480
+ error: (e) => console.error(e),
481
+ });
482
+ }
483
+
453
484
  async requestCapability(authInfo: AuthInfoInput): Promise<string> {
454
485
  const { agentRequestCapability } = unwrapApolloResult(
455
486
  await this.#apolloClient.mutate({
@@ -636,6 +667,27 @@ export class AgentClient {
636
667
  return runtimeHostingUserInfo;
637
668
  }
638
669
 
670
+ async computeLog(since?: string, limit?: number, userEmail?: string): Promise<ComputeLogEntry[]> {
671
+ const { runtimeComputeLog } = unwrapApolloResult(
672
+ await this.#apolloClient.query({
673
+ query: gql`query runtimeComputeLog($since: String, $limit: Int, $userEmail: String) {
674
+ runtimeComputeLog(since: $since, limit: $limit, userEmail: $userEmail) {
675
+ id
676
+ userEmail
677
+ timestamp
678
+ operation
679
+ summary
680
+ cost
681
+ creditsAfter
682
+ }
683
+ }`,
684
+ variables: { since, limit, userEmail },
685
+ fetchPolicy: 'network-only',
686
+ })
687
+ );
688
+ return runtimeComputeLog;
689
+ }
690
+
639
691
  async setHotWalletAddress(address: string): Promise<boolean> {
640
692
  const { runtimeSetHotWalletAddress } = unwrapApolloResult(
641
693
  await this.#apolloClient.mutate({
@@ -27,11 +27,11 @@ export function exprRef2String(ref: ExpressionRef): string {
27
27
  }
28
28
 
29
29
  export function parseExprUrl(url: string): ExpressionRef {
30
- if(url.startsWith("literal://")) {
30
+ if(url.startsWith("literal:")) {
31
31
  const languageRef = new LanguageRef()
32
32
  languageRef.address = 'literal'
33
33
  languageRef.name = 'literal'
34
- const content = url.substring(10)
34
+ const content = url.substring(8)
35
35
  return new ExpressionRef(languageRef, content)
36
36
  }
37
37
 
@@ -5,6 +5,7 @@ import { Perspective, PerspectiveExpression } from '../perspectives/Perspective'
5
5
  import { PerspectiveDiff } from '../perspectives/PerspectiveDiff';
6
6
  import { InputType, Field, ObjectType } from "type-graphql";
7
7
  import { PerspectiveState } from '../perspectives/PerspectiveHandle';
8
+ import { LinkQuery } from '../perspectives/LinkQuery';
8
9
 
9
10
  /** Interface of AD4M Languages
10
11
  *
@@ -41,8 +42,14 @@ export interface Language {
41
42
  /** Interface for getting UI/web components for rendering Expressions of this Language */
42
43
  readonly expressionUI?: ExpressionUI;
43
44
 
45
+ // TODO: Rename linksAdapter to perspectiveSyncAdapter needs a lot of changes elsewhere...
44
46
  /** Interface of LinkLanguages for the core implementation of Neighbourhoods */
45
- readonly linksAdapter?: LinkSyncAdapter;
47
+ readonly perspectiveSyncAdapter?: PerspectiveSyncAdapter;
48
+
49
+ /** Interface for Languages that implement a query return a Perspective (snapshot)
50
+ * Used for back-links and wrapping of APIs that implement queries.
51
+ */
52
+ readonly pespectiveQueryAdapter?: PerspectiveQueryAdapter;
46
53
 
47
54
  /** Additional Interface of LinkLanguages that support telepresence features,
48
55
  * that is:
@@ -156,11 +163,11 @@ export type SyncStateChangeObserver = (state: PerspectiveState)=>void;
156
163
  * The assumption is that every version of the shared Perspective
157
164
  * is labeled with a unique revision string.
158
165
  * Changes are committed and retrieved through diffs.
159
- * Think of a LinkSyncAdapter as a git branch to which agents commit
166
+ * Think of a PerspectiveSyncAdapter as a git branch to which agents commit
160
167
  * their changes to and pull diffs from their current revision
161
168
  * to the latest one.
162
169
  */
163
- export interface LinkSyncAdapter {
170
+ export interface PerspectiveSyncAdapter {
164
171
  writable(): boolean;
165
172
  public(): boolean;
166
173
  others(): Promise<DID[]>;
@@ -276,3 +283,41 @@ export interface TelepresenceAdapter {
276
283
  sendBroadcast(payload: PerspectiveExpression): Promise<object>;
277
284
  registerSignalCallback(callback: TelepresenceSignalCallback): Promise<void>;
278
285
  }
286
+
287
+
288
+ /** Interface for Languages that implement queries returning links, i.e. a Perspective (-snapshot)
289
+ * Main differentiation between these Languages and LinkLanguages is that this enables
290
+ * access to other shared perspectives without forcing a full-sync.
291
+ *
292
+ * All PerspectiveQuery Languages are supposed to implement `linkQuery` which is a simple graph query
293
+ * specifying non or all of source, predicate, target of the links we want to get.
294
+ * This is enough to implement simple back-links.
295
+ *
296
+ * Prolog queries are optional since this requires a Prolog engine to be available.
297
+ *
298
+ */
299
+ export interface PerspectiveQueryAdapter {
300
+ /** Same semantic as PerspectiveProxy.get(LinkQuery) */
301
+ linkQuery(query: LinkQuery): Promise<Perspective>;
302
+
303
+ /** Tells ADAM if Prolog queries are implemented by this Language.
304
+ * If not, prologQuery won't be used, instead in some circumstances,
305
+ * linkQuery() might be called with an all-query, followed by using
306
+ * ADAM's internal Prolog engine on the result.
307
+ */
308
+ supportsPrologQueries(): boolean;
309
+
310
+ /** Same semantic as PerspectiveProxy.infer, will return plain Prolog results */
311
+ infer(prologQuery: string): Promise<any>
312
+
313
+ /** Specify which links shall be returned through Prolog.
314
+ * Assumes unbound variables in query that describe a LinkExpression:
315
+ * - Source
316
+ * - Predicate
317
+ * - Target
318
+ * - Author
319
+ * - Timestamp
320
+ * Will construct a Perspective where each link is a solution to the query.
321
+ */
322
+ prologQuery(query: string): Promise<Perspective>;
323
+ }