@coasys/ad4m 0.13.0-test-1 → 0.13.0-test-3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/lib/index.cjs +2377 -849
  2. package/lib/index.js +2354 -846
  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/index.d.ts +0 -1
  8. package/lib/src/index.js +0 -1
  9. package/lib/src/language/Language.d.ts +26 -176
  10. package/lib/src/language/Language.js +28 -2
  11. package/lib/src/model/Ad4mModel.d.ts +52 -28
  12. package/lib/src/model/Ad4mModel.js +255 -118
  13. package/lib/src/model/Ad4mModel.test.js +1727 -537
  14. package/lib/src/model/ModelQueryBuilder.d.ts +67 -34
  15. package/lib/src/model/ModelQueryBuilder.js +208 -79
  16. package/lib/src/model/Subject.js +6 -6
  17. package/lib/src/model/decorators.d.ts +14 -8
  18. package/lib/src/model/decorators.js +41 -14
  19. package/lib/src/model/hydration-batch.d.ts +34 -0
  20. package/lib/src/model/hydration-batch.js +147 -0
  21. package/lib/src/model/hydration-batching.test.d.ts +7 -0
  22. package/lib/src/model/hydration-batching.test.js +456 -0
  23. package/lib/src/model/hydration.d.ts +4 -3
  24. package/lib/src/model/hydration.js +365 -86
  25. package/lib/src/model/index.d.ts +4 -1
  26. package/lib/src/model/index.js +4 -1
  27. package/lib/src/model/json-schema.js +2 -2
  28. package/lib/src/model/query-cache.d.ts +30 -0
  29. package/lib/src/model/query-cache.js +66 -0
  30. package/lib/src/model/query-cache.test.d.ts +1 -0
  31. package/lib/src/model/query-cache.test.js +43 -0
  32. package/lib/src/model/query-common.d.ts +1 -1
  33. package/lib/src/model/query-common.js +1 -1
  34. package/lib/src/model/query-sparql-batch.d.ts +17 -0
  35. package/lib/src/model/query-sparql-batch.js +260 -0
  36. package/lib/src/model/query-sparql.d.ts +124 -0
  37. package/lib/src/model/query-sparql.js +767 -0
  38. package/lib/src/model/query-sparql.test.d.ts +1 -0
  39. package/lib/src/model/query-sparql.test.js +495 -0
  40. package/lib/src/model/{surreal-utils.d.ts → query-utils.d.ts} +12 -9
  41. package/lib/src/model/{surreal-utils.js → query-utils.js} +43 -27
  42. package/lib/src/model/relation-filtering.test.js +15 -15
  43. package/lib/src/model/sdna.js +1 -1
  44. package/lib/src/model/shacl-gen.js +42 -18
  45. package/lib/src/model/subscription-delta.test.d.ts +24 -0
  46. package/lib/src/model/subscription-delta.test.js +180 -0
  47. package/lib/src/model/subscription-pool.d.ts +39 -0
  48. package/lib/src/model/subscription-pool.js +165 -0
  49. package/lib/src/model/types.d.ts +52 -4
  50. package/lib/src/model/types.js +1 -1
  51. package/lib/src/perspectives/PerspectiveClient.d.ts +3 -17
  52. package/lib/src/perspectives/PerspectiveClient.js +42 -66
  53. package/lib/src/perspectives/PerspectiveClient.test.d.ts +1 -0
  54. package/lib/src/perspectives/PerspectiveClient.test.js +169 -0
  55. package/lib/src/perspectives/PerspectiveProxy.d.ts +54 -30
  56. package/lib/src/perspectives/PerspectiveProxy.js +239 -177
  57. package/lib/src/perspectives/PerspectiveResolver.d.ts +0 -1
  58. package/lib/src/perspectives/PerspectiveResolver.js +0 -11
  59. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +3 -3
  60. package/lib/src/perspectives/WakerSubscriptionManager.js +7 -8
  61. package/lib/src/runtime/RuntimeResolver.d.ts +11 -0
  62. package/lib/src/runtime/RuntimeResolver.js +56 -0
  63. package/lib/src/schema.gql +11 -1
  64. package/lib/src/shacl/SHACLFlow.d.ts +1 -1
  65. package/lib/src/shacl/SHACLFlow.js +9 -9
  66. package/lib/src/shacl/SHACLShape.d.ts +1 -1
  67. package/lib/src/shacl/SHACLShape.js +38 -38
  68. package/lib/src/typeDefs.js +11 -1
  69. package/lib/src/utils.d.ts +6 -6
  70. package/lib/src/utils.js +6 -6
  71. package/package.json +1 -1
  72. package/src/Ad4mClient.test.ts +56 -1
  73. package/src/Literal.test.ts +10 -5
  74. package/src/Literal.ts +6 -5
  75. package/src/agent/AgentClient.ts +53 -1
  76. package/src/expression/ExpressionRef.ts +2 -2
  77. package/src/index.ts +0 -1
  78. package/src/language/Language.ts +55 -231
  79. package/src/model/Ad4mModel.test.ts +1709 -572
  80. package/src/model/Ad4mModel.ts +274 -120
  81. package/src/model/ModelQueryBuilder.ts +234 -87
  82. package/src/model/Subject.ts +6 -6
  83. package/src/model/decorators.ts +51 -22
  84. package/src/model/hydration-batch.ts +205 -0
  85. package/src/model/hydration-batching.test.ts +563 -0
  86. package/src/model/hydration.ts +349 -84
  87. package/src/model/index.ts +4 -1
  88. package/src/model/json-schema.ts +2 -2
  89. package/src/model/query-cache.test.ts +54 -0
  90. package/src/model/query-cache.ts +79 -0
  91. package/src/model/query-common.ts +1 -1
  92. package/src/model/query-sparql-batch.ts +301 -0
  93. package/src/model/query-sparql.test.ts +568 -0
  94. package/src/model/query-sparql.ts +820 -0
  95. package/src/model/{surreal-utils.ts → query-utils.ts} +44 -27
  96. package/src/model/relation-filtering.test.ts +15 -15
  97. package/src/model/sdna.ts +1 -1
  98. package/src/model/shacl-gen.ts +42 -17
  99. package/src/model/subscription-delta.test.ts +207 -0
  100. package/src/model/subscription-pool.ts +211 -0
  101. package/src/model/types.ts +53 -4
  102. package/src/perspectives/PerspectiveClient.test.ts +204 -0
  103. package/src/perspectives/PerspectiveClient.ts +41 -68
  104. package/src/perspectives/PerspectiveProxy.ts +244 -181
  105. package/src/perspectives/PerspectiveResolver.ts +0 -8
  106. package/src/perspectives/WakerSubscriptionManager.ts +8 -9
  107. package/src/runtime/RuntimeResolver.ts +43 -0
  108. package/src/shacl/SHACLFlow.ts +9 -9
  109. package/src/shacl/SHACLShape.ts +39 -39
  110. package/src/utils.ts +6 -6
  111. package/lib/src/model/query-surreal.d.ts +0 -44
  112. package/lib/src/model/query-surreal.js +0 -249
  113. package/src/language/LanguageContext.ts +0 -37
  114. package/src/model/query-surreal.ts +0 -280
  115. package/tsconfig-browser.json +0 -82
@@ -12,13 +12,16 @@ import { AIClient } from "../ai/AIClient";
12
12
  import { PERSPECTIVE_QUERY_SUBSCRIPTION } from "./PerspectiveResolver";
13
13
  import { gql } from "@apollo/client/core";
14
14
  import { getPropertiesMetadata, getRelationsMetadata } from "../model/decorators";
15
+ import { getCachedResult, setCachedResult, invalidatePerspectiveCache } from "../model/query-cache";
15
16
  import { AllInstancesResult } from "../model/types";
16
- import { escapeSurrealString } from "../utils";
17
+
17
18
  import { SHACLShape } from "../shacl/SHACLShape";
18
19
  import { SHACLFlow, LinkPattern } from "../shacl/SHACLFlow";
19
20
 
20
21
  type QueryCallback = (result: AllInstancesResult) => void;
21
22
 
23
+
24
+
22
25
  // Generic subscription interface that matches Apollo's Subscription
23
26
  interface Unsubscribable {
24
27
  unsubscribe(): void;
@@ -71,7 +74,6 @@ export class QuerySubscriptionProxy {
71
74
  #initReject?: (reason?: any) => void;
72
75
  #initTimeoutId?: NodeJS.Timeout;
73
76
  #query: string;
74
- isSurrealDB: boolean = false;
75
77
 
76
78
  /** Creates a new query subscription
77
79
  * @param uuid - The UUID of the perspective
@@ -114,11 +116,7 @@ export class QuerySubscriptionProxy {
114
116
  try {
115
117
  // Initialize the query subscription
116
118
  let initialResult;
117
- if (this.isSurrealDB) {
118
- initialResult = await this.#client.perspectiveSubscribeSurrealQuery(this.#uuid, this.#query);
119
- } else {
120
- initialResult = await this.#client.subscribeQuery(this.#uuid, this.#query);
121
- }
119
+ initialResult = await this.#client.subscribeQuery(this.#uuid, this.#query);
122
120
  this.#subscriptionId = initialResult.subscriptionId;
123
121
 
124
122
  // Process the initial result immediately for fast UX
@@ -180,11 +178,7 @@ export class QuerySubscriptionProxy {
180
178
  if (this.#disposed) return;
181
179
 
182
180
  try {
183
- if (this.isSurrealDB) {
184
- await this.#client.perspectiveKeepAliveSurrealQuery(this.#uuid, this.#subscriptionId);
185
- } else {
186
- await this.#client.keepAliveQuery(this.#uuid, this.#subscriptionId);
187
- }
181
+ await this.#client.keepAliveQuery(this.#uuid, this.#subscriptionId);
188
182
  } catch (e) {
189
183
  console.error('Error in keepalive:', e);
190
184
  // try to reinitialize the subscription
@@ -308,13 +302,8 @@ export class QuerySubscriptionProxy {
308
302
 
309
303
  // Tell the backend to dispose of the subscription
310
304
  if (this.#subscriptionId) {
311
- if (this.isSurrealDB) {
312
- this.#client.perspectiveDisposeSurrealQuerySubscription(this.#uuid, this.#subscriptionId)
313
- .catch(e => console.error('Error disposing surreal query subscription:', e));
314
- } else {
315
- this.#client.disposeQuerySubscription(this.#uuid, this.#subscriptionId)
316
- .catch(e => console.error('Error disposing query subscription:', e));
317
- }
305
+ this.#client.disposeQuerySubscription(this.#uuid, this.#subscriptionId)
306
+ .catch(e => console.error('Error disposing query subscription:', e));
318
307
  }
319
308
  }
320
309
  }
@@ -391,6 +380,7 @@ export class PerspectiveProxy {
391
380
  #perspectiveLinkRemovedCallbacks: LinkCallback[]
392
381
  #perspectiveLinkUpdatedCallbacks: LinkCallback[]
393
382
  #perspectiveSyncStateChangeCallbacks: SyncStateChangeCallback[]
383
+ #ensuredSubjectClasses = new Set<string>()
394
384
 
395
385
  /**
396
386
  * Creates a new PerspectiveProxy instance.
@@ -415,6 +405,24 @@ export class PerspectiveProxy {
415
405
  this.#client.addPerspectiveSyncStateChangeListener(this.#handle.uuid, this.#perspectiveSyncStateChangeCallbacks)
416
406
  }
417
407
 
408
+ /** Update the proxy's internal handle and public fields in-place.
409
+ * Keeps the same object reference so all holders see the update. */
410
+ updateHandle(handle: PerspectiveHandle): void {
411
+ if (handle.uuid !== this.#handle.uuid) {
412
+ throw new Error(
413
+ `PerspectiveProxy.updateHandle: UUID mismatch — proxy is bound to "${this.#handle.uuid}" but received handle with UUID "${handle.uuid}". ` +
414
+ `This would silently diverge from listeners registered under the original UUID.`
415
+ );
416
+ }
417
+ this.#handle = handle;
418
+ this.uuid = handle.uuid;
419
+ this.name = handle.name;
420
+ this.owners = handle.owners;
421
+ this.sharedUrl = handle.sharedUrl;
422
+ this.neighbourhood = handle.neighbourhood;
423
+ this.state = handle.state;
424
+ }
425
+
418
426
  /**
419
427
  * Escapes special regex characters in a string to prevent ReDoS attacks
420
428
  * and regex injection when building dynamic regular expressions.
@@ -489,7 +497,9 @@ export class PerspectiveProxy {
489
497
  * @param batchId - Optional batch ID to group this operation with others
490
498
  */
491
499
  async executeAction(actions, expression, parameters: Parameter[], batchId?: string) {
492
- return await this.#client.executeCommands(this.#handle.uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId)
500
+ const result = await this.#client.executeCommands(this.#handle.uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId)
501
+ invalidatePerspectiveCache(this.#handle.uuid);
502
+ return result
493
503
  }
494
504
 
495
505
  /**
@@ -545,34 +555,27 @@ export class PerspectiveProxy {
545
555
  }
546
556
 
547
557
  /**
548
- * Executes a SurrealQL query against the perspective's link cache.
549
- * This allows powerful SQL-like queries on the link data stored in SurrealDB.
558
+ * Executes a SPARQL query against the perspective's link cache.
559
+ * This allows powerful SQL-like queries on the link data stored in SPARQL.
550
560
  *
551
561
  * **Security Note:** Only read-only queries (SELECT, RETURN, etc.) are permitted.
552
562
  * Mutating operations (DELETE, UPDATE, INSERT, CREATE, DROP, DEFINE, etc.) are
553
563
  * blocked for security reasons. Use the perspective's add/remove methods to modify links.
554
564
  *
555
- * @param query - SurrealQL query string (read-only operations only)
565
+ * @param query - SPARQL query string (read-only operations only)
556
566
  * @returns Query results as parsed JSON
557
567
  *
558
- * @example
559
- * ```typescript
560
- * // Get all links
561
- * const links = await perspective.querySurrealDB('SELECT * FROM link');
562
- *
563
- * // Filter links by predicate
564
- * const follows = await perspective.querySurrealDB(
565
- * "SELECT * FROM link WHERE predicate = 'follows'"
566
- * );
567
- *
568
- * // Complex aggregation query
569
- * const stats = await perspective.querySurrealDB(
570
- * "SELECT predicate, count() as total FROM link GROUP BY predicate"
571
- * );
572
- * ```
568
+ * Executes a SPARQL query against the perspective's RDF (Oxigraph) store.
569
+ *
570
+ * @param query - SPARQL query string
571
+ * @returns Query results as parsed JSON
573
572
  */
574
- async querySurrealDB(query: string): Promise<any> {
575
- return await this.#client.querySurrealDB(this.#handle.uuid, query)
573
+ async querySparql(query: string): Promise<any> {
574
+ const cached = getCachedResult(this.#handle.uuid, query);
575
+ if (cached !== undefined) return cached;
576
+ const result = await this.#client.querySparql(this.#handle.uuid, query);
577
+ setCachedResult(this.#handle.uuid, query, result);
578
+ return result;
576
579
  }
577
580
 
578
581
  /**
@@ -601,7 +604,9 @@ export class PerspectiveProxy {
601
604
  * ```
602
605
  */
603
606
  async add(link: Link, status: LinkStatus = 'shared', batchId?: string): Promise<LinkExpression> {
604
- return await this.#client.addLink(this.#handle.uuid, link, status, batchId)
607
+ const result = await this.#client.addLink(this.#handle.uuid, link, status, batchId)
608
+ invalidatePerspectiveCache(this.#handle.uuid);
609
+ return result;
605
610
  }
606
611
 
607
612
  /**
@@ -614,7 +619,9 @@ export class PerspectiveProxy {
614
619
  * @returns Array of created LinkExpressions
615
620
  */
616
621
  async addLinks(links: Link[], status: LinkStatus = 'shared', batchId?: string): Promise<LinkExpression[]> {
617
- return await this.#client.addLinks(this.#handle.uuid, links, status, batchId)
622
+ const result = await this.#client.addLinks(this.#handle.uuid, links, status, batchId)
623
+ invalidatePerspectiveCache(this.#handle.uuid);
624
+ return result;
618
625
  }
619
626
 
620
627
  /**
@@ -625,7 +632,9 @@ export class PerspectiveProxy {
625
632
  * @returns Array of removed LinkExpressions
626
633
  */
627
634
  async removeLinks(links: LinkExpressionInput[], batchId?: string): Promise<LinkExpression[]> {
628
- return await this.#client.removeLinks(this.#handle.uuid, links, batchId)
635
+ const result = await this.#client.removeLinks(this.#handle.uuid, links, batchId)
636
+ invalidatePerspectiveCache(this.#handle.uuid);
637
+ return result;
629
638
  }
630
639
 
631
640
  /**
@@ -637,7 +646,9 @@ export class PerspectiveProxy {
637
646
  * @returns Object containing results of the mutations
638
647
  */
639
648
  async linkMutations(mutations: LinkMutations, status: LinkStatus = 'shared'): Promise<LinkExpressionMutations> {
640
- return await this.#client.linkMutations(this.#handle.uuid, mutations, status)
649
+ const result = await this.#client.linkMutations(this.#handle.uuid, mutations, status)
650
+ invalidatePerspectiveCache(this.#handle.uuid);
651
+ return result;
641
652
  }
642
653
 
643
654
  /**
@@ -660,7 +671,9 @@ export class PerspectiveProxy {
660
671
  * @param batchId - Optional batch ID to group this operation with others
661
672
  */
662
673
  async update(oldLink: LinkExpressionInput, newLink: Link, batchId?: string): Promise<LinkExpression> {
663
- return await this.#client.updateLink(this.#handle.uuid, oldLink, newLink, batchId)
674
+ const result = await this.#client.updateLink(this.#handle.uuid, oldLink, newLink, batchId)
675
+ invalidatePerspectiveCache(this.#handle.uuid);
676
+ return result;
664
677
  }
665
678
 
666
679
  /**
@@ -670,7 +683,9 @@ export class PerspectiveProxy {
670
683
  * @param batchId - Optional batch ID to group this operation with others
671
684
  */
672
685
  async remove(link: LinkExpressionInput, batchId?: string): Promise<boolean> {
673
- return await this.#client.removeLink(this.#handle.uuid, link, batchId)
686
+ const result = await this.#client.removeLink(this.#handle.uuid, link, batchId)
687
+ invalidatePerspectiveCache(this.#handle.uuid);
688
+ return result;
674
689
  }
675
690
 
676
691
  /** Creates a new batch for grouping operations */
@@ -680,9 +695,9 @@ export class PerspectiveProxy {
680
695
 
681
696
  /** Commits a batch of operations */
682
697
  async commitBatch(batchId: string): Promise<LinkExpressionMutations> {
683
- return await this.#client.commitBatch(this.#handle.uuid, batchId)
684
-
685
-
698
+ const result = await this.#client.commitBatch(this.#handle.uuid, batchId)
699
+ invalidatePerspectiveCache(this.#handle.uuid);
700
+ return result;
686
701
  }
687
702
  /**
688
703
  * Retrieves and renders an Expression referenced in this perspective.
@@ -1075,6 +1090,14 @@ export class PerspectiveProxy {
1075
1090
  return this.#client.addSdna(this.#handle.uuid, name, sdnaCode, sdnaType, shaclJson)
1076
1091
  }
1077
1092
 
1093
+ /**
1094
+ * Adds a subject class to the perspective.
1095
+ * Alias for addSdna() with sdnaType='subject_class'.
1096
+ */
1097
+ async addSubjectClass(name: string, shaclJson: string) {
1098
+ return this.addSdna(name, '', 'subject_class', shaclJson);
1099
+ }
1100
+
1078
1101
  /**
1079
1102
  * **Recommended way to add SDNA schemas.**
1080
1103
  *
@@ -1107,7 +1130,7 @@ export class PerspectiveProxy {
1107
1130
  const shapeLinks = shape.toLinks();
1108
1131
 
1109
1132
  // Create name -> shape mapping links
1110
- const nameMapping = Literal.fromUrl(`literal://string:shacl://${name}`);
1133
+ const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);
1111
1134
  const allLinks: Link[] = [
1112
1135
  ...shapeLinks.map(l => new Link({
1113
1136
  source: l.source,
@@ -1135,7 +1158,7 @@ export class PerspectiveProxy {
1135
1158
  */
1136
1159
  async getShacl(name: string): Promise<SHACLShape | null> {
1137
1160
  // Find the shape URI from the name mapping
1138
- const nameMapping = Literal.fromUrl(`literal://string:shacl://${name}`);
1161
+ const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);
1139
1162
  const shapeUriLinks = await this.get(new LinkQuery({
1140
1163
  source: nameMapping.toUrl(),
1141
1164
  predicate: "ad4m://shacl_shape_uri"
@@ -1146,7 +1169,6 @@ export class PerspectiveProxy {
1146
1169
  }
1147
1170
 
1148
1171
  const shapeUri = shapeUriLinks[0].data.target;
1149
- const escapedShapeUri = escapeSurrealString(shapeUri);
1150
1172
 
1151
1173
  // First get property shape URIs so we can query everything in one go
1152
1174
  const propertyLinks = await this.get(new LinkQuery({
@@ -1154,18 +1176,21 @@ export class PerspectiveProxy {
1154
1176
  predicate: "sh://property"
1155
1177
  }));
1156
1178
 
1157
- // Build a single surreal query that fetches all relevant links
1179
+ // Fetch all links from the shape and its property shapes
1158
1180
  const sourceUris = [shapeUri, ...propertyLinks.map(l => l.data.target)];
1159
- const escapedSources = sourceUris.map(u => `'${escapeSurrealString(u)}'`).join(', ');
1160
-
1161
- const query = `SELECT in.uri AS source, predicate, out.uri AS target FROM link WHERE in.uri IN [${escapedSources}]`;
1162
- const result = await this.querySurrealDB(query);
1181
+ const allLinks: Array<{source: string, predicate: string, target: string}> = [];
1182
+ for (const uri of sourceUris) {
1183
+ const links = await this.get(new LinkQuery({ source: uri }));
1184
+ for (const l of links) {
1185
+ allLinks.push({
1186
+ source: l.data.source,
1187
+ predicate: l.data.predicate,
1188
+ target: l.data.target
1189
+ });
1190
+ }
1191
+ }
1163
1192
 
1164
- const shapeLinks = (result || []).map((r: any) => ({
1165
- source: r.source,
1166
- predicate: r.predicate,
1167
- target: r.target
1168
- }));
1193
+ const shapeLinks = allLinks;
1169
1194
 
1170
1195
  return SHACLShape.fromLinks(shapeLinks, shapeUri);
1171
1196
  }
@@ -1279,22 +1304,22 @@ export class PerspectiveProxy {
1279
1304
  }
1280
1305
 
1281
1306
  const flowUri = flowUriLinks[0].data.target;
1282
- const escapedFlowUri = escapeSurrealString(flowUri);
1283
-
1284
1307
  // Compute alternate prefix for state/transition URIs
1285
1308
  const alternatePrefix = flowUri.endsWith('Flow')
1286
1309
  ? flowUri.slice(0, -4) + '.'
1287
1310
  : flowUri + '.';
1288
- const escapedAltPrefix = escapeSurrealString(alternatePrefix);
1289
1311
 
1290
- // Single surreal query to get all flow-related links
1291
- const query = `SELECT in.uri AS source, predicate, out.uri AS target FROM link WHERE in.uri = '${escapedFlowUri}' OR string::starts_with(in.uri, '${escapedAltPrefix}')`;
1292
- const result = await this.querySurrealDB(query);
1312
+ // Fetch flow links using SPARQL to match flowUri source OR alternatePrefix sources
1313
+ const sparqlQuery = `SELECT ?s ?p ?o WHERE {
1314
+ ?s ?p ?o .
1315
+ FILTER(?s = <${flowUri}> || STRSTARTS(STR(?s), "${alternatePrefix}"))
1316
+ }`;
1317
+ const sparqlResult = await this.querySparql(sparqlQuery);
1293
1318
 
1294
- const flowLinks = (result || []).map((r: any) => ({
1295
- source: r.source,
1296
- predicate: r.predicate,
1297
- target: r.target
1319
+ const flowLinks = (sparqlResult || []).map((r: any) => ({
1320
+ source: r.s,
1321
+ predicate: r.p,
1322
+ target: r.o
1298
1323
  }));
1299
1324
 
1300
1325
  return SHACLFlow.fromLinks(flowLinks, flowUri);
@@ -1427,8 +1452,8 @@ export class PerspectiveProxy {
1427
1452
 
1428
1453
  for (const link of links) {
1429
1454
  if (shapePattern.test(link.data.source)) {
1430
- // Parse actions from literal://string:{json}
1431
- const prefix = "literal://string:";
1455
+ // Parse actions from literal:string:{json}
1456
+ const prefix = "literal:string:";
1432
1457
  if (link.data.target.startsWith(prefix)) {
1433
1458
  const jsonStr = link.data.target.slice(prefix.length);
1434
1459
  // Decode URL-encoded JSON if needed, with fallback for raw % characters
@@ -1488,38 +1513,21 @@ export class PerspectiveProxy {
1488
1513
 
1489
1514
  // If no required triples, any expression with links is an instance
1490
1515
  if (metadata.requiredTriples.length === 0) {
1491
- const escapedExpression = escapeSurrealString(expression);
1492
- const checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}'`;
1493
- const result = await this.querySurrealDB(checkQuery);
1494
- const count = result[0]?.count ?? 0;
1495
- const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
1496
- return countValue > 0;
1516
+ const links = await this.get(new LinkQuery({ source: expression }));
1517
+ return links.length > 0;
1497
1518
  }
1498
1519
 
1499
1520
  // Check if the expression has all required triples (predicate + optional exact target)
1500
1521
  for (const triple of metadata.requiredTriples) {
1501
- const escapedExpression = escapeSurrealString(expression);
1502
- const escapedPredicate = escapeSurrealString(triple.predicate);
1503
- let checkQuery: string;
1522
+ let query: LinkQuery;
1504
1523
  if (triple.target) {
1505
- // Flag: must match both predicate AND exact target value
1506
- const escapedTarget = escapeSurrealString(triple.target);
1507
- checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}' AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}'`;
1524
+ query = new LinkQuery({ source: expression, predicate: triple.predicate, target: triple.target });
1508
1525
  } else {
1509
- // Property: just check predicate exists
1510
- checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}' AND predicate = '${escapedPredicate}'`;
1511
- }
1512
- const result = await this.querySurrealDB(checkQuery);
1513
-
1514
- if (!result || result.length === 0) {
1515
- return false;
1526
+ query = new LinkQuery({ source: expression, predicate: triple.predicate });
1516
1527
  }
1528
+ const links = await this.get(query);
1517
1529
 
1518
- const count = result[0]?.count ?? 0;
1519
- // Handle potential object response like {Int: 0}
1520
- const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
1521
-
1522
- if (countValue === 0) {
1530
+ if (!links || links.length === 0) {
1523
1531
  return false;
1524
1532
  }
1525
1533
  }
@@ -1551,6 +1559,16 @@ export class PerspectiveProxy {
1551
1559
  * Gets subject class metadata from SHACL links using SHACLShape.fromLinks().
1552
1560
  * Retrieves the SHACL shape and extracts metadata for instance queries.
1553
1561
  */
1562
+ async getSubjectClassMetadata(className: string): Promise<{
1563
+ requiredPredicates: string[],
1564
+ requiredTriples: Array<{predicate: string, target?: string}>,
1565
+ properties: Map<string, { predicate: string, resolveLanguage?: string }>,
1566
+ relations: Map<string, { predicate: string, instanceFilter?: string, condition?: string }>
1567
+ } | null> {
1568
+ return this.getSubjectClassMetadataFromSDNA(className);
1569
+ }
1570
+
1571
+ /** @deprecated Use getSubjectClassMetadata() */
1554
1572
  async getSubjectClassMetadataFromSDNA(className: string): Promise<{
1555
1573
  requiredPredicates: string[],
1556
1574
  requiredTriples: Array<{predicate: string, target?: string}>,
@@ -1612,40 +1630,61 @@ export class PerspectiveProxy {
1612
1630
  }
1613
1631
  }
1614
1632
  /**
1615
- * Generates a SurrealDB query to find instances based on class metadata.
1633
+ * Generates a SPARQL query to find instances based on class metadata.
1634
+ */
1635
+ /**
1636
+ * Finds all instances matching subject class metadata by querying links.
1637
+ * Returns base URIs of matching instances.
1616
1638
  */
1617
- private generateSurrealInstanceQuery(metadata: {
1639
+ private async findInstancesByMetadata(metadata: {
1618
1640
  requiredPredicates: string[],
1619
1641
  requiredTriples: Array<{predicate: string, target?: string}>,
1620
1642
  properties: Map<string, { predicate: string, resolveLanguage?: string }>,
1621
1643
  relations: Map<string, { predicate: string, instanceFilter?: string, condition?: string }>
1622
- }): string {
1644
+ }): Promise<Array<{base: string}>> {
1623
1645
  if (metadata.requiredTriples.length === 0) {
1624
- // No required triples - any node with links is an instance
1625
- return `SELECT DISTINCT uri AS base FROM node WHERE count(->link) > 0`;
1646
+ // No required triples - return all unique sources that have any link
1647
+ const allLinks = await this.get(new LinkQuery({}));
1648
+ const sources = new Set(allLinks.map(l => l.data.source));
1649
+ return Array.from(sources).map(s => ({ base: s }));
1626
1650
  }
1627
1651
 
1628
- // Generate WHERE conditions for each required triple (predicate + optional exact target)
1629
- const whereConditions = metadata.requiredTriples.map(triple => {
1630
- const escapedPredicate = escapeSurrealString(triple.predicate);
1631
- if (triple.target) {
1632
- // Flag: must match both predicate AND exact target value
1633
- const escapedTarget = escapeSurrealString(triple.target);
1634
- return `count(->link[WHERE predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}']) > 0`;
1635
- } else {
1636
- // Property: just check predicate exists
1637
- return `count(->link[WHERE predicate = '${escapedPredicate}']) > 0`;
1652
+ // Use first required triple to get candidate set, then filter by rest
1653
+ const first = metadata.requiredTriples[0];
1654
+ let query: LinkQuery;
1655
+ if (first.target) {
1656
+ query = new LinkQuery({ predicate: first.predicate, target: first.target });
1657
+ } else {
1658
+ query = new LinkQuery({ predicate: first.predicate });
1659
+ }
1660
+ const candidateLinks = await this.get(query);
1661
+ let candidates = [...new Set(candidateLinks.map(l => l.data.source))];
1662
+
1663
+ // Filter by remaining required triples
1664
+ for (let i = 1; i < metadata.requiredTriples.length; i++) {
1665
+ const triple = metadata.requiredTriples[i];
1666
+ const remaining: string[] = [];
1667
+ for (const expr of candidates) {
1668
+ let q: LinkQuery;
1669
+ if (triple.target) {
1670
+ q = new LinkQuery({ source: expr, predicate: triple.predicate, target: triple.target });
1671
+ } else {
1672
+ q = new LinkQuery({ source: expr, predicate: triple.predicate });
1673
+ }
1674
+ const links = await this.get(q);
1675
+ if (links.length > 0) remaining.push(expr);
1638
1676
  }
1639
- }).join(' AND ');
1677
+ candidates = remaining;
1678
+ }
1640
1679
 
1641
- return `SELECT uri AS base FROM node WHERE ${whereConditions}`;
1680
+ return candidates.map(c => ({ base: c }));
1642
1681
  }
1643
1682
 
1644
1683
  /**
1645
- * Gets a property value using SurrealDB when Prolog fails.
1684
+ * Gets a property value using SPARQL when Prolog fails.
1646
1685
  * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
1647
1686
  */
1648
- async getPropertyValueViaSurreal(baseExpression: string, className: string, propertyName: string): Promise<any> {
1687
+ async getPropertyValueViaSparql(baseExpression: string, className: string, propertyName: string): Promise<any> {
1649
1688
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
1650
1689
  if (!metadata) {
1651
1690
  return undefined;
@@ -1656,16 +1695,13 @@ export class PerspectiveProxy {
1656
1695
  return undefined;
1657
1696
  }
1658
1697
 
1659
- const escapedBaseExpression = escapeSurrealString(baseExpression);
1660
- const escapedPredicate = escapeSurrealString(propMeta.predicate);
1661
- const query = `SELECT out.uri AS value FROM link WHERE in.uri = '${escapedBaseExpression}' AND predicate = '${escapedPredicate}' LIMIT 1`;
1662
- const result = await this.querySurrealDB(query);
1698
+ const links = await this.get(new LinkQuery({ source: baseExpression, predicate: propMeta.predicate }));
1663
1699
 
1664
- if (!result || result.length === 0) {
1700
+ if (!links || links.length === 0) {
1665
1701
  return undefined;
1666
1702
  }
1667
1703
 
1668
- const value = result[0].value;
1704
+ const value = links[0].data.target;
1669
1705
 
1670
1706
  // Handle expression resolution if needed
1671
1707
  if (propMeta.resolveLanguage && value) {
@@ -1685,11 +1721,11 @@ export class PerspectiveProxy {
1685
1721
  }
1686
1722
 
1687
1723
  /**
1688
- * Gets relation values using SurrealDB when Prolog fails.
1724
+ * Gets relation values using SPARQL when Prolog fails.
1689
1725
  * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
1690
1726
  * Note: This is used by Subject.ts (legacy pattern). Ad4mModel.ts uses getModelMetadata() instead.
1691
1727
  */
1692
- async getRelationValuesViaSurreal(baseExpression: string, className: string, relationName: string): Promise<any[]> {
1728
+ async getRelationValuesViaSparql(baseExpression: string, className: string, relationName: string): Promise<any[]> {
1693
1729
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
1694
1730
  if (!metadata) {
1695
1731
  return [];
@@ -1700,16 +1736,16 @@ export class PerspectiveProxy {
1700
1736
  return [];
1701
1737
  }
1702
1738
 
1703
- const escapedBaseExpression = escapeSurrealString(baseExpression);
1704
- const escapedPredicate = escapeSurrealString(relMeta.predicate);
1705
- const query = `SELECT out.uri AS value, timestamp FROM link WHERE in.uri = '${escapedBaseExpression}' AND predicate = '${escapedPredicate}' ORDER BY timestamp ASC`;
1706
- const result = await this.querySurrealDB(query);
1739
+ const links = await this.get(new LinkQuery({ source: baseExpression, predicate: relMeta.predicate }));
1707
1740
 
1708
- if (!result || result.length === 0) {
1741
+ if (!links || links.length === 0) {
1709
1742
  return [];
1710
1743
  }
1711
1744
 
1712
- let values = result.map(r => r.value).filter(v => v !== "" && v !== '');
1745
+ // Sort by timestamp ascending
1746
+ links.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
1747
+
1748
+ let values = links.map(l => l.data.target).filter(v => v !== "" && v !== '');
1713
1749
 
1714
1750
  // Apply condition filtering if present
1715
1751
  if (relMeta.condition && values.length > 0) {
@@ -1722,14 +1758,26 @@ export class PerspectiveProxy {
1722
1758
  .replace(/\$base/g, `'${baseExpression}'`)
1723
1759
  .replace(/Target/g, `'${value.replace(/'/g, "\\'")}'`);
1724
1760
 
1725
- // If condition starts with WHERE, wrap in array length check
1726
- if (condition.trim().startsWith('WHERE')) {
1727
- condition = `array::len(SELECT * FROM link ${condition}) > 0`;
1728
- }
1761
+ // Parse condition to extract link query parameters
1762
+ // Conditions typically look like: WHERE in.uri = 'X' AND predicate = 'Y' AND out.uri = 'Z'
1763
+ // or: array::len(SELECT * FROM link WHERE ...) > 0
1764
+ // Convert to queryLinks calls
1765
+ const sourceMatch = condition.match(/in\.uri\s*=\s*'([^']+)'/);
1766
+ const predicateMatch = condition.match(/predicate\s*=\s*'([^']+)'/);
1767
+ const targetMatch = condition.match(/out\.uri\s*=\s*'([^']+)'/);
1729
1768
 
1730
- const filterResult = await this.querySurrealDB(`RETURN ${condition}`);
1731
- const isTrue = filterResult === true || (Array.isArray(filterResult) && filterResult.length > 0 && filterResult[0] === true);
1732
- if (isTrue) {
1769
+ if (sourceMatch || predicateMatch || targetMatch) {
1770
+ const linkQuery: any = {};
1771
+ if (sourceMatch) linkQuery.source = sourceMatch[1];
1772
+ if (predicateMatch) linkQuery.predicate = predicateMatch[1];
1773
+ if (targetMatch) linkQuery.target = targetMatch[1];
1774
+
1775
+ const matchingLinks = await this.get(new LinkQuery(linkQuery));
1776
+ if (matchingLinks.length > 0) {
1777
+ filteredValues.push(value);
1778
+ }
1779
+ } else {
1780
+ // Can't parse condition, include by default
1733
1781
  filteredValues.push(value);
1734
1782
  }
1735
1783
  }
@@ -1760,7 +1808,7 @@ export class PerspectiveProxy {
1760
1808
  }
1761
1809
 
1762
1810
  /**
1763
- * Batch-checks multiple expressions against subject class metadata using a single or limited SurrealDB queries.
1811
+ * Batch-checks multiple expressions against subject class metadata using a single or limited SPARQL queries.
1764
1812
  * This avoids N+1 query problems by checking all values at once.
1765
1813
  */
1766
1814
  async batchCheckSubjectInstances(
@@ -1778,33 +1826,30 @@ export class PerspectiveProxy {
1778
1826
 
1779
1827
  // If no required triples, check which expressions have any links
1780
1828
  if (metadata.requiredTriples.length === 0) {
1781
- const escapedExpressions = expressions.map(e => `'${escapeSurrealString(e)}'`).join(', ');
1782
- const checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] GROUP BY in.uri HAVING count() > 0`;
1783
- const result = await this.querySurrealDB(checkQuery);
1784
- return result.map(r => r.uri);
1829
+ const results: string[] = [];
1830
+ for (const expr of expressions) {
1831
+ const links = await this.get(new LinkQuery({ source: expr }));
1832
+ if (links.length > 0) results.push(expr);
1833
+ }
1834
+ return results;
1785
1835
  }
1786
1836
 
1787
- // For each required triple, build a query that finds matching expressions
1837
+ // For each required triple, find which expressions match
1788
1838
  const validExpressionSets: Set<string>[] = [];
1789
1839
 
1790
1840
  for (const triple of metadata.requiredTriples) {
1791
- const escapedExpressions = expressions.map(e => `'${escapeSurrealString(e)}'`).join(', ');
1792
- const escapedPredicate = escapeSurrealString(triple.predicate);
1793
-
1794
- let checkQuery: string;
1795
- if (triple.target) {
1796
- // Flag: must match both predicate AND exact target value
1797
- const escapedTarget = escapeSurrealString(triple.target);
1798
- // Note: Removed GROUP BY because it was causing SurrealDB to only return one result
1799
- checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}'`;
1800
- } else {
1801
- // Property: just check predicate exists
1802
- // Note: Removed GROUP BY because it was causing SurrealDB to only return one result
1803
- checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}'`;
1841
+ const matchingExprs = new Set<string>();
1842
+ for (const expr of expressions) {
1843
+ let query: LinkQuery;
1844
+ if (triple.target) {
1845
+ query = new LinkQuery({ source: expr, predicate: triple.predicate, target: triple.target });
1846
+ } else {
1847
+ query = new LinkQuery({ source: expr, predicate: triple.predicate });
1848
+ }
1849
+ const links = await this.get(query);
1850
+ if (links.length > 0) matchingExprs.add(expr);
1804
1851
  }
1805
-
1806
- const result = await this.querySurrealDB(checkQuery);
1807
- validExpressionSets.push(new Set(result.map(r => r.uri)));
1852
+ validExpressionSets.push(matchingExprs);
1808
1853
  }
1809
1854
 
1810
1855
  // Find intersection: expressions that passed ALL required triple checks
@@ -1860,13 +1905,13 @@ export class PerspectiveProxy {
1860
1905
  let instances = []
1861
1906
  for(let className of classes) {
1862
1907
  //console.log(`getAllSubjectInstances: Processing class ${className}`);
1863
- // Query SDNA for metadata, then query SurrealDB for instances
1908
+ // Query SDNA for metadata, then query SPARQL for instances
1864
1909
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
1865
1910
  //console.log(`getAllSubjectInstances: Got metadata for ${className}:`, metadata);
1866
1911
  if (metadata) {
1867
- const surrealQuery = this.generateSurrealInstanceQuery(metadata);
1868
- const results = await this.querySurrealDB(surrealQuery);
1869
- // console.log(`getAllSubjectInstances: SurrealDB returned ${results?.length || 0} results`);
1912
+ const results = await this.findInstancesByMetadata(metadata);
1913
+
1914
+ // console.log(`getAllSubjectInstances: SPARQL returned ${results?.length || 0} results`);
1870
1915
 
1871
1916
  for (const result of results || []) {
1872
1917
  //console.log(`getAllSubjectInstances: Creating subject for base ${result.base}`);
@@ -1912,11 +1957,11 @@ export class PerspectiveProxy {
1912
1957
 
1913
1958
  let instances = []
1914
1959
  for(let className of classes) {
1915
- // Query SDNA for metadata, then query SurrealDB for instances
1960
+ // Query SDNA for metadata, then query SPARQL for instances
1916
1961
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
1917
1962
  if (metadata) {
1918
- const surrealQuery = this.generateSurrealInstanceQuery(metadata);
1919
- const results = await this.querySurrealDB(surrealQuery);
1963
+ const results = await this.findInstancesByMetadata(metadata);
1964
+
1920
1965
 
1921
1966
  for (const result of results || []) {
1922
1967
  try {
@@ -1967,16 +2012,16 @@ export class PerspectiveProxy {
1967
2012
  return null;
1968
2013
  }
1969
2014
 
1970
- // Single SurrealDB query to find all classes and their properties/relations
1971
- const query = `SELECT
1972
- in.uri AS shape_source,
1973
- predicate,
1974
- out.uri AS target
1975
- FROM link
1976
- WHERE predicate IN ['rdf://type', 'sh://property', 'sh://collection']`;
1977
-
1978
- const results = await this.querySurrealDB(query);
1979
- if (!results || results.length === 0) return null;
2015
+ // Query links for class shapes using queryLinks
2016
+ const typeLinks = await this.get(new LinkQuery({ predicate: 'rdf://type', target: 'ad4m://SubjectClass' }));
2017
+ const propLinks = await this.get(new LinkQuery({ predicate: 'sh://property' }));
2018
+ const collLinks = await this.get(new LinkQuery({ predicate: 'sh://collection' }));
2019
+ const results = [
2020
+ ...typeLinks.map(l => ({ shape_source: l.data.source, predicate: l.data.predicate, target: l.data.target })),
2021
+ ...propLinks.map(l => ({ shape_source: l.data.source, predicate: l.data.predicate, target: l.data.target })),
2022
+ ...collLinks.map(l => ({ shape_source: l.data.source, predicate: l.data.predicate, target: l.data.target })),
2023
+ ];
2024
+ if (results.length === 0) return null;
1980
2025
 
1981
2026
  // Build a map of className -> { properties, relations }
1982
2027
  const classShapes: Map<string, { shapeUri: string, properties: string[], relations: string[] }> = new Map();
@@ -2076,9 +2121,17 @@ export class PerspectiveProxy {
2076
2121
  * static generateSDNA() function and adds it to the perspective's SDNA.
2077
2122
  */
2078
2123
  async ensureSDNASubjectClass(jsClass: any): Promise<void> {
2124
+ return this.ensureSubjectClass(jsClass);
2125
+ }
2126
+
2127
+ /** Takes a JS class (its constructor) and ensures the SHACL subject class exists. */
2128
+ async ensureSubjectClass(jsClass: any): Promise<void> {
2079
2129
  // Get the class name from the JS class
2080
2130
  const className = jsClass.className || jsClass.prototype?.className || jsClass.name;
2081
2131
 
2132
+ // Skip if already registered for this perspective instance
2133
+ if (this.#ensuredSubjectClasses.has(className)) return;
2134
+
2082
2135
  // Note: Duplicate checking is handled on the Rust side in add_sdna
2083
2136
 
2084
2137
  // Generate SHACL SDNA (Prolog-free)
@@ -2095,6 +2148,16 @@ export class PerspectiveProxy {
2095
2148
  // Pass SHACL JSON to backend (Prolog-free)
2096
2149
  // Backend stores SHACL links directly
2097
2150
  await this.addSdna(className, '', 'subject_class', shaclJson);
2151
+
2152
+ // Mark as registered for this perspective instance
2153
+ this.#ensuredSubjectClasses.add(className);
2154
+ }
2155
+
2156
+ /** Clear the per-instance ensured subject class cache.
2157
+ * Call this after wiping a perspective's links so that
2158
+ * subsequent register() calls re-add SHACL definitions. */
2159
+ clearEnsuredSubjectClasses(): void {
2160
+ this.#ensuredSubjectClasses.clear();
2098
2161
  }
2099
2162
 
2100
2163
  getNeighbourhoodProxy(): NeighbourhoodProxy {
@@ -2175,7 +2238,7 @@ export class PerspectiveProxy {
2175
2238
  }
2176
2239
 
2177
2240
  /**
2178
- * Creates a subscription for a SurrealQL query that updates in real-time.
2241
+ * Creates a subscription for a SPARQL query that updates in real-time.
2179
2242
  *
2180
2243
  * This method:
2181
2244
  * 1. Creates the subscription on the Rust side
@@ -2190,16 +2253,16 @@ export class PerspectiveProxy {
2190
2253
  * when dispose() is called. Make sure to call dispose() when you're done to
2191
2254
  * prevent memory leaks and ensure proper cleanup of resources.
2192
2255
  *
2193
- * @param query - SurrealQL query string
2256
+ /** Subscribe to a query with live updates via the SPARQL subscription endpoint.
2257
+ * @param query - Query string
2194
2258
  * @returns Initialized QuerySubscriptionProxy instance
2195
2259
  */
2196
- async subscribeSurrealDB(query: string): Promise<QuerySubscriptionProxy> {
2260
+ async subscribeQuery(query: string): Promise<QuerySubscriptionProxy> {
2197
2261
  const subscriptionProxy = new QuerySubscriptionProxy(
2198
2262
  this.uuid,
2199
2263
  query,
2200
2264
  this.#client
2201
2265
  );
2202
- subscriptionProxy.isSurrealDB = true;
2203
2266
 
2204
2267
  // Start the subscription on the Rust side first to get the real subscription ID
2205
2268
  await subscriptionProxy.subscribe();