@coasys/ad4m 0.12.1-dev → 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 (97) hide show
  1. package/lib/index.cjs +1469 -781
  2. package/lib/index.js +1453 -779
  3. package/lib/src/Literal.js +6 -5
  4. package/lib/src/agent/AgentClient.d.ts +8 -1
  5. package/lib/src/agent/AgentClient.js +73 -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/RuntimeClient.d.ts +2 -0
  51. package/lib/src/runtime/RuntimeClient.js +17 -0
  52. package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
  53. package/lib/src/runtime/RuntimeResolver.js +84 -0
  54. package/lib/src/schema.gql +14 -1
  55. package/lib/src/shacl/SHACLFlow.d.ts +1 -1
  56. package/lib/src/shacl/SHACLFlow.js +9 -9
  57. package/lib/src/shacl/SHACLShape.d.ts +1 -1
  58. package/lib/src/shacl/SHACLShape.js +38 -38
  59. package/lib/src/typeDefs.js +14 -1
  60. package/lib/src/utils.d.ts +6 -6
  61. package/lib/src/utils.js +6 -6
  62. package/package.json +1 -1
  63. package/src/Literal.test.ts +10 -5
  64. package/src/Literal.ts +6 -5
  65. package/src/agent/AgentClient.ts +81 -1
  66. package/src/expression/ExpressionRef.ts +2 -2
  67. package/src/language/Language.ts +48 -3
  68. package/src/model/Ad4mModel.test.ts +1515 -565
  69. package/src/model/Ad4mModel.ts +142 -102
  70. package/src/model/ModelQueryBuilder.ts +185 -86
  71. package/src/model/Subject.ts +6 -6
  72. package/src/model/decorators.ts +51 -22
  73. package/src/model/hydration-batch.ts +205 -0
  74. package/src/model/hydration.ts +102 -39
  75. package/src/model/index.ts +4 -1
  76. package/src/model/json-schema.ts +2 -2
  77. package/src/model/query-cache.test.ts +54 -0
  78. package/src/model/query-cache.ts +79 -0
  79. package/src/model/query-common.ts +1 -1
  80. package/src/model/query-sparql-batch.ts +301 -0
  81. package/src/model/query-sparql.ts +363 -0
  82. package/src/model/{surreal-utils.ts → query-utils.ts} +40 -27
  83. package/src/model/relation-filtering.test.ts +15 -15
  84. package/src/model/sdna.ts +1 -1
  85. package/src/model/shacl-gen.ts +42 -17
  86. package/src/model/subscription-pool.ts +163 -0
  87. package/src/model/types.ts +3 -3
  88. package/src/perspectives/PerspectiveClient.ts +5 -61
  89. package/src/perspectives/PerspectiveProxy.ts +226 -181
  90. package/src/perspectives/PerspectiveResolver.ts +0 -8
  91. package/src/perspectives/WakerSubscriptionManager.ts +8 -9
  92. package/src/runtime/RuntimeClient.ts +19 -0
  93. package/src/runtime/RuntimeResolver.ts +58 -0
  94. package/src/shacl/SHACLFlow.ts +9 -9
  95. package/src/shacl/SHACLShape.ts +39 -39
  96. package/src/utils.ts +6 -6
  97. package/src/model/query-surreal.ts +0 -280
package/lib/index.cjs CHANGED
@@ -4310,8 +4310,10 @@ class Literal {
4310
4310
  _Literal_url.set(this, void 0);
4311
4311
  }
4312
4312
  static fromUrl(url) {
4313
- if (!url || !url.startsWith("literal://"))
4313
+ if (!url || !url.startsWith("literal:"))
4314
4314
  throw new Error("Can't create Literal from non-literal URL");
4315
+ if (url.startsWith("literal://"))
4316
+ throw new Error("literal:// format is no longer supported. Use literal: instead.");
4315
4317
  const l = new Literal();
4316
4318
  __classPrivateFieldSet$b(l, _Literal_url, url, "f");
4317
4319
  return l;
@@ -4341,17 +4343,16 @@ class Literal {
4341
4343
  encoded = `json:${encodeRFC3986URIComponent(JSON.stringify(__classPrivateFieldGet$b(this, _Literal_literal, "f")))}`;
4342
4344
  break;
4343
4345
  }
4344
- return `literal://${encoded}`;
4346
+ return `literal:${encoded}`;
4345
4347
  }
4346
4348
  get() {
4347
4349
  if (__classPrivateFieldGet$b(this, _Literal_literal, "f"))
4348
4350
  return __classPrivateFieldGet$b(this, _Literal_literal, "f");
4349
4351
  if (!__classPrivateFieldGet$b(this, _Literal_url, "f"))
4350
4352
  throw new Error("Can't render empty Literal");
4351
- if (!__classPrivateFieldGet$b(this, _Literal_url, "f").startsWith("literal://"))
4353
+ if (!__classPrivateFieldGet$b(this, _Literal_url, "f").startsWith("literal:"))
4352
4354
  throw new Error("Can't render Literal from non-literal URL");
4353
- // get rid of "literal://"
4354
- const body = __classPrivateFieldGet$b(this, _Literal_url, "f").substring(10);
4355
+ const body = __classPrivateFieldGet$b(this, _Literal_url, "f").substring(8);
4355
4356
  if (body.startsWith("string:")) {
4356
4357
  return decodeURIComponent(body.substring(7));
4357
4358
  }
@@ -4481,12 +4482,12 @@ class Subject {
4481
4482
  Object.defineProperty(this, p, {
4482
4483
  configurable: true,
4483
4484
  get: async () => {
4484
- // Use SurrealDB for data queries
4485
+ // Use SPARQL for data queries
4485
4486
  try {
4486
- return await __classPrivateFieldGet$a(this, _Subject_perspective, "f").getPropertyValueViaSurreal(__classPrivateFieldGet$a(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$a(this, _Subject_subjectClassName, "f"), p);
4487
+ return await __classPrivateFieldGet$a(this, _Subject_perspective, "f").getPropertyValueViaSparql(__classPrivateFieldGet$a(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$a(this, _Subject_subjectClassName, "f"), p);
4487
4488
  }
4488
4489
  catch (err) {
4489
- console.warn(`Failed to get property ${p} via SurrealDB:`, err);
4490
+ console.warn(`Failed to get property ${p} via SPARQL:`, err);
4490
4491
  return undefined;
4491
4492
  }
4492
4493
  }
@@ -4520,12 +4521,12 @@ class Subject {
4520
4521
  Object.defineProperty(this, c, {
4521
4522
  configurable: true,
4522
4523
  get: async () => {
4523
- // Use SurrealDB for data queries
4524
+ // Use SPARQL for data queries
4524
4525
  try {
4525
- return await __classPrivateFieldGet$a(this, _Subject_perspective, "f").getRelationValuesViaSurreal(__classPrivateFieldGet$a(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$a(this, _Subject_subjectClassName, "f"), c);
4526
+ return await __classPrivateFieldGet$a(this, _Subject_perspective, "f").getRelationValuesViaSparql(__classPrivateFieldGet$a(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$a(this, _Subject_subjectClassName, "f"), c);
4526
4527
  }
4527
4528
  catch (err) {
4528
- console.warn(`Failed to get relation ${c} via SurrealDB:`, err);
4529
+ console.warn(`Failed to get relation ${c} via SPARQL:`, err);
4529
4530
  return [];
4530
4531
  }
4531
4532
  }
@@ -4663,7 +4664,7 @@ function buildSDNA(subjectName, obj, properties, allRelationsMeta) {
4663
4664
  // Optional properties (required: false) are excluded — they should
4664
4665
  // remain unset (undefined) until explicitly assigned.
4665
4666
  const effectiveInitial = initial
4666
- ?? (required && writable && !flag && through ? "literal://string:" : undefined);
4667
+ ?? (required && writable && !flag && through ? "literal:string:" : undefined);
4667
4668
  if (effectiveInitial) {
4668
4669
  constructorActions.push({
4669
4670
  action: "addLink",
@@ -4949,7 +4950,7 @@ class SHACLShape {
4949
4950
  links.push({
4950
4951
  source: this.nodeShapeUri,
4951
4952
  predicate: "ad4m://constructor",
4952
- target: `literal://string:${JSON.stringify(this.constructor_actions)}`
4953
+ target: `literal:string:${JSON.stringify(this.constructor_actions)}`
4953
4954
  });
4954
4955
  }
4955
4956
  // Destructor actions — same rationale as constructor.
@@ -4957,7 +4958,7 @@ class SHACLShape {
4957
4958
  links.push({
4958
4959
  source: this.nodeShapeUri,
4959
4960
  predicate: "ad4m://destructor",
4960
- target: `literal://string:${JSON.stringify(this.destructor_actions)}`
4961
+ target: `literal:string:${JSON.stringify(this.destructor_actions)}`
4961
4962
  });
4962
4963
  }
4963
4964
  // Property shapes (each gets a named URI: {namespace}/{ClassName}.{propertyName})
@@ -5007,42 +5008,42 @@ class SHACLShape {
5007
5008
  links.push({
5008
5009
  source: propShapeId,
5009
5010
  predicate: "sh://minCount",
5010
- target: `literal://${prop.minCount}^^xsd:integer`
5011
+ target: `literal:${prop.minCount}^^xsd:integer`
5011
5012
  });
5012
5013
  }
5013
5014
  if (prop.maxCount !== undefined) {
5014
5015
  links.push({
5015
5016
  source: propShapeId,
5016
5017
  predicate: "sh://maxCount",
5017
- target: `literal://${prop.maxCount}^^xsd:integer`
5018
+ target: `literal:${prop.maxCount}^^xsd:integer`
5018
5019
  });
5019
5020
  }
5020
5021
  if (prop.pattern) {
5021
5022
  links.push({
5022
5023
  source: propShapeId,
5023
5024
  predicate: "sh://pattern",
5024
- target: `literal://${prop.pattern}`
5025
+ target: `literal:${prop.pattern}`
5025
5026
  });
5026
5027
  }
5027
5028
  if (prop.minInclusive !== undefined) {
5028
5029
  links.push({
5029
5030
  source: propShapeId,
5030
5031
  predicate: "sh://minInclusive",
5031
- target: `literal://${prop.minInclusive}`
5032
+ target: `literal:${prop.minInclusive}`
5032
5033
  });
5033
5034
  }
5034
5035
  if (prop.maxInclusive !== undefined) {
5035
5036
  links.push({
5036
5037
  source: propShapeId,
5037
5038
  predicate: "sh://maxInclusive",
5038
- target: `literal://${prop.maxInclusive}`
5039
+ target: `literal:${prop.maxInclusive}`
5039
5040
  });
5040
5041
  }
5041
5042
  if (prop.hasValue) {
5042
5043
  links.push({
5043
5044
  source: propShapeId,
5044
5045
  predicate: "sh://hasValue",
5045
- target: `literal://${prop.hasValue}`
5046
+ target: `literal:${prop.hasValue}`
5046
5047
  });
5047
5048
  }
5048
5049
  // AD4M-specific metadata
@@ -5050,21 +5051,21 @@ class SHACLShape {
5050
5051
  links.push({
5051
5052
  source: propShapeId,
5052
5053
  predicate: "ad4m://local",
5053
- target: `literal://${prop.local}`
5054
+ target: `literal:${prop.local}`
5054
5055
  });
5055
5056
  }
5056
5057
  if (prop.writable !== undefined) {
5057
5058
  links.push({
5058
5059
  source: propShapeId,
5059
5060
  predicate: "ad4m://writable",
5060
- target: `literal://${prop.writable}`
5061
+ target: `literal:${prop.writable}`
5061
5062
  });
5062
5063
  }
5063
5064
  if (prop.resolveLanguage) {
5064
5065
  links.push({
5065
5066
  source: propShapeId,
5066
5067
  predicate: "ad4m://resolveLanguage",
5067
- target: `literal://string:${prop.resolveLanguage}`
5068
+ target: `literal:string:${prop.resolveLanguage}`
5068
5069
  });
5069
5070
  }
5070
5071
  // AD4M-specific actions
@@ -5072,35 +5073,35 @@ class SHACLShape {
5072
5073
  links.push({
5073
5074
  source: propShapeId,
5074
5075
  predicate: "ad4m://setter",
5075
- target: `literal://string:${JSON.stringify(prop.setter)}`
5076
+ target: `literal:string:${JSON.stringify(prop.setter)}`
5076
5077
  });
5077
5078
  }
5078
5079
  if (prop.adder && prop.adder.length > 0) {
5079
5080
  links.push({
5080
5081
  source: propShapeId,
5081
5082
  predicate: "ad4m://adder",
5082
- target: `literal://string:${JSON.stringify(prop.adder)}`
5083
+ target: `literal:string:${JSON.stringify(prop.adder)}`
5083
5084
  });
5084
5085
  }
5085
5086
  if (prop.remover && prop.remover.length > 0) {
5086
5087
  links.push({
5087
5088
  source: propShapeId,
5088
5089
  predicate: "ad4m://remover",
5089
- target: `literal://string:${JSON.stringify(prop.remover)}`
5090
+ target: `literal:string:${JSON.stringify(prop.remover)}`
5090
5091
  });
5091
5092
  }
5092
5093
  if (prop.getter) {
5093
5094
  links.push({
5094
5095
  source: propShapeId,
5095
5096
  predicate: "ad4m://getter",
5096
- target: `literal://string:${prop.getter}`
5097
+ target: `literal:string:${prop.getter}`
5097
5098
  });
5098
5099
  }
5099
5100
  if (prop.conformanceConditions && prop.conformanceConditions.length > 0) {
5100
5101
  links.push({
5101
5102
  source: propShapeId,
5102
5103
  predicate: "ad4m://conformanceConditions",
5103
- target: `literal://string:${JSON.stringify(prop.conformanceConditions)}`
5104
+ target: `literal:string:${JSON.stringify(prop.conformanceConditions)}`
5104
5105
  });
5105
5106
  }
5106
5107
  if (prop.class) {
@@ -5124,7 +5125,7 @@ class SHACLShape {
5124
5125
  const constructorLink = links.find(l => l.source === shapeUri && l.predicate === "ad4m://constructor");
5125
5126
  if (constructorLink) {
5126
5127
  try {
5127
- const jsonStr = constructorLink.target.replace('literal://string:', '');
5128
+ const jsonStr = constructorLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
5128
5129
  shape.constructor_actions = JSON.parse(jsonStr);
5129
5130
  }
5130
5131
  catch (e) {
@@ -5135,7 +5136,7 @@ class SHACLShape {
5135
5136
  const destructorLink = links.find(l => l.source === shapeUri && l.predicate === "ad4m://destructor");
5136
5137
  if (destructorLink) {
5137
5138
  try {
5138
- const jsonStr = destructorLink.target.replace('literal://string:', '');
5139
+ const jsonStr = destructorLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
5139
5140
  shape.destructor_actions = JSON.parse(jsonStr);
5140
5141
  }
5141
5142
  catch (e) {
@@ -5173,70 +5174,70 @@ class SHACLShape {
5173
5174
  }
5174
5175
  const minCountLink = links.find(l => l.source === propShapeId && l.predicate === "sh://minCount");
5175
5176
  if (minCountLink) {
5176
- // Handle both formats: literal://5^^xsd:integer and literal://number:5
5177
- let val = minCountLink.target.replace('literal://', '').replace(/\^\^.*$/, '');
5177
+ // Handle both formats: literal:5^^xsd:integer and literal:number:5
5178
+ let val = minCountLink.target.replace(/^literal:\/\/|^literal:/, '').replace(/\^\^.*$/, '');
5178
5179
  if (val.startsWith('number:'))
5179
5180
  val = val.substring(7);
5180
5181
  prop.minCount = parseInt(val);
5181
5182
  }
5182
5183
  const maxCountLink = links.find(l => l.source === propShapeId && l.predicate === "sh://maxCount");
5183
5184
  if (maxCountLink) {
5184
- // Handle both formats: literal://5^^xsd:integer and literal://number:5
5185
- let val = maxCountLink.target.replace('literal://', '').replace(/\^\^.*$/, '');
5185
+ // Handle both formats: literal:5^^xsd:integer and literal:number:5
5186
+ let val = maxCountLink.target.replace(/^literal:\/\/|^literal:/, '').replace(/\^\^.*$/, '');
5186
5187
  if (val.startsWith('number:'))
5187
5188
  val = val.substring(7);
5188
5189
  prop.maxCount = parseInt(val);
5189
5190
  }
5190
5191
  const patternLink = links.find(l => l.source === propShapeId && l.predicate === "sh://pattern");
5191
5192
  if (patternLink) {
5192
- prop.pattern = patternLink.target.replace('literal://', '');
5193
+ prop.pattern = patternLink.target.replace(/^literal:\/\/|^literal:/, '');
5193
5194
  }
5194
5195
  const minInclusiveLink = links.find(l => l.source === propShapeId && l.predicate === "sh://minInclusive");
5195
5196
  if (minInclusiveLink) {
5196
- // Handle both formats: literal://5 and literal://number:5
5197
- let val = minInclusiveLink.target.replace('literal://', '');
5197
+ // Handle both formats: literal:5 and literal:number:5
5198
+ let val = minInclusiveLink.target.replace(/^literal:\/\/|^literal:/, '');
5198
5199
  if (val.startsWith('number:'))
5199
5200
  val = val.substring(7);
5200
5201
  prop.minInclusive = parseFloat(val);
5201
5202
  }
5202
5203
  const maxInclusiveLink = links.find(l => l.source === propShapeId && l.predicate === "sh://maxInclusive");
5203
5204
  if (maxInclusiveLink) {
5204
- // Handle both formats: literal://5 and literal://number:5
5205
- let val = maxInclusiveLink.target.replace('literal://', '');
5205
+ // Handle both formats: literal:5 and literal:number:5
5206
+ let val = maxInclusiveLink.target.replace(/^literal:\/\/|^literal:/, '');
5206
5207
  if (val.startsWith('number:'))
5207
5208
  val = val.substring(7);
5208
5209
  prop.maxInclusive = parseFloat(val);
5209
5210
  }
5210
5211
  const hasValueLink = links.find(l => l.source === propShapeId && l.predicate === "sh://hasValue");
5211
5212
  if (hasValueLink) {
5212
- prop.hasValue = hasValueLink.target.replace('literal://', '');
5213
+ prop.hasValue = hasValueLink.target.replace(/^literal:\/\/|^literal:/, '');
5213
5214
  }
5214
5215
  // AD4M-specific
5215
5216
  const localLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://local");
5216
5217
  if (localLink) {
5217
- // Handle both formats: literal://true and literal://boolean:true
5218
- let val = localLink.target.replace('literal://', '');
5218
+ // Handle both formats: literal:true and literal:boolean:true
5219
+ let val = localLink.target.replace(/^literal:\/\/|^literal:/, '');
5219
5220
  if (val.startsWith('boolean:'))
5220
5221
  val = val.substring(8);
5221
5222
  prop.local = val === 'true';
5222
5223
  }
5223
5224
  const writableLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://writable");
5224
5225
  if (writableLink) {
5225
- // Handle both formats: literal://true and literal://boolean:true
5226
- let val = writableLink.target.replace('literal://', '');
5226
+ // Handle both formats: literal:true and literal:boolean:true
5227
+ let val = writableLink.target.replace(/^literal:\/\/|^literal:/, '');
5227
5228
  if (val.startsWith('boolean:'))
5228
5229
  val = val.substring(8);
5229
5230
  prop.writable = val === 'true';
5230
5231
  }
5231
5232
  const resolveLangLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://resolveLanguage");
5232
5233
  if (resolveLangLink) {
5233
- prop.resolveLanguage = resolveLangLink.target.replace('literal://string:', '');
5234
+ prop.resolveLanguage = resolveLangLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
5234
5235
  }
5235
5236
  // Parse action arrays
5236
5237
  const setterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://setter");
5237
5238
  if (setterLink) {
5238
5239
  try {
5239
- const jsonStr = setterLink.target.replace('literal://string:', '');
5240
+ const jsonStr = setterLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
5240
5241
  prop.setter = JSON.parse(jsonStr);
5241
5242
  }
5242
5243
  catch (e) {
@@ -5246,7 +5247,7 @@ class SHACLShape {
5246
5247
  const adderLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://adder");
5247
5248
  if (adderLink) {
5248
5249
  try {
5249
- const jsonStr = adderLink.target.replace('literal://string:', '');
5250
+ const jsonStr = adderLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
5250
5251
  prop.adder = JSON.parse(jsonStr);
5251
5252
  }
5252
5253
  catch (e) {
@@ -5256,7 +5257,7 @@ class SHACLShape {
5256
5257
  const removerLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://remover");
5257
5258
  if (removerLink) {
5258
5259
  try {
5259
- const jsonStr = removerLink.target.replace('literal://string:', '');
5260
+ const jsonStr = removerLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
5260
5261
  prop.remover = JSON.parse(jsonStr);
5261
5262
  }
5262
5263
  catch (e) {
@@ -5265,12 +5266,12 @@ class SHACLShape {
5265
5266
  }
5266
5267
  const getterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://getter");
5267
5268
  if (getterLink) {
5268
- prop.getter = getterLink.target.replace('literal://string:', '');
5269
+ prop.getter = getterLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
5269
5270
  }
5270
5271
  const conditionsLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://conformanceConditions");
5271
5272
  if (conditionsLink) {
5272
5273
  try {
5273
- const jsonStr = conditionsLink.target.replace('literal://string:', '');
5274
+ const jsonStr = conditionsLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
5274
5275
  prop.conformanceConditions = JSON.parse(jsonStr);
5275
5276
  }
5276
5277
  catch (e) {
@@ -5387,28 +5388,28 @@ function capSentence(cap) {
5387
5388
  return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
5388
5389
  }
5389
5390
  /**
5390
- * Escapes a string value for safe use in SurrealQL queries.
5391
+ * Escapes a string value for safe use in query strings.
5391
5392
  *
5392
5393
  * @description
5393
5394
  * Prevents SQL injection by properly escaping special characters in string values
5394
- * that will be interpolated into SurrealQL queries. This handles the most common
5395
+ * that will be interpolated into query strings. This handles the most common
5395
5396
  * special characters that could break SQL queries or enable injection attacks.
5396
5397
  *
5397
5398
  * Single quotes, backslashes, and other special characters are escaped using
5398
- * backslash notation, which is the standard escaping mechanism for SurrealQL.
5399
+ * backslash notation, which is the standard escaping mechanism for query.
5399
5400
  *
5400
5401
  * @param value - The string value to escape
5401
- * @returns The escaped string safe for SurrealQL interpolation (without surrounding quotes)
5402
+ * @returns The escaped string safe for query interpolation (without surrounding quotes)
5402
5403
  *
5403
5404
  * @example
5404
5405
  * ```typescript
5405
5406
  * const userInput = "user's input with 'quotes'";
5406
- * const escaped = escapeSurrealString(userInput);
5407
+ * const escaped = escapeQueryString(userInput);
5407
5408
  * const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
5408
5409
  * // Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''
5409
5410
  * ```
5410
5411
  */
5411
- function escapeSurrealString(value) {
5412
+ function escapeQueryString(value) {
5412
5413
  return value
5413
5414
  .replace(/\\/g, '\\\\') // Backslash -> \\
5414
5415
  .replace(/'/g, "\\'") // Single quote -> \'
@@ -5419,19 +5420,21 @@ function escapeSurrealString(value) {
5419
5420
  }
5420
5421
 
5421
5422
  /**
5422
- * Shared SurrealQL compilation utilities.
5423
+ * Shared query compilation utilities.
5423
5424
  *
5424
5425
  * These functions are used by both the runtime query builder (`Ad4mModel`) and
5425
5426
  * the compile-time SHACL generator (`decorators.ts`).
5427
+ *
5428
+ * All output uses native SPARQL syntax.
5426
5429
  */
5427
5430
  /**
5428
- * Format a JavaScript value for embedding in a SurrealQL expression.
5431
+ * Format a JavaScript value for embedding in a query expression.
5429
5432
  *
5430
5433
  * - Strings are single-quoted with backslash / quote / newline escaping
5431
5434
  * - Numbers and booleans are passed through as-is
5432
5435
  * - Arrays are recursed
5433
5436
  */
5434
- function formatSurrealValue(value) {
5437
+ function formatQueryValue(value) {
5435
5438
  if (typeof value === 'string') {
5436
5439
  // Escape backslashes first, then single quotes and other special characters
5437
5440
  const escaped = value
@@ -5447,33 +5450,45 @@ function formatSurrealValue(value) {
5447
5450
  return String(value);
5448
5451
  }
5449
5452
  else if (Array.isArray(value)) {
5450
- return `[${value.map(v => formatSurrealValue(v)).join(', ')}]`;
5453
+ return `[${value.map(v => formatQueryValue(v)).join(', ')}]`;
5451
5454
  }
5452
5455
  else {
5453
5456
  return String(value);
5454
5457
  }
5455
5458
  }
5456
5459
  /**
5457
- * Compile a single Where condition for a property into a SurrealQL
5458
- * graph-traversal sub-expression.
5460
+ * Compile a single Where condition for a property into a SPARQL triple pattern
5461
+ * that can be embedded in a getter's WHERE clause.
5459
5462
  *
5460
- * Operates on the **target node** — generates `count(->link[WHERE ...]) > 0`
5461
- * style checks that can be used inside a `[WHERE ...]` filter on nodes.
5463
+ * The generated pattern operates on `?target` — e.g.:
5464
+ * `?target <pred> <value> .`
5465
+ * `FILTER EXISTS { ?target <pred> ?_v0 }`
5462
5466
  *
5463
5467
  * @param predicate - The predicate URI for the property
5464
5468
  * @param condition - The Where condition value
5465
5469
  * @param opts - Optional settings (e.g. `resolveLanguage`)
5466
- * @returns A single SurrealQL condition string
5470
+ * @returns A single SPARQL condition string
5467
5471
  */
5468
5472
  function buildWhereCondition(predicate, condition, opts) {
5469
- const escapedPredicate = escapeSurrealString(predicate);
5470
- const targetField = opts?.resolveLanguage === 'literal'
5471
- ? 'fn::parse_literal(out.uri)'
5472
- : 'out.uri';
5473
+ const escapedPredicate = escapeQueryString(predicate);
5474
+ // For literal-resolved properties, we match against the raw IRI (which is a literal: URI)
5475
+ // For language-resolved properties, we match against the plain URI
5476
+ // For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>
5477
+ // For language-resolved properties, values are plain URIs
5478
+ const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
5479
+ function formatValue(v) {
5480
+ if (typeof v === 'string') {
5481
+ return isLiteral
5482
+ ? `<literal:string:${escapeQueryString(v)}>`
5483
+ : `<${escapeQueryString(v)}>`;
5484
+ }
5485
+ // Numbers/booleans — also stored as literal:string: in AD4M
5486
+ return `<literal:string:${v}>`;
5487
+ }
5473
5488
  if (Array.isArray(condition)) {
5474
- // Array values → IN clause
5475
- const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
5476
- return `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} IN [${formattedValues}]]) > 0`;
5489
+ // Array values → FILTER IN
5490
+ const formattedValues = condition.map(formatValue).join(', ');
5491
+ return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;
5477
5492
  }
5478
5493
  else if (typeof condition === 'object' && condition !== null) {
5479
5494
  // Operator object
@@ -5481,31 +5496,29 @@ function buildWhereCondition(predicate, condition, opts) {
5481
5496
  const parts = [];
5482
5497
  if (ops.not !== undefined) {
5483
5498
  if (Array.isArray(ops.not)) {
5484
- const formattedValues = ops.not.map((v) => formatSurrealValue(v)).join(', ');
5485
- parts.push(`count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
5499
+ const formattedValues = ops.not.map((v) => formatValue(v)).join(', ');
5500
+ parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ?_nval . FILTER(?_nval IN (${formattedValues})) }`);
5486
5501
  }
5487
5502
  else {
5488
- parts.push(`count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`);
5503
+ parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ${formatValue(ops.not)} }`);
5489
5504
  }
5490
5505
  }
5491
- // Comparison operators — ensure property exists (actual comparison
5492
- // may be post-filtered in JS at runtime, but the SurrealQL condition
5493
- // is valid for compile-time getter generation too).
5506
+ // Comparison operators — ensure property exists
5494
5507
  const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
5495
5508
  ops.lt !== undefined || ops.lte !== undefined ||
5496
5509
  ops.between !== undefined || ops.contains !== undefined;
5497
5510
  if (hasComparisonOps) {
5498
- parts.push(`count(->link[WHERE predicate = '${escapedPredicate}']) > 0`);
5511
+ parts.push(`FILTER EXISTS { ?target <${escapedPredicate}> ?_cmp }`);
5499
5512
  }
5500
- return parts.join(' AND ');
5513
+ return parts.join(' ');
5501
5514
  }
5502
5515
  else {
5503
5516
  // Simple equality
5504
- return `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} = ${formatSurrealValue(condition)}]) > 0`;
5517
+ return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
5505
5518
  }
5506
5519
  }
5507
5520
  /**
5508
- * Compile a full `Where` clause to an array of SurrealQL condition strings.
5521
+ * Compile a full `Where` clause to an array of SPARQL condition strings.
5509
5522
  *
5510
5523
  * When `metadata` is provided, property names are resolved to predicates
5511
5524
  * using the model's property metadata. When `metadata` is `null`, property
@@ -5675,7 +5688,7 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
5675
5688
  // ── Constructor / Destructor entries ────────────────────────────
5676
5689
  const effectiveInitial = propMeta.initial
5677
5690
  ?? (propMeta.required && propMeta.writable && !propMeta.flag && propMeta.through
5678
- ? "literal://string:" : undefined);
5691
+ ? "literal:string:" : undefined);
5679
5692
  if (effectiveInitial) {
5680
5693
  constructorActions.push({
5681
5694
  action: "addLink",
@@ -5726,7 +5739,7 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
5726
5739
  // ── Build Getter (conformance filter) ───────────────────────────
5727
5740
  // Priority chain:
5728
5741
  // 1. Explicit getter string → use verbatim
5729
- // 2. `where` clause → compile DSL to SurrealQL getter
5742
+ // 2. `where` clause → compile DSL to SPARQL getter
5730
5743
  // 3. target + filter !== false → auto-derive from shape
5731
5744
  if (relMeta.getter) {
5732
5745
  relShape.getter = relMeta.getter;
@@ -5739,8 +5752,8 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
5739
5752
  : null;
5740
5753
  const conditions = compileWhereClause(relMeta.where, targetMetadata);
5741
5754
  if (conditions.length > 0) {
5742
- const escapedPredicate = escapeSurrealString(relMeta.predicate);
5743
- relShape.getter = `(->link[WHERE predicate = '${escapedPredicate}'].out[WHERE ${conditions.join(' AND ')}].uri)`;
5755
+ const escapedPredicate = escapeQueryString(relMeta.predicate);
5756
+ relShape.getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;
5744
5757
  }
5745
5758
  }
5746
5759
  catch (e) {
@@ -5748,18 +5761,42 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
5748
5761
  }
5749
5762
  }
5750
5763
  else if (relMeta.target && relMeta.filter !== false) {
5751
- try {
5752
- const TargetClass = relMeta.target();
5753
- const filter = conformanceFilterFn(relMeta.predicate, TargetClass);
5754
- if (filter) {
5755
- relShape.getter = filter.getter;
5756
- relShape.conformanceConditions = filter.conformanceConditions;
5764
+ // Lazy conformance filter: store deferred reference,
5765
+ // resolve on first access via a getter on relShape
5766
+ const targetThunk = relMeta.target;
5767
+ const predicate = relMeta.predicate;
5768
+ let resolved = false;
5769
+ let cachedGetter;
5770
+ let cachedConditions;
5771
+ const resolveFilter = () => {
5772
+ if (resolved)
5773
+ return;
5774
+ resolved = true;
5775
+ try {
5776
+ const TargetClass = targetThunk();
5777
+ const filter = conformanceFilterFn(predicate, TargetClass);
5778
+ if (filter) {
5779
+ cachedGetter = filter.getter;
5780
+ cachedConditions = filter.conformanceConditions;
5781
+ }
5757
5782
  }
5758
- }
5759
- catch (e) {
5760
- // Target class may not be available yet — getter will be
5761
- // absent and runtime will fall back to unfiltered get_links
5762
- }
5783
+ catch (e) {
5784
+ // Target class may not be available yet
5785
+ }
5786
+ };
5787
+ // Define lazy getters that resolve on first access
5788
+ Object.defineProperty(relShape, 'getter', {
5789
+ get() { resolveFilter(); return cachedGetter; },
5790
+ set(v) { resolved = true; cachedGetter = v; },
5791
+ enumerable: true,
5792
+ configurable: true,
5793
+ });
5794
+ Object.defineProperty(relShape, 'conformanceConditions', {
5795
+ get() { resolveFilter(); return cachedConditions; },
5796
+ set(v) { resolved = true; cachedConditions = v; },
5797
+ enumerable: true,
5798
+ configurable: true,
5799
+ });
5763
5800
  }
5764
5801
  // ── sh:class — target shape reference ───────────────────────────
5765
5802
  if (relMeta.target) {
@@ -5777,7 +5814,7 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
5777
5814
  shape.addProperty(relShape);
5778
5815
  }
5779
5816
  // Always set constructor and destructor actions on the shape, even
5780
- // when empty. An empty array serialises to `literal://string:[]`
5817
+ // when empty. An empty array serialises to `literal:string:[]`
5781
5818
  // which the Rust executor parses as a valid (no-op) command list,
5782
5819
  // avoiding "No SHACL constructor found" errors for models whose
5783
5820
  // properties are all optional and have no @Flag.
@@ -5793,11 +5830,21 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
5793
5830
  const propertyRegistry = new WeakMap();
5794
5831
  /** Registry of relation metadata keyed by constructor → { propName → metadata } */
5795
5832
  const relationRegistry = new WeakMap();
5833
+ /** Memoisation cache for getPropertiesMetadata — avoids repeated prototype-chain walks */
5834
+ const propertiesMetadataCache = new WeakMap();
5835
+ /** Memoisation cache for getRelationsMetadata — avoids repeated prototype-chain walks */
5836
+ const relationsMetadataCache = new WeakMap();
5837
+ /** Memoisation cache for generateSHACL — avoids recomputing SHACL shapes */
5838
+ const shaclCache = new WeakMap();
5796
5839
  /**
5797
5840
  * Retrieve property metadata for a given class constructor.
5798
5841
  * Walks the prototype chain so subclass decorators compose with parent decorators.
5842
+ * Results are memoised per class constructor.
5799
5843
  */
5800
5844
  function getPropertiesMetadata(ctor) {
5845
+ const cached = propertiesMetadataCache.get(ctor);
5846
+ if (cached)
5847
+ return cached;
5801
5848
  const result = {};
5802
5849
  const chain = [];
5803
5850
  let current = ctor;
@@ -5810,13 +5857,18 @@ function getPropertiesMetadata(ctor) {
5810
5857
  if (meta)
5811
5858
  Object.assign(result, meta);
5812
5859
  }
5860
+ propertiesMetadataCache.set(ctor, result);
5813
5861
  return result;
5814
5862
  }
5815
5863
  /**
5816
5864
  * Retrieve relation metadata for a given class constructor.
5817
5865
  * Walks the prototype chain so subclass decorators compose with parent decorators.
5866
+ * Results are memoised per class constructor.
5818
5867
  */
5819
5868
  function getRelationsMetadata(ctor) {
5869
+ const cached = relationsMetadataCache.get(ctor);
5870
+ if (cached)
5871
+ return cached;
5820
5872
  const result = {};
5821
5873
  const chain = [];
5822
5874
  let current = ctor;
@@ -5829,6 +5881,18 @@ function getRelationsMetadata(ctor) {
5829
5881
  if (meta)
5830
5882
  Object.assign(result, meta);
5831
5883
  }
5884
+ relationsMetadataCache.set(ctor, result);
5885
+ return result;
5886
+ }
5887
+ /**
5888
+ * Get or compute memoised SHACL for a class. Used by @Model decorator.
5889
+ */
5890
+ function getMemoizedSHACL(target, compute) {
5891
+ const cached = shaclCache.get(target);
5892
+ if (cached)
5893
+ return cached;
5894
+ const result = compute();
5895
+ shaclCache.set(target, result);
5832
5896
  return result;
5833
5897
  }
5834
5898
  /**
@@ -5854,7 +5918,7 @@ function setRelationRegistryEntry(ctor, relName, meta) {
5854
5918
  *
5855
5919
  * Inspects the target class's property metadata to derive:
5856
5920
  * - `conformanceConditions`: Structured, DB-agnostic conditions (flag & required checks)
5857
- * - `getter`: Pre-computed SurrealQL expression that traverses outgoing links and filters
5921
+ * - `getter`: Pre-computed graph traversal expression that traverses outgoing links and filters
5858
5922
  * target nodes to only those conforming to the target shape.
5859
5923
  *
5860
5924
  * @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
@@ -5865,7 +5929,8 @@ function buildConformanceFilter(relationPredicate, targetClass) {
5865
5929
  try {
5866
5930
  const targetProps = getPropertiesMetadata(targetClass);
5867
5931
  const conditions = [];
5868
- const surrealConditions = [];
5932
+ const sparqlConditions = [];
5933
+ let varIdx = 0;
5869
5934
  // 1. Flags — check predicate + value
5870
5935
  for (const [_propName, propMeta] of Object.entries(targetProps)) {
5871
5936
  if (propMeta.flag && propMeta.initial && propMeta.through) {
@@ -5874,7 +5939,7 @@ function buildConformanceFilter(relationPredicate, targetClass) {
5874
5939
  predicate: propMeta.through,
5875
5940
  value: propMeta.initial,
5876
5941
  });
5877
- surrealConditions.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.through)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
5942
+ sparqlConditions.push(`?target <${escapeQueryString(propMeta.through)}> <${escapeQueryString(propMeta.initial)}> .`);
5878
5943
  }
5879
5944
  }
5880
5945
  // 2. Required (non-flag) properties — check predicate exists
@@ -5885,14 +5950,13 @@ function buildConformanceFilter(relationPredicate, targetClass) {
5885
5950
  type: 'required',
5886
5951
  predicate: propMeta.through,
5887
5952
  });
5888
- surrealConditions.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.through)}']) > 0`);
5953
+ sparqlConditions.push(`?target <${escapeQueryString(propMeta.through)}> ?_v${varIdx++} .`);
5889
5954
  }
5890
5955
  }
5891
5956
  if (conditions.length === 0) {
5892
5957
  return undefined;
5893
5958
  }
5894
- const escapedPredicate = escapeSurrealString(relationPredicate);
5895
- const getter = `(->link[WHERE predicate = '${escapedPredicate}'].out[WHERE ${surrealConditions.join(' AND ')}].uri)`;
5959
+ const getter = `SELECT ?target WHERE { <Base> <${escapeQueryString(relationPredicate)}> ?target . ${sparqlConditions.join(' ')} }`;
5896
5960
  return { getter, conformanceConditions: conditions };
5897
5961
  }
5898
5962
  catch (e) {
@@ -5913,8 +5977,8 @@ function applyPropertyMetadata(opts) {
5913
5977
  if (opts.required && !opts.initial) {
5914
5978
  throw new Error("SubjectProperty requires an 'initial' option if 'required' is true");
5915
5979
  }
5916
- if (!opts.through && !opts.prologGetter) {
5917
- throw new Error("SubjectProperty requires either 'through' or 'prologGetter' option");
5980
+ if (!opts.through && !opts.prologGetter && !opts.getter) {
5981
+ throw new Error("SubjectProperty requires either 'through' or 'prologGetter' or 'getter' option");
5918
5982
  }
5919
5983
  // Write to WeakMap registry (keyed by constructor)
5920
5984
  const ctor = target.constructor;
@@ -6099,7 +6163,7 @@ function Model(opts) {
6099
6163
  return buildSDNA(opts.name, target.prototype, getPropertiesMetadata(target), getRelationsMetadata(target));
6100
6164
  };
6101
6165
  target.generateSHACL = function () {
6102
- return buildSHACL(opts.name, target, getPropertiesMetadata(target), getRelationsMetadata(target), buildConformanceFilter);
6166
+ return getMemoizedSHACL(target, () => buildSHACL(opts.name, target, getPropertiesMetadata(target), getRelationsMetadata(target), buildConformanceFilter));
6103
6167
  };
6104
6168
  Object.defineProperty(target, 'type', { configurable: true });
6105
6169
  };
@@ -6122,7 +6186,7 @@ function Model(opts) {
6122
6186
  * Properties are optional by default. When a model instance is created without
6123
6187
  * providing a value for an optional property, no link is added to the graph.
6124
6188
  * Set `required: true` explicitly when a property must always be present (this
6125
- * also adds a `"literal://string:uninitialized"` sentinel as the initial value
6189
+ * also adds a `"literal:string:uninitialized"` sentinel as the initial value
6126
6190
  * so that the SDNA constructor creates a placeholder link).
6127
6191
  *
6128
6192
  * @example
@@ -6161,7 +6225,7 @@ function Model(opts) {
6161
6225
  * @param {PropertyOptions} opts - Property configuration
6162
6226
  * @param {string} opts.through - The predicate URI for the property
6163
6227
  * @param {boolean} [opts.required=false] - Whether the property is required (adds query filters and sentinel initial value)
6164
- * @param {string} [opts.initial] - Initial value (defaults to "literal://string:uninitialized" when required)
6228
+ * @param {string} [opts.initial] - Initial value (defaults to "literal:string:uninitialized" when required)
6165
6229
  * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
6166
6230
  * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
6167
6231
  * @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
@@ -6174,7 +6238,7 @@ function Property(opts) {
6174
6238
  required,
6175
6239
  readOnly: opts.readOnly ?? false,
6176
6240
  resolveLanguage: opts.resolveLanguage ?? "literal",
6177
- initial: opts.initial ?? (required ? "literal://string:uninitialized" : undefined),
6241
+ initial: opts.initial ?? (required ? "literal:string:uninitialized" : undefined),
6178
6242
  });
6179
6243
  }
6180
6244
  /**
@@ -6263,7 +6327,7 @@ function resolveRelationArgs(first, second) {
6263
6327
  }
6264
6328
  if (opts.where) {
6265
6329
  throw new Error('Relation decorator: `where` and `getter` are mutually exclusive. ' +
6266
- 'Use `where` for DSL-based filtering, or `getter` for raw SurrealQL.');
6330
+ 'Use `where` for DSL-based filtering, or `getter` for raw getter expression.');
6267
6331
  }
6268
6332
  return opts;
6269
6333
  }
@@ -6406,6 +6470,73 @@ function BelongsToMany(first, second) {
6406
6470
  };
6407
6471
  }
6408
6472
 
6473
+ /**
6474
+ * Query Result TTL Cache
6475
+ *
6476
+ * Short-lived cache (200ms TTL) for SPARQL query results.
6477
+ * Prevents redundant queries during rapid render cycles where
6478
+ * multiple components issue the same query within milliseconds.
6479
+ *
6480
+ * Key: `perspectiveUUID + queryText`
6481
+ */
6482
+ const cache = new Map();
6483
+ const DEFAULT_TTL_MS = 200;
6484
+ function makeKey$1(perspectiveUUID, queryText) {
6485
+ return `${perspectiveUUID}:${queryText}`;
6486
+ }
6487
+ /**
6488
+ * Get a cached query result if it exists and hasn't expired.
6489
+ */
6490
+ function getCachedResult(perspectiveUUID, queryText) {
6491
+ const key = makeKey$1(perspectiveUUID, queryText);
6492
+ const entry = cache.get(key);
6493
+ if (!entry)
6494
+ return undefined;
6495
+ if (Date.now() > entry.expiry) {
6496
+ cache.delete(key);
6497
+ return undefined;
6498
+ }
6499
+ return entry.result;
6500
+ }
6501
+ /**
6502
+ * Store a query result in the cache with TTL.
6503
+ */
6504
+ function setCachedResult(perspectiveUUID, queryText, result, ttlMs = DEFAULT_TTL_MS) {
6505
+ // Lazy eviction of expired entries
6506
+ const now = Date.now();
6507
+ for (const [key, entry] of cache) {
6508
+ if (now > entry.expiry) {
6509
+ cache.delete(key);
6510
+ }
6511
+ }
6512
+ const cacheKey = makeKey$1(perspectiveUUID, queryText);
6513
+ cache.set(cacheKey, { result, expiry: now + ttlMs });
6514
+ }
6515
+ /**
6516
+ * Invalidate all cache entries for a given perspective.
6517
+ * Called after write operations to ensure stale data isn't served.
6518
+ */
6519
+ function invalidatePerspectiveCache(perspectiveUUID) {
6520
+ const prefix = perspectiveUUID + ':';
6521
+ for (const [key] of cache) {
6522
+ if (key.startsWith(prefix)) {
6523
+ cache.delete(key);
6524
+ }
6525
+ }
6526
+ }
6527
+ /**
6528
+ * Clear all cache entries (useful for testing).
6529
+ */
6530
+ function clearQueryCache() {
6531
+ cache.clear();
6532
+ }
6533
+ /**
6534
+ * Get the current size of the cache (useful for testing).
6535
+ */
6536
+ function queryCacheSize() {
6537
+ return cache.size;
6538
+ }
6539
+
6409
6540
  /**
6410
6541
  * SHACL Flow - represents a state machine for AD4M expressions
6411
6542
  *
@@ -6521,7 +6652,7 @@ class SHACLFlow {
6521
6652
  }
6522
6653
  /**
6523
6654
  * Serialize the flow to AD4M links
6524
- * These links can be stored in a perspective and queried via SurrealDB
6655
+ * These links can be stored in a perspective and queried via SPARQL
6525
6656
  *
6526
6657
  * @returns Array of Link objects representing the flow
6527
6658
  */
@@ -6552,7 +6683,7 @@ class SHACLFlow {
6552
6683
  links.push({
6553
6684
  source: flowUri,
6554
6685
  predicate: "ad4m://flowable",
6555
- target: `literal://string:${encodeURIComponent(JSON.stringify(this.flowable))}`
6686
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.flowable))}`
6556
6687
  });
6557
6688
  }
6558
6689
  // Start action
@@ -6560,7 +6691,7 @@ class SHACLFlow {
6560
6691
  links.push({
6561
6692
  source: flowUri,
6562
6693
  predicate: "ad4m://startAction",
6563
- target: `literal://string:${encodeURIComponent(JSON.stringify(this.startAction))}`
6694
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.startAction))}`
6564
6695
  });
6565
6696
  }
6566
6697
  // States
@@ -6594,7 +6725,7 @@ class SHACLFlow {
6594
6725
  links.push({
6595
6726
  source: stateUri,
6596
6727
  predicate: "ad4m://stateCheck",
6597
- target: `literal://string:${encodeURIComponent(JSON.stringify(state.stateCheck))}`
6728
+ target: `literal:string:${encodeURIComponent(JSON.stringify(state.stateCheck))}`
6598
6729
  });
6599
6730
  }
6600
6731
  // Transitions
@@ -6636,7 +6767,7 @@ class SHACLFlow {
6636
6767
  links.push({
6637
6768
  source: transitionUri,
6638
6769
  predicate: "ad4m://transitionActions",
6639
- target: `literal://string:${encodeURIComponent(JSON.stringify(transition.actions))}`
6770
+ target: `literal:string:${encodeURIComponent(JSON.stringify(transition.actions))}`
6640
6771
  });
6641
6772
  }
6642
6773
  return links;
@@ -6668,7 +6799,7 @@ class SHACLFlow {
6668
6799
  }
6669
6800
  else {
6670
6801
  try {
6671
- const jsonStr = flowableLink.target.replace('literal://string:', '');
6802
+ const jsonStr = flowableLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
6672
6803
  flow.flowable = JSON.parse(decodeURIComponent(jsonStr));
6673
6804
  }
6674
6805
  catch {
@@ -6680,7 +6811,7 @@ class SHACLFlow {
6680
6811
  const startActionLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://startAction");
6681
6812
  if (startActionLink) {
6682
6813
  try {
6683
- const jsonStr = startActionLink.target.replace('literal://string:', '');
6814
+ const jsonStr = startActionLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
6684
6815
  flow.startAction = JSON.parse(decodeURIComponent(jsonStr));
6685
6816
  }
6686
6817
  catch {
@@ -6706,7 +6837,7 @@ class SHACLFlow {
6706
6837
  let stateCheck = { predicate: "", target: "" };
6707
6838
  if (checkLink) {
6708
6839
  try {
6709
- const jsonStr = checkLink.target.replace('literal://string:', '');
6840
+ const jsonStr = checkLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
6710
6841
  stateCheck = JSON.parse(decodeURIComponent(jsonStr));
6711
6842
  }
6712
6843
  catch {
@@ -6735,7 +6866,7 @@ class SHACLFlow {
6735
6866
  let actions = [];
6736
6867
  if (actionsLink) {
6737
6868
  try {
6738
- const jsonStr = actionsLink.target.replace('literal://string:', '');
6869
+ const jsonStr = actionsLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
6739
6870
  actions = JSON.parse(decodeURIComponent(jsonStr));
6740
6871
  }
6741
6872
  catch {
@@ -6787,7 +6918,7 @@ var __classPrivateFieldGet$9 = (undefined && undefined.__classPrivateFieldGet) |
6787
6918
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
6788
6919
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6789
6920
  };
6790
- var _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initResolve, _QuerySubscriptionProxy_initReject, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_query, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks;
6921
+ var _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initResolve, _QuerySubscriptionProxy_initReject, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_query, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, _PerspectiveProxy_ensuredSubjectClasses;
6791
6922
  /** Proxy object for a subscribed Prolog query that provides real-time updates
6792
6923
  *
6793
6924
  * This class handles:
@@ -6842,7 +6973,6 @@ class QuerySubscriptionProxy {
6842
6973
  _QuerySubscriptionProxy_initReject.set(this, void 0);
6843
6974
  _QuerySubscriptionProxy_initTimeoutId.set(this, void 0);
6844
6975
  _QuerySubscriptionProxy_query.set(this, void 0);
6845
- this.isSurrealDB = false;
6846
6976
  __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_uuid, uuid, "f");
6847
6977
  __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_query, query, "f");
6848
6978
  __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_client, client, "f");
@@ -6873,12 +7003,7 @@ class QuerySubscriptionProxy {
6873
7003
  try {
6874
7004
  // Initialize the query subscription
6875
7005
  let initialResult;
6876
- if (this.isSurrealDB) {
6877
- initialResult = await __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").perspectiveSubscribeSurrealQuery(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_query, "f"));
6878
- }
6879
- else {
6880
- initialResult = await __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_query, "f"));
6881
- }
7006
+ initialResult = await __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_query, "f"));
6882
7007
  __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_subscriptionId, initialResult.subscriptionId, "f");
6883
7008
  // Process the initial result immediately for fast UX
6884
7009
  if (initialResult.result) {
@@ -6931,12 +7056,7 @@ class QuerySubscriptionProxy {
6931
7056
  if (__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_disposed, "f"))
6932
7057
  return;
6933
7058
  try {
6934
- if (this.isSurrealDB) {
6935
- await __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").perspectiveKeepAliveSurrealQuery(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f"));
6936
- }
6937
- else {
6938
- await __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f"));
6939
- }
7059
+ await __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f"));
6940
7060
  }
6941
7061
  catch (e) {
6942
7062
  console.error('Error in keepalive:', e);
@@ -7043,14 +7163,8 @@ class QuerySubscriptionProxy {
7043
7163
  }
7044
7164
  // Tell the backend to dispose of the subscription
7045
7165
  if (__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f")) {
7046
- if (this.isSurrealDB) {
7047
- __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").perspectiveDisposeSurrealQuerySubscription(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f"))
7048
- .catch(e => console.error('Error disposing surreal query subscription:', e));
7049
- }
7050
- else {
7051
- __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f"))
7052
- .catch(e => console.error('Error disposing query subscription:', e));
7053
- }
7166
+ __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f"))
7167
+ .catch(e => console.error('Error disposing query subscription:', e));
7054
7168
  }
7055
7169
  }
7056
7170
  }
@@ -7115,6 +7229,12 @@ class PerspectiveProxy {
7115
7229
  _PerspectiveProxy_perspectiveLinkRemovedCallbacks.set(this, void 0);
7116
7230
  _PerspectiveProxy_perspectiveLinkUpdatedCallbacks.set(this, void 0);
7117
7231
  _PerspectiveProxy_perspectiveSyncStateChangeCallbacks.set(this, void 0);
7232
+ _PerspectiveProxy_ensuredSubjectClasses.set(this, new Set()
7233
+ /**
7234
+ * Creates a new PerspectiveProxy instance.
7235
+ * Note: Don't create this directly, use ad4m.perspective.add() instead.
7236
+ */
7237
+ );
7118
7238
  __classPrivateFieldSet$9(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, [], "f");
7119
7239
  __classPrivateFieldSet$9(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, [], "f");
7120
7240
  __classPrivateFieldSet$9(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, [], "f");
@@ -7205,7 +7325,9 @@ class PerspectiveProxy {
7205
7325
  * @param batchId - Optional batch ID to group this operation with others
7206
7326
  */
7207
7327
  async executeAction(actions, expression, parameters, batchId) {
7208
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").executeCommands(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId);
7328
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").executeCommands(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId);
7329
+ invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
7330
+ return result;
7209
7331
  }
7210
7332
  /**
7211
7333
  * Retrieves links from the perspective that match the given query.
@@ -7258,34 +7380,28 @@ class PerspectiveProxy {
7258
7380
  return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").queryProlog(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, query);
7259
7381
  }
7260
7382
  /**
7261
- * Executes a SurrealQL query against the perspective's link cache.
7262
- * This allows powerful SQL-like queries on the link data stored in SurrealDB.
7383
+ * Executes a SPARQL query against the perspective's link cache.
7384
+ * This allows powerful SQL-like queries on the link data stored in SPARQL.
7263
7385
  *
7264
7386
  * **Security Note:** Only read-only queries (SELECT, RETURN, etc.) are permitted.
7265
7387
  * Mutating operations (DELETE, UPDATE, INSERT, CREATE, DROP, DEFINE, etc.) are
7266
7388
  * blocked for security reasons. Use the perspective's add/remove methods to modify links.
7267
7389
  *
7268
- * @param query - SurrealQL query string (read-only operations only)
7390
+ * @param query - SPARQL query string (read-only operations only)
7269
7391
  * @returns Query results as parsed JSON
7270
7392
  *
7271
- * @example
7272
- * ```typescript
7273
- * // Get all links
7274
- * const links = await perspective.querySurrealDB('SELECT * FROM link');
7393
+ * Executes a SPARQL query against the perspective's RDF (Oxigraph) store.
7275
7394
  *
7276
- * // Filter links by predicate
7277
- * const follows = await perspective.querySurrealDB(
7278
- * "SELECT * FROM link WHERE predicate = 'follows'"
7279
- * );
7280
- *
7281
- * // Complex aggregation query
7282
- * const stats = await perspective.querySurrealDB(
7283
- * "SELECT predicate, count() as total FROM link GROUP BY predicate"
7284
- * );
7285
- * ```
7395
+ * @param query - SPARQL query string
7396
+ * @returns Query results as parsed JSON
7286
7397
  */
7287
- async querySurrealDB(query) {
7288
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").querySurrealDB(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, query);
7398
+ async querySparql(query) {
7399
+ const cached = getCachedResult(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, query);
7400
+ if (cached !== undefined)
7401
+ return cached;
7402
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").querySparql(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, query);
7403
+ setCachedResult(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, query, result);
7404
+ return result;
7289
7405
  }
7290
7406
  /**
7291
7407
  * Adds a new link to the perspective.
@@ -7313,7 +7429,9 @@ class PerspectiveProxy {
7313
7429
  * ```
7314
7430
  */
7315
7431
  async add(link, status = 'shared', batchId) {
7316
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").addLink(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
7432
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").addLink(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
7433
+ invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
7434
+ return result;
7317
7435
  }
7318
7436
  /**
7319
7437
  * Adds multiple links to the perspective in a single operation.
@@ -7325,7 +7443,9 @@ class PerspectiveProxy {
7325
7443
  * @returns Array of created LinkExpressions
7326
7444
  */
7327
7445
  async addLinks(links, status = 'shared', batchId) {
7328
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").addLinks(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, links, status, batchId);
7446
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").addLinks(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, links, status, batchId);
7447
+ invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
7448
+ return result;
7329
7449
  }
7330
7450
  /**
7331
7451
  * Removes multiple links from the perspective.
@@ -7335,7 +7455,9 @@ class PerspectiveProxy {
7335
7455
  * @returns Array of removed LinkExpressions
7336
7456
  */
7337
7457
  async removeLinks(links, batchId) {
7338
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").removeLinks(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, links, batchId);
7458
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").removeLinks(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, links, batchId);
7459
+ invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
7460
+ return result;
7339
7461
  }
7340
7462
  /**
7341
7463
  * Applies a set of link mutations (adds and removes) in a single operation.
@@ -7346,7 +7468,9 @@ class PerspectiveProxy {
7346
7468
  * @returns Object containing results of the mutations
7347
7469
  */
7348
7470
  async linkMutations(mutations, status = 'shared') {
7349
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").linkMutations(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, mutations, status);
7471
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").linkMutations(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, mutations, status);
7472
+ invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
7473
+ return result;
7350
7474
  }
7351
7475
  /**
7352
7476
  * Adds a pre-signed LinkExpression to the perspective.
@@ -7367,7 +7491,9 @@ class PerspectiveProxy {
7367
7491
  * @param batchId - Optional batch ID to group this operation with others
7368
7492
  */
7369
7493
  async update(oldLink, newLink, batchId) {
7370
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").updateLink(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, oldLink, newLink, batchId);
7494
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").updateLink(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, oldLink, newLink, batchId);
7495
+ invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
7496
+ return result;
7371
7497
  }
7372
7498
  /**
7373
7499
  * Removes a link from the perspective.
@@ -7376,7 +7502,9 @@ class PerspectiveProxy {
7376
7502
  * @param batchId - Optional batch ID to group this operation with others
7377
7503
  */
7378
7504
  async remove(link, batchId) {
7379
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, link, batchId);
7505
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, link, batchId);
7506
+ invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
7507
+ return result;
7380
7508
  }
7381
7509
  /** Creates a new batch for grouping operations */
7382
7510
  async createBatch() {
@@ -7384,7 +7512,9 @@ class PerspectiveProxy {
7384
7512
  }
7385
7513
  /** Commits a batch of operations */
7386
7514
  async commitBatch(batchId) {
7387
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").commitBatch(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, batchId);
7515
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").commitBatch(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, batchId);
7516
+ invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
7517
+ return result;
7388
7518
  }
7389
7519
  /**
7390
7520
  * Retrieves and renders an Expression referenced in this perspective.
@@ -7759,6 +7889,13 @@ class PerspectiveProxy {
7759
7889
  async addSdna(name, sdnaCode, sdnaType, shaclJson) {
7760
7890
  return __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").addSdna(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, name, sdnaCode, sdnaType, shaclJson);
7761
7891
  }
7892
+ /**
7893
+ * Adds a subject class to the perspective.
7894
+ * Alias for addSdna() with sdnaType='subject_class'.
7895
+ */
7896
+ async addSubjectClass(name, shaclJson) {
7897
+ return this.addSdna(name, '', 'subject_class', shaclJson);
7898
+ }
7762
7899
  /**
7763
7900
  * **Recommended way to add SDNA schemas.**
7764
7901
  *
@@ -7790,7 +7927,7 @@ class PerspectiveProxy {
7790
7927
  // Serialize shape to links
7791
7928
  const shapeLinks = shape.toLinks();
7792
7929
  // Create name -> shape mapping links
7793
- const nameMapping = Literal.fromUrl(`literal://string:shacl://${name}`);
7930
+ const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);
7794
7931
  const allLinks = [
7795
7932
  ...shapeLinks.map(l => new exports.Link({
7796
7933
  source: l.source,
@@ -7816,7 +7953,7 @@ class PerspectiveProxy {
7816
7953
  */
7817
7954
  async getShacl(name) {
7818
7955
  // Find the shape URI from the name mapping
7819
- const nameMapping = Literal.fromUrl(`literal://string:shacl://${name}`);
7956
+ const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);
7820
7957
  const shapeUriLinks = await this.get(new exports.LinkQuery({
7821
7958
  source: nameMapping.toUrl(),
7822
7959
  predicate: "ad4m://shacl_shape_uri"
@@ -7825,22 +7962,25 @@ class PerspectiveProxy {
7825
7962
  return null;
7826
7963
  }
7827
7964
  const shapeUri = shapeUriLinks[0].data.target;
7828
- escapeSurrealString(shapeUri);
7829
7965
  // First get property shape URIs so we can query everything in one go
7830
7966
  const propertyLinks = await this.get(new exports.LinkQuery({
7831
7967
  source: shapeUri,
7832
7968
  predicate: "sh://property"
7833
7969
  }));
7834
- // Build a single surreal query that fetches all relevant links
7970
+ // Fetch all links from the shape and its property shapes
7835
7971
  const sourceUris = [shapeUri, ...propertyLinks.map(l => l.data.target)];
7836
- const escapedSources = sourceUris.map(u => `'${escapeSurrealString(u)}'`).join(', ');
7837
- const query = `SELECT in.uri AS source, predicate, out.uri AS target FROM link WHERE in.uri IN [${escapedSources}]`;
7838
- const result = await this.querySurrealDB(query);
7839
- const shapeLinks = (result || []).map((r) => ({
7840
- source: r.source,
7841
- predicate: r.predicate,
7842
- target: r.target
7843
- }));
7972
+ const allLinks = [];
7973
+ for (const uri of sourceUris) {
7974
+ const links = await this.get(new exports.LinkQuery({ source: uri }));
7975
+ for (const l of links) {
7976
+ allLinks.push({
7977
+ source: l.data.source,
7978
+ predicate: l.data.predicate,
7979
+ target: l.data.target
7980
+ });
7981
+ }
7982
+ }
7983
+ const shapeLinks = allLinks;
7844
7984
  return SHACLShape.fromLinks(shapeLinks, shapeUri);
7845
7985
  }
7846
7986
  /**
@@ -7942,19 +8082,20 @@ class PerspectiveProxy {
7942
8082
  return null;
7943
8083
  }
7944
8084
  const flowUri = flowUriLinks[0].data.target;
7945
- const escapedFlowUri = escapeSurrealString(flowUri);
7946
8085
  // Compute alternate prefix for state/transition URIs
7947
8086
  const alternatePrefix = flowUri.endsWith('Flow')
7948
8087
  ? flowUri.slice(0, -4) + '.'
7949
8088
  : flowUri + '.';
7950
- const escapedAltPrefix = escapeSurrealString(alternatePrefix);
7951
- // Single surreal query to get all flow-related links
7952
- 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}')`;
7953
- const result = await this.querySurrealDB(query);
7954
- const flowLinks = (result || []).map((r) => ({
7955
- source: r.source,
7956
- predicate: r.predicate,
7957
- target: r.target
8089
+ // Fetch flow links using SPARQL to match flowUri source OR alternatePrefix sources
8090
+ const sparqlQuery = `SELECT ?s ?p ?o WHERE {
8091
+ ?s ?p ?o .
8092
+ FILTER(?s = <${flowUri}> || STRSTARTS(STR(?s), "${alternatePrefix}"))
8093
+ }`;
8094
+ const sparqlResult = await this.querySparql(sparqlQuery);
8095
+ const flowLinks = (sparqlResult || []).map((r) => ({
8096
+ source: r.s,
8097
+ predicate: r.p,
8098
+ target: r.o
7958
8099
  }));
7959
8100
  return SHACLFlow.fromLinks(flowLinks, flowUri);
7960
8101
  }
@@ -8063,8 +8204,8 @@ class PerspectiveProxy {
8063
8204
  const links = await this.get(new exports.LinkQuery({ predicate }));
8064
8205
  for (const link of links) {
8065
8206
  if (shapePattern.test(link.data.source)) {
8066
- // Parse actions from literal://string:{json}
8067
- const prefix = "literal://string:";
8207
+ // Parse actions from literal:string:{json}
8208
+ const prefix = "literal:string:";
8068
8209
  if (link.data.target.startsWith(prefix)) {
8069
8210
  const jsonStr = link.data.target.slice(prefix.length);
8070
8211
  // Decode URL-encoded JSON if needed, with fallback for raw % characters
@@ -8120,35 +8261,20 @@ class PerspectiveProxy {
8120
8261
  }
8121
8262
  // If no required triples, any expression with links is an instance
8122
8263
  if (metadata.requiredTriples.length === 0) {
8123
- const escapedExpression = escapeSurrealString(expression);
8124
- const checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}'`;
8125
- const result = await this.querySurrealDB(checkQuery);
8126
- const count = result[0]?.count ?? 0;
8127
- const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
8128
- return countValue > 0;
8264
+ const links = await this.get(new exports.LinkQuery({ source: expression }));
8265
+ return links.length > 0;
8129
8266
  }
8130
8267
  // Check if the expression has all required triples (predicate + optional exact target)
8131
8268
  for (const triple of metadata.requiredTriples) {
8132
- const escapedExpression = escapeSurrealString(expression);
8133
- const escapedPredicate = escapeSurrealString(triple.predicate);
8134
- let checkQuery;
8269
+ let query;
8135
8270
  if (triple.target) {
8136
- // Flag: must match both predicate AND exact target value
8137
- const escapedTarget = escapeSurrealString(triple.target);
8138
- checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}' AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}'`;
8271
+ query = new exports.LinkQuery({ source: expression, predicate: triple.predicate, target: triple.target });
8139
8272
  }
8140
8273
  else {
8141
- // Property: just check predicate exists
8142
- checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}' AND predicate = '${escapedPredicate}'`;
8274
+ query = new exports.LinkQuery({ source: expression, predicate: triple.predicate });
8143
8275
  }
8144
- const result = await this.querySurrealDB(checkQuery);
8145
- if (!result || result.length === 0) {
8146
- return false;
8147
- }
8148
- const count = result[0]?.count ?? 0;
8149
- // Handle potential object response like {Int: 0}
8150
- const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
8151
- if (countValue === 0) {
8276
+ const links = await this.get(query);
8277
+ if (!links || links.length === 0) {
8152
8278
  return false;
8153
8279
  }
8154
8280
  }
@@ -8176,6 +8302,10 @@ class PerspectiveProxy {
8176
8302
  * Gets subject class metadata from SHACL links using SHACLShape.fromLinks().
8177
8303
  * Retrieves the SHACL shape and extracts metadata for instance queries.
8178
8304
  */
8305
+ async getSubjectClassMetadata(className) {
8306
+ return this.getSubjectClassMetadataFromSDNA(className);
8307
+ }
8308
+ /** @deprecated Use getSubjectClassMetadata() */
8179
8309
  async getSubjectClassMetadataFromSDNA(className) {
8180
8310
  try {
8181
8311
  // Use getShacl() to retrieve the shape via SHACLShape.fromLinks()
@@ -8230,33 +8360,55 @@ class PerspectiveProxy {
8230
8360
  }
8231
8361
  }
8232
8362
  /**
8233
- * Generates a SurrealDB query to find instances based on class metadata.
8363
+ * Generates a SPARQL query to find instances based on class metadata.
8364
+ */
8365
+ /**
8366
+ * Finds all instances matching subject class metadata by querying links.
8367
+ * Returns base URIs of matching instances.
8234
8368
  */
8235
- generateSurrealInstanceQuery(metadata) {
8369
+ async findInstancesByMetadata(metadata) {
8236
8370
  if (metadata.requiredTriples.length === 0) {
8237
- // No required triples - any node with links is an instance
8238
- return `SELECT DISTINCT uri AS base FROM node WHERE count(->link) > 0`;
8371
+ // No required triples - return all unique sources that have any link
8372
+ const allLinks = await this.get(new exports.LinkQuery({}));
8373
+ const sources = new Set(allLinks.map(l => l.data.source));
8374
+ return Array.from(sources).map(s => ({ base: s }));
8239
8375
  }
8240
- // Generate WHERE conditions for each required triple (predicate + optional exact target)
8241
- const whereConditions = metadata.requiredTriples.map(triple => {
8242
- const escapedPredicate = escapeSurrealString(triple.predicate);
8243
- if (triple.target) {
8244
- // Flag: must match both predicate AND exact target value
8245
- const escapedTarget = escapeSurrealString(triple.target);
8246
- return `count(->link[WHERE predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}']) > 0`;
8247
- }
8248
- else {
8249
- // Property: just check predicate exists
8250
- return `count(->link[WHERE predicate = '${escapedPredicate}']) > 0`;
8376
+ // Use first required triple to get candidate set, then filter by rest
8377
+ const first = metadata.requiredTriples[0];
8378
+ let query;
8379
+ if (first.target) {
8380
+ query = new exports.LinkQuery({ predicate: first.predicate, target: first.target });
8381
+ }
8382
+ else {
8383
+ query = new exports.LinkQuery({ predicate: first.predicate });
8384
+ }
8385
+ const candidateLinks = await this.get(query);
8386
+ let candidates = [...new Set(candidateLinks.map(l => l.data.source))];
8387
+ // Filter by remaining required triples
8388
+ for (let i = 1; i < metadata.requiredTriples.length; i++) {
8389
+ const triple = metadata.requiredTriples[i];
8390
+ const remaining = [];
8391
+ for (const expr of candidates) {
8392
+ let q;
8393
+ if (triple.target) {
8394
+ q = new exports.LinkQuery({ source: expr, predicate: triple.predicate, target: triple.target });
8395
+ }
8396
+ else {
8397
+ q = new exports.LinkQuery({ source: expr, predicate: triple.predicate });
8398
+ }
8399
+ const links = await this.get(q);
8400
+ if (links.length > 0)
8401
+ remaining.push(expr);
8251
8402
  }
8252
- }).join(' AND ');
8253
- return `SELECT uri AS base FROM node WHERE ${whereConditions}`;
8403
+ candidates = remaining;
8404
+ }
8405
+ return candidates.map(c => ({ base: c }));
8254
8406
  }
8255
8407
  /**
8256
- * Gets a property value using SurrealDB when Prolog fails.
8408
+ * Gets a property value using SPARQL when Prolog fails.
8257
8409
  * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
8258
8410
  */
8259
- async getPropertyValueViaSurreal(baseExpression, className, propertyName) {
8411
+ async getPropertyValueViaSparql(baseExpression, className, propertyName) {
8260
8412
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
8261
8413
  if (!metadata) {
8262
8414
  return undefined;
@@ -8265,14 +8417,11 @@ class PerspectiveProxy {
8265
8417
  if (!propMeta) {
8266
8418
  return undefined;
8267
8419
  }
8268
- const escapedBaseExpression = escapeSurrealString(baseExpression);
8269
- const escapedPredicate = escapeSurrealString(propMeta.predicate);
8270
- const query = `SELECT out.uri AS value FROM link WHERE in.uri = '${escapedBaseExpression}' AND predicate = '${escapedPredicate}' LIMIT 1`;
8271
- const result = await this.querySurrealDB(query);
8272
- if (!result || result.length === 0) {
8420
+ const links = await this.get(new exports.LinkQuery({ source: baseExpression, predicate: propMeta.predicate }));
8421
+ if (!links || links.length === 0) {
8273
8422
  return undefined;
8274
8423
  }
8275
- const value = result[0].value;
8424
+ const value = links[0].data.target;
8276
8425
  // Handle expression resolution if needed
8277
8426
  if (propMeta.resolveLanguage && value) {
8278
8427
  try {
@@ -8291,11 +8440,11 @@ class PerspectiveProxy {
8291
8440
  return value;
8292
8441
  }
8293
8442
  /**
8294
- * Gets relation values using SurrealDB when Prolog fails.
8443
+ * Gets relation values using SPARQL when Prolog fails.
8295
8444
  * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
8296
8445
  * Note: This is used by Subject.ts (legacy pattern). Ad4mModel.ts uses getModelMetadata() instead.
8297
8446
  */
8298
- async getRelationValuesViaSurreal(baseExpression, className, relationName) {
8447
+ async getRelationValuesViaSparql(baseExpression, className, relationName) {
8299
8448
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
8300
8449
  if (!metadata) {
8301
8450
  return [];
@@ -8304,14 +8453,13 @@ class PerspectiveProxy {
8304
8453
  if (!relMeta) {
8305
8454
  return [];
8306
8455
  }
8307
- const escapedBaseExpression = escapeSurrealString(baseExpression);
8308
- const escapedPredicate = escapeSurrealString(relMeta.predicate);
8309
- const query = `SELECT out.uri AS value, timestamp FROM link WHERE in.uri = '${escapedBaseExpression}' AND predicate = '${escapedPredicate}' ORDER BY timestamp ASC`;
8310
- const result = await this.querySurrealDB(query);
8311
- if (!result || result.length === 0) {
8456
+ const links = await this.get(new exports.LinkQuery({ source: baseExpression, predicate: relMeta.predicate }));
8457
+ if (!links || links.length === 0) {
8312
8458
  return [];
8313
8459
  }
8314
- let values = result.map(r => r.value).filter(v => v !== "" && v !== '');
8460
+ // Sort by timestamp ascending
8461
+ links.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
8462
+ let values = links.map(l => l.data.target).filter(v => v !== "" && v !== '');
8315
8463
  // Apply condition filtering if present
8316
8464
  if (relMeta.condition && values.length > 0) {
8317
8465
  try {
@@ -8321,13 +8469,28 @@ class PerspectiveProxy {
8321
8469
  .replace(/\$perspective/g, `'${this.uuid}'`)
8322
8470
  .replace(/\$base/g, `'${baseExpression}'`)
8323
8471
  .replace(/Target/g, `'${value.replace(/'/g, "\\'")}'`);
8324
- // If condition starts with WHERE, wrap in array length check
8325
- if (condition.trim().startsWith('WHERE')) {
8326
- condition = `array::len(SELECT * FROM link ${condition}) > 0`;
8472
+ // Parse condition to extract link query parameters
8473
+ // Conditions typically look like: WHERE in.uri = 'X' AND predicate = 'Y' AND out.uri = 'Z'
8474
+ // or: array::len(SELECT * FROM link WHERE ...) > 0
8475
+ // Convert to queryLinks calls
8476
+ const sourceMatch = condition.match(/in\.uri\s*=\s*'([^']+)'/);
8477
+ const predicateMatch = condition.match(/predicate\s*=\s*'([^']+)'/);
8478
+ const targetMatch = condition.match(/out\.uri\s*=\s*'([^']+)'/);
8479
+ if (sourceMatch || predicateMatch || targetMatch) {
8480
+ const linkQuery = {};
8481
+ if (sourceMatch)
8482
+ linkQuery.source = sourceMatch[1];
8483
+ if (predicateMatch)
8484
+ linkQuery.predicate = predicateMatch[1];
8485
+ if (targetMatch)
8486
+ linkQuery.target = targetMatch[1];
8487
+ const matchingLinks = await this.get(new exports.LinkQuery(linkQuery));
8488
+ if (matchingLinks.length > 0) {
8489
+ filteredValues.push(value);
8490
+ }
8327
8491
  }
8328
- const filterResult = await this.querySurrealDB(`RETURN ${condition}`);
8329
- const isTrue = filterResult === true || (Array.isArray(filterResult) && filterResult.length > 0 && filterResult[0] === true);
8330
- if (isTrue) {
8492
+ else {
8493
+ // Can't parse condition, include by default
8331
8494
  filteredValues.push(value);
8332
8495
  }
8333
8496
  }
@@ -8355,7 +8518,7 @@ class PerspectiveProxy {
8355
8518
  return values;
8356
8519
  }
8357
8520
  /**
8358
- * Batch-checks multiple expressions against subject class metadata using a single or limited SurrealDB queries.
8521
+ * Batch-checks multiple expressions against subject class metadata using a single or limited SPARQL queries.
8359
8522
  * This avoids N+1 query problems by checking all values at once.
8360
8523
  */
8361
8524
  async batchCheckSubjectInstances(expressions, metadata) {
@@ -8364,30 +8527,31 @@ class PerspectiveProxy {
8364
8527
  }
8365
8528
  // If no required triples, check which expressions have any links
8366
8529
  if (metadata.requiredTriples.length === 0) {
8367
- const escapedExpressions = expressions.map(e => `'${escapeSurrealString(e)}'`).join(', ');
8368
- const checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] GROUP BY in.uri HAVING count() > 0`;
8369
- const result = await this.querySurrealDB(checkQuery);
8370
- return result.map(r => r.uri);
8530
+ const results = [];
8531
+ for (const expr of expressions) {
8532
+ const links = await this.get(new exports.LinkQuery({ source: expr }));
8533
+ if (links.length > 0)
8534
+ results.push(expr);
8535
+ }
8536
+ return results;
8371
8537
  }
8372
- // For each required triple, build a query that finds matching expressions
8538
+ // For each required triple, find which expressions match
8373
8539
  const validExpressionSets = [];
8374
8540
  for (const triple of metadata.requiredTriples) {
8375
- const escapedExpressions = expressions.map(e => `'${escapeSurrealString(e)}'`).join(', ');
8376
- const escapedPredicate = escapeSurrealString(triple.predicate);
8377
- let checkQuery;
8378
- if (triple.target) {
8379
- // Flag: must match both predicate AND exact target value
8380
- const escapedTarget = escapeSurrealString(triple.target);
8381
- // Note: Removed GROUP BY because it was causing SurrealDB to only return one result
8382
- checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}'`;
8383
- }
8384
- else {
8385
- // Property: just check predicate exists
8386
- // Note: Removed GROUP BY because it was causing SurrealDB to only return one result
8387
- checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}'`;
8541
+ const matchingExprs = new Set();
8542
+ for (const expr of expressions) {
8543
+ let query;
8544
+ if (triple.target) {
8545
+ query = new exports.LinkQuery({ source: expr, predicate: triple.predicate, target: triple.target });
8546
+ }
8547
+ else {
8548
+ query = new exports.LinkQuery({ source: expr, predicate: triple.predicate });
8549
+ }
8550
+ const links = await this.get(query);
8551
+ if (links.length > 0)
8552
+ matchingExprs.add(expr);
8388
8553
  }
8389
- const result = await this.querySurrealDB(checkQuery);
8390
- validExpressionSets.push(new Set(result.map(r => r.uri)));
8554
+ validExpressionSets.push(matchingExprs);
8391
8555
  }
8392
8556
  // Find intersection: expressions that passed ALL required triple checks
8393
8557
  if (validExpressionSets.length === 0) {
@@ -8439,13 +8603,12 @@ class PerspectiveProxy {
8439
8603
  let instances = [];
8440
8604
  for (let className of classes) {
8441
8605
  //console.log(`getAllSubjectInstances: Processing class ${className}`);
8442
- // Query SDNA for metadata, then query SurrealDB for instances
8606
+ // Query SDNA for metadata, then query SPARQL for instances
8443
8607
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
8444
8608
  //console.log(`getAllSubjectInstances: Got metadata for ${className}:`, metadata);
8445
8609
  if (metadata) {
8446
- const surrealQuery = this.generateSurrealInstanceQuery(metadata);
8447
- const results = await this.querySurrealDB(surrealQuery);
8448
- // console.log(`getAllSubjectInstances: SurrealDB returned ${results?.length || 0} results`);
8610
+ const results = await this.findInstancesByMetadata(metadata);
8611
+ // console.log(`getAllSubjectInstances: SPARQL returned ${results?.length || 0} results`);
8449
8612
  for (const result of results || []) {
8450
8613
  //console.log(`getAllSubjectInstances: Creating subject for base ${result.base}`);
8451
8614
  try {
@@ -8489,11 +8652,10 @@ class PerspectiveProxy {
8489
8652
  }
8490
8653
  let instances = [];
8491
8654
  for (let className of classes) {
8492
- // Query SDNA for metadata, then query SurrealDB for instances
8655
+ // Query SDNA for metadata, then query SPARQL for instances
8493
8656
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
8494
8657
  if (metadata) {
8495
- const surrealQuery = this.generateSurrealInstanceQuery(metadata);
8496
- const results = await this.querySurrealDB(surrealQuery);
8658
+ const results = await this.findInstancesByMetadata(metadata);
8497
8659
  for (const result of results || []) {
8498
8660
  try {
8499
8661
  let subject = new Subject(this, result.base, className);
@@ -8538,15 +8700,16 @@ class PerspectiveProxy {
8538
8700
  if (properties.length === 0 && relations.length === 0) {
8539
8701
  return null;
8540
8702
  }
8541
- // Single SurrealDB query to find all classes and their properties/relations
8542
- const query = `SELECT
8543
- in.uri AS shape_source,
8544
- predicate,
8545
- out.uri AS target
8546
- FROM link
8547
- WHERE predicate IN ['rdf://type', 'sh://property', 'sh://collection']`;
8548
- const results = await this.querySurrealDB(query);
8549
- if (!results || results.length === 0)
8703
+ // Query links for class shapes using queryLinks
8704
+ const typeLinks = await this.get(new exports.LinkQuery({ predicate: 'rdf://type', target: 'ad4m://SubjectClass' }));
8705
+ const propLinks = await this.get(new exports.LinkQuery({ predicate: 'sh://property' }));
8706
+ const collLinks = await this.get(new exports.LinkQuery({ predicate: 'sh://collection' }));
8707
+ const results = [
8708
+ ...typeLinks.map(l => ({ shape_source: l.data.source, predicate: l.data.predicate, target: l.data.target })),
8709
+ ...propLinks.map(l => ({ shape_source: l.data.source, predicate: l.data.predicate, target: l.data.target })),
8710
+ ...collLinks.map(l => ({ shape_source: l.data.source, predicate: l.data.predicate, target: l.data.target })),
8711
+ ];
8712
+ if (results.length === 0)
8550
8713
  return null;
8551
8714
  // Build a map of className -> { properties, relations }
8552
8715
  const classShapes = new Map();
@@ -8644,8 +8807,15 @@ class PerspectiveProxy {
8644
8807
  * static generateSDNA() function and adds it to the perspective's SDNA.
8645
8808
  */
8646
8809
  async ensureSDNASubjectClass(jsClass) {
8810
+ return this.ensureSubjectClass(jsClass);
8811
+ }
8812
+ /** Takes a JS class (its constructor) and ensures the SHACL subject class exists. */
8813
+ async ensureSubjectClass(jsClass) {
8647
8814
  // Get the class name from the JS class
8648
8815
  const className = jsClass.className || jsClass.prototype?.className || jsClass.name;
8816
+ // Skip if already registered for this perspective instance
8817
+ if (__classPrivateFieldGet$9(this, _PerspectiveProxy_ensuredSubjectClasses, "f").has(className))
8818
+ return;
8649
8819
  // Note: Duplicate checking is handled on the Rust side in add_sdna
8650
8820
  // Generate SHACL SDNA (Prolog-free)
8651
8821
  if (!jsClass.generateSHACL) {
@@ -8658,6 +8828,14 @@ class PerspectiveProxy {
8658
8828
  // Pass SHACL JSON to backend (Prolog-free)
8659
8829
  // Backend stores SHACL links directly
8660
8830
  await this.addSdna(className, '', 'subject_class', shaclJson);
8831
+ // Mark as registered for this perspective instance
8832
+ __classPrivateFieldGet$9(this, _PerspectiveProxy_ensuredSubjectClasses, "f").add(className);
8833
+ }
8834
+ /** Clear the per-instance ensured subject class cache.
8835
+ * Call this after wiping a perspective's links so that
8836
+ * subsequent register() calls re-add SHACL definitions. */
8837
+ clearEnsuredSubjectClasses() {
8838
+ __classPrivateFieldGet$9(this, _PerspectiveProxy_ensuredSubjectClasses, "f").clear();
8661
8839
  }
8662
8840
  getNeighbourhoodProxy() {
8663
8841
  return __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").getNeighbourhoodProxy(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
@@ -8727,7 +8905,7 @@ class PerspectiveProxy {
8727
8905
  return subscriptionProxy;
8728
8906
  }
8729
8907
  /**
8730
- * Creates a subscription for a SurrealQL query that updates in real-time.
8908
+ * Creates a subscription for a SPARQL query that updates in real-time.
8731
8909
  *
8732
8910
  * This method:
8733
8911
  * 1. Creates the subscription on the Rust side
@@ -8742,12 +8920,12 @@ class PerspectiveProxy {
8742
8920
  * when dispose() is called. Make sure to call dispose() when you're done to
8743
8921
  * prevent memory leaks and ensure proper cleanup of resources.
8744
8922
  *
8745
- * @param query - SurrealQL query string
8923
+ /** Subscribe to a query with live updates via the SPARQL subscription endpoint.
8924
+ * @param query - Query string
8746
8925
  * @returns Initialized QuerySubscriptionProxy instance
8747
8926
  */
8748
- async subscribeSurrealDB(query) {
8927
+ async subscribeQuery(query) {
8749
8928
  const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f"));
8750
- subscriptionProxy.isSurrealDB = true;
8751
8929
  // Start the subscription on the Rust side first to get the real subscription ID
8752
8930
  await subscriptionProxy.subscribe();
8753
8931
  // Wait for the initial result
@@ -8755,7 +8933,7 @@ class PerspectiveProxy {
8755
8933
  return subscriptionProxy;
8756
8934
  }
8757
8935
  }
8758
- _PerspectiveProxy_handle = new WeakMap(), _PerspectiveProxy_client = new WeakMap(), _PerspectiveProxy_perspectiveLinkAddedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkRemovedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkUpdatedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveSyncStateChangeCallbacks = new WeakMap();
8936
+ _PerspectiveProxy_handle = new WeakMap(), _PerspectiveProxy_client = new WeakMap(), _PerspectiveProxy_perspectiveLinkAddedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkRemovedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkUpdatedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveSyncStateChangeCallbacks = new WeakMap(), _PerspectiveProxy_ensuredSubjectClasses = new WeakMap();
8759
8937
 
8760
8938
  var __classPrivateFieldSet$8 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
8761
8939
  if (kind === "m") throw new TypeError("Private method is not writable");
@@ -8894,23 +9072,14 @@ class PerspectiveClient {
8894
9072
  }));
8895
9073
  return JSON.parse(perspectiveQueryProlog);
8896
9074
  }
8897
- /**
8898
- * Executes a read-only SurrealQL query against a perspective's link cache.
8899
- *
8900
- * Security: Only SELECT, RETURN, and other read-only queries are permitted.
8901
- * Mutating operations (DELETE, UPDATE, INSERT, etc.) are blocked.
8902
- *
8903
- * Note: GraphQL field name is "perspectiveQuerySurrealDb" (lowercase "b" in "Db")
8904
- * as generated from Rust method "perspective_query_surreal_db"
8905
- */
8906
- async querySurrealDB(uuid, query) {
8907
- const { perspectiveQuerySurrealDb } = unwrapApolloResult(await __classPrivateFieldGet$8(this, _PerspectiveClient_apolloClient, "f").query({
8908
- query: gql `query perspectiveQuerySurrealDb($uuid: String!, $query: String!) {
8909
- perspectiveQuerySurrealDb(uuid: $uuid, query: $query)
9075
+ async querySparql(uuid, query) {
9076
+ const { perspectiveQuerySparql } = unwrapApolloResult(await __classPrivateFieldGet$8(this, _PerspectiveClient_apolloClient, "f").query({
9077
+ query: gql `query perspectiveQuerySparql($uuid: String!, $query: String!) {
9078
+ perspectiveQuerySparql(uuid: $uuid, query: $query)
8910
9079
  }`,
8911
9080
  variables: { uuid, query }
8912
9081
  }));
8913
- return JSON.parse(perspectiveQuerySurrealDb);
9082
+ return JSON.parse(perspectiveQuerySparql);
8914
9083
  }
8915
9084
  async subscribeQuery(uuid, query) {
8916
9085
  const { perspectiveSubscribeQuery } = unwrapApolloResult(await __classPrivateFieldGet$8(this, _PerspectiveClient_apolloClient, "f").mutate({
@@ -8937,49 +9106,6 @@ class PerspectiveClient {
8937
9106
  }
8938
9107
  return { subscriptionId, result: finalResult, isInit };
8939
9108
  }
8940
- async perspectiveSubscribeSurrealQuery(uuid, query) {
8941
- const { perspectiveSubscribeSurrealQuery } = unwrapApolloResult(await __classPrivateFieldGet$8(this, _PerspectiveClient_apolloClient, "f").mutate({
8942
- mutation: gql `mutation perspectiveSubscribeSurrealQuery($uuid: String!, $query: String!) {
8943
- perspectiveSubscribeSurrealQuery(uuid: $uuid, query: $query) {
8944
- subscriptionId
8945
- result
8946
- }
8947
- }`,
8948
- variables: { uuid, query }
8949
- }));
8950
- const { subscriptionId, result } = perspectiveSubscribeSurrealQuery;
8951
- let finalResult = result;
8952
- let isInit = false;
8953
- if (finalResult.startsWith("#init#")) {
8954
- finalResult = finalResult.substring(6);
8955
- isInit = true;
8956
- }
8957
- try {
8958
- finalResult = JSON.parse(finalResult);
8959
- }
8960
- catch (e) {
8961
- console.error('Error parsing perspectiveSubscribeSurrealQuery result:', e);
8962
- }
8963
- return { subscriptionId, result: finalResult, isInit };
8964
- }
8965
- async perspectiveKeepAliveSurrealQuery(uuid, subscriptionId) {
8966
- const { perspectiveKeepAliveSurrealQuery } = unwrapApolloResult(await __classPrivateFieldGet$8(this, _PerspectiveClient_apolloClient, "f").mutate({
8967
- mutation: gql `mutation perspectiveKeepAliveSurrealQuery($uuid: String!, $subscriptionId: String!) {
8968
- perspectiveKeepAliveSurrealQuery(uuid: $uuid, subscriptionId: $subscriptionId)
8969
- }`,
8970
- variables: { uuid, subscriptionId }
8971
- }));
8972
- return perspectiveKeepAliveSurrealQuery;
8973
- }
8974
- async perspectiveDisposeSurrealQuerySubscription(uuid, subscriptionId) {
8975
- const { perspectiveDisposeSurrealQuerySubscription } = unwrapApolloResult(await __classPrivateFieldGet$8(this, _PerspectiveClient_apolloClient, "f").mutate({
8976
- mutation: gql `mutation perspectiveDisposeSurrealQuerySubscription($uuid: String!, $subscriptionId: String!) {
8977
- perspectiveDisposeSurrealQuerySubscription(uuid: $uuid, subscriptionId: $subscriptionId)
8978
- }`,
8979
- variables: { uuid, subscriptionId }
8980
- }));
8981
- return perspectiveDisposeSurrealQuerySubscription;
8982
- }
8983
9109
  subscribeToQueryUpdates(subscriptionId, onData) {
8984
9110
  const subscription = __classPrivateFieldGet$8(this, _PerspectiveClient_apolloClient, "f").subscribe({
8985
9111
  query: gql `
@@ -9376,7 +9502,7 @@ var __classPrivateFieldGet$7 = (undefined && undefined.__classPrivateFieldGet) |
9376
9502
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
9377
9503
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
9378
9504
  };
9379
- var _AgentClient_apolloClient, _AgentClient_appsChangedCallback, _AgentClient_updatedCallbacks, _AgentClient_agentStatusChangedCallbacks;
9505
+ var _AgentClient_apolloClient, _AgentClient_appsChangedCallback, _AgentClient_updatedCallbacks, _AgentClient_agentStatusChangedCallbacks, _AgentClient_hostingUserInfoChangedCallbacks, _AgentClient_computeLogUpdatedCallbacks;
9380
9506
  const AGENT_SUBITEMS = `
9381
9507
  did
9382
9508
  directMessageLanguage
@@ -9439,10 +9565,14 @@ class AgentClient {
9439
9565
  _AgentClient_appsChangedCallback.set(this, void 0);
9440
9566
  _AgentClient_updatedCallbacks.set(this, void 0);
9441
9567
  _AgentClient_agentStatusChangedCallbacks.set(this, void 0);
9568
+ _AgentClient_hostingUserInfoChangedCallbacks.set(this, void 0);
9569
+ _AgentClient_computeLogUpdatedCallbacks.set(this, void 0);
9442
9570
  __classPrivateFieldSet$7(this, _AgentClient_apolloClient, client, "f");
9443
9571
  __classPrivateFieldSet$7(this, _AgentClient_updatedCallbacks, [], "f");
9444
9572
  __classPrivateFieldSet$7(this, _AgentClient_agentStatusChangedCallbacks, [], "f");
9445
9573
  __classPrivateFieldSet$7(this, _AgentClient_appsChangedCallback, [], "f");
9574
+ __classPrivateFieldSet$7(this, _AgentClient_hostingUserInfoChangedCallbacks, [], "f");
9575
+ __classPrivateFieldSet$7(this, _AgentClient_computeLogUpdatedCallbacks, [], "f");
9446
9576
  if (subscribe) {
9447
9577
  this.subscribeAgentUpdated();
9448
9578
  this.subscribeAgentStatusChanged();
@@ -9703,6 +9833,55 @@ class AgentClient {
9703
9833
  error: (e) => console.error(e),
9704
9834
  });
9705
9835
  }
9836
+ addHostingUserInfoChangedListener(listener) {
9837
+ __classPrivateFieldGet$7(this, _AgentClient_hostingUserInfoChangedCallbacks, "f").push(listener);
9838
+ }
9839
+ subscribeHostingUserInfoChanged() {
9840
+ __classPrivateFieldGet$7(this, _AgentClient_apolloClient, "f")
9841
+ .subscribe({
9842
+ query: gql `subscription {
9843
+ runtimeHostingUserInfoChanged {
9844
+ email
9845
+ remainingCredits
9846
+ hotWalletAddress
9847
+ freeAccess
9848
+ }
9849
+ }`,
9850
+ })
9851
+ .subscribe({
9852
+ next: (result) => {
9853
+ const info = result.data.runtimeHostingUserInfoChanged;
9854
+ __classPrivateFieldGet$7(this, _AgentClient_hostingUserInfoChangedCallbacks, "f").forEach((cb) => cb(info));
9855
+ },
9856
+ error: (e) => console.error(e),
9857
+ });
9858
+ }
9859
+ addComputeLogUpdatedListener(listener) {
9860
+ __classPrivateFieldGet$7(this, _AgentClient_computeLogUpdatedCallbacks, "f").push(listener);
9861
+ }
9862
+ subscribeComputeLogUpdated() {
9863
+ __classPrivateFieldGet$7(this, _AgentClient_apolloClient, "f")
9864
+ .subscribe({
9865
+ query: gql `subscription {
9866
+ runtimeComputeLogUpdated {
9867
+ id
9868
+ userEmail
9869
+ timestamp
9870
+ operation
9871
+ summary
9872
+ cost
9873
+ creditsAfter
9874
+ }
9875
+ }`,
9876
+ })
9877
+ .subscribe({
9878
+ next: (result) => {
9879
+ const entry = result.data.runtimeComputeLogUpdated;
9880
+ __classPrivateFieldGet$7(this, _AgentClient_computeLogUpdatedCallbacks, "f").forEach((cb) => cb(entry));
9881
+ },
9882
+ error: (e) => console.error(e),
9883
+ });
9884
+ }
9706
9885
  async requestCapability(authInfo) {
9707
9886
  const { agentRequestCapability } = unwrapApolloResult(await __classPrivateFieldGet$7(this, _AgentClient_apolloClient, "f").mutate({
9708
9887
  mutation: gql `
@@ -9849,6 +10028,24 @@ class AgentClient {
9849
10028
  }));
9850
10029
  return runtimeHostingUserInfo;
9851
10030
  }
10031
+ async computeLog(since, limit, userEmail) {
10032
+ const { runtimeComputeLog } = unwrapApolloResult(await __classPrivateFieldGet$7(this, _AgentClient_apolloClient, "f").query({
10033
+ query: gql `query runtimeComputeLog($since: String, $limit: Int, $userEmail: String) {
10034
+ runtimeComputeLog(since: $since, limit: $limit, userEmail: $userEmail) {
10035
+ id
10036
+ userEmail
10037
+ timestamp
10038
+ operation
10039
+ summary
10040
+ cost
10041
+ creditsAfter
10042
+ }
10043
+ }`,
10044
+ variables: { since, limit, userEmail },
10045
+ fetchPolicy: 'network-only',
10046
+ }));
10047
+ return runtimeComputeLog;
10048
+ }
9852
10049
  async setHotWalletAddress(address) {
9853
10050
  const { runtimeSetHotWalletAddress } = unwrapApolloResult(await __classPrivateFieldGet$7(this, _AgentClient_apolloClient, "f").mutate({
9854
10051
  mutation: gql `mutation runtimeSetHotWalletAddress($address: String!) {
@@ -9871,7 +10068,7 @@ class AgentClient {
9871
10068
  return runtimeRequestPayment;
9872
10069
  }
9873
10070
  }
9874
- _AgentClient_apolloClient = new WeakMap(), _AgentClient_appsChangedCallback = new WeakMap(), _AgentClient_updatedCallbacks = new WeakMap(), _AgentClient_agentStatusChangedCallbacks = new WeakMap();
10071
+ _AgentClient_apolloClient = new WeakMap(), _AgentClient_appsChangedCallback = new WeakMap(), _AgentClient_updatedCallbacks = new WeakMap(), _AgentClient_agentStatusChangedCallbacks = new WeakMap(), _AgentClient_hostingUserInfoChangedCallbacks = new WeakMap(), _AgentClient_computeLogUpdatedCallbacks = new WeakMap();
9875
10072
 
9876
10073
  var __classPrivateFieldSet$6 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
9877
10074
  if (kind === "m") throw new TypeError("Private method is not writable");
@@ -10662,6 +10859,23 @@ class RuntimeClient {
10662
10859
  }));
10663
10860
  return runtimeSetMultiUserEnabled;
10664
10861
  }
10862
+ async freeHostingEnabled() {
10863
+ const { runtimeFreeHostingEnabled } = unwrapApolloResult(await __classPrivateFieldGet$4(this, _RuntimeClient_apolloClient, "f").query({
10864
+ query: gql `query runtimeFreeHostingEnabled {
10865
+ runtimeFreeHostingEnabled
10866
+ }`
10867
+ }));
10868
+ return runtimeFreeHostingEnabled;
10869
+ }
10870
+ async setFreeHostingEnabled(enabled) {
10871
+ const { runtimeSetFreeHostingEnabled } = unwrapApolloResult(await __classPrivateFieldGet$4(this, _RuntimeClient_apolloClient, "f").mutate({
10872
+ mutation: gql `mutation runtimeSetFreeHostingEnabled($enabled: Boolean!) {
10873
+ runtimeSetFreeHostingEnabled(enabled: $enabled)
10874
+ }`,
10875
+ variables: { enabled }
10876
+ }));
10877
+ return runtimeSetFreeHostingEnabled;
10878
+ }
10665
10879
  async listUsers() {
10666
10880
  const { runtimeListUsers } = unwrapApolloResult(await __classPrivateFieldGet$4(this, _RuntimeClient_apolloClient, "f").query({
10667
10881
  query: gql `query runtimeListUsers {
@@ -18645,11 +18859,11 @@ function exprRef2String(ref) {
18645
18859
  return `${ref.language.address}://${ref.expression}`;
18646
18860
  }
18647
18861
  function parseExprUrl(url) {
18648
- if (url.startsWith("literal://")) {
18862
+ if (url.startsWith("literal:")) {
18649
18863
  const languageRef = new exports.LanguageRef();
18650
18864
  languageRef.address = 'literal';
18651
18865
  languageRef.name = 'literal';
18652
- const content = url.substring(10);
18866
+ const content = url.substring(8);
18653
18867
  return new exports.ExpressionRef(languageRef, content);
18654
18868
  }
18655
18869
  const URIregexp = /^([^:^\s]+):\/\/([\s\S]+)$/;
@@ -18970,7 +19184,7 @@ exports.PerspectiveHandle = __decorate$2([
18970
19184
  ], exports.PerspectiveHandle);
18971
19185
 
18972
19186
  /**
18973
- * WakerSubscriptionManager — manages live SurrealDB subscriptions for the waker.
19187
+ * WakerSubscriptionManager — manages live query subscriptions for the waker.
18974
19188
  *
18975
19189
  * Lives in core so it can be imported by both the plugin and integration tests
18976
19190
  * without ESM/CJS import issues.
@@ -18994,7 +19208,7 @@ class WakerSubscriptionManager {
18994
19208
  this.previousSeenMessages = options.previousSeenMessages ?? {};
18995
19209
  }
18996
19210
  /**
18997
- * Create a live SurrealDB subscription.
19211
+ * Create a live SPARQL subscription.
18998
19212
  * If a subscription with the same id already exists, it is disposed first.
18999
19213
  */
19000
19214
  async subscribe(sub) {
@@ -19005,9 +19219,9 @@ class WakerSubscriptionManager {
19005
19219
  }
19006
19220
  const QuerySubscriptionProxy = this.QuerySubscriptionProxyCtor;
19007
19221
  this.logger.info(`[waker] ${sub.id}: creating subscription (perspective=${sub.perspective}, type=${sub.type})`);
19008
- this.logger.info(`[waker] ${sub.id}: SurrealQL query:\n${sub.query}`);
19222
+ this.logger.info(`[waker] ${sub.id}: SPARQL query:\n${sub.query}`);
19009
19223
  const proxy = new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient);
19010
- proxy.isSurrealDB = true;
19224
+ proxy.isSPARQL = true;
19011
19225
  // Suppress unhandled rejection from proxy.initialized — QuerySubscriptionProxy
19012
19226
  // rejects this promise internally when subscribe() fails, and if nobody catches
19013
19227
  // it before the next microtask it crashes the process.
@@ -19040,7 +19254,7 @@ class WakerSubscriptionManager {
19040
19254
  }
19041
19255
  proxy.onResult(async (result) => {
19042
19256
  this.logger.info(`[waker] ${sub.id}: onResult fired — type=${typeof result}, isArray=${Array.isArray(result)}, value=${String(JSON.stringify(result)).substring(0, 500)}`);
19043
- // SurrealDB can deliver non-array values (e.g. false) on disconnect/reconnect — ignore them
19257
+ // Query engine can deliver non-array values (e.g. false) on disconnect/reconnect — ignore them
19044
19258
  if (!Array.isArray(result)) {
19045
19259
  this.logger.warn(`[waker] ${sub.id}: ignoring non-array result: ${JSON.stringify(result)}`);
19046
19260
  return;
@@ -19065,10 +19279,9 @@ class WakerSubscriptionManager {
19065
19279
  for (const msgAddr of newMessages) {
19066
19280
  const parents = [];
19067
19281
  try {
19068
- const escaped = msgAddr.replace(/'/g, "\\'");
19069
- const parentQuery = `SELECT * FROM link WHERE predicate = 'ad4m://has_child' AND target = '${escaped}'`;
19282
+ const parentQuery = `SELECT ?source WHERE { ?source <ad4m://has_child> <${msgAddr}> . }`;
19070
19283
  this.logger.info(`[waker] ${sub.id}: resolving parents for ${msgAddr}`);
19071
- const parentResult = await this.perspectiveClient.querySurrealDB(sub.perspective, parentQuery);
19284
+ const parentResult = await this.perspectiveClient.querySparql(sub.perspective, parentQuery);
19072
19285
  if (Array.isArray(parentResult)) {
19073
19286
  for (const link of parentResult) {
19074
19287
  if (link && link.source) {
@@ -19267,7 +19480,7 @@ class SmartLiteral {
19267
19480
  _SmartLiteral_perspective = new WeakMap(), _SmartLiteral_base = new WeakMap();
19268
19481
 
19269
19482
  /**
19270
- * Shared query helpers used by both the Prolog and SurrealQL query pipelines.
19483
+ * Shared query helpers used by both the Prolog and SPARQL query pipelines.
19271
19484
  */
19272
19485
  /**
19273
19486
  * Resolves the predicate for a parent query.
@@ -19705,14 +19918,14 @@ function buildModelFromJSONSchema(BaseClass, schema, options) {
19705
19918
  }
19706
19919
  // Default resolveLanguage to 'literal' for all remaining property types,
19707
19920
  // matching the @Property decorator behaviour. Without this, string values
19708
- // stored as literal:// URLs are returned unparsed.
19921
+ // stored as literal: URLs are returned unparsed.
19709
19922
  if (resolveLanguage === undefined || resolveLanguage === null) {
19710
19923
  resolveLanguage = 'literal';
19711
19924
  }
19712
19925
  // If property is required, ensure it has an initial value
19713
19926
  if (isRequired && !initial) {
19714
19927
  if (isObjectType(propertySchema)) {
19715
- initial = 'literal://json:{}';
19928
+ initial = 'literal:json:{}';
19716
19929
  }
19717
19930
  else {
19718
19931
  initial = "ad4m://undefined";
@@ -19768,250 +19981,433 @@ function buildModelFromJSONSchema(BaseClass, schema, options) {
19768
19981
  }
19769
19982
 
19770
19983
  /**
19771
- * SurrealQL query building utilities for Ad4mModel.
19984
+ * SPARQL query building utilities for Ad4mModel.
19772
19985
  *
19773
- * Contains the graph-traversal WHERE clause builder, legacy
19774
- * subquery-based clause builders, SELECT-field builders, and
19775
- * the main `buildSurrealQLQuery()` function that produces a
19776
- * complete SurrealQL query string from a `Query` object.
19986
+ * Uses the direct triple + named graph storage model where each AD4M link
19987
+ * is stored in a named graph (keyed by link hash) with metadata in the default graph.
19777
19988
  *
19778
- * All functions are stateless — model metadata and relation metadata
19779
- * are passed in as parameters instead of accessed via `this`.
19989
+ * All AD4M URIs (source, predicate, target) become RDF IRIs.
19780
19990
  *
19781
19991
  * @module
19782
19992
  */
19783
- // ─── Graph Traversal WHERE Clause ────────────────────────────────────────────
19784
19993
  /**
19785
- * Builds WHERE clause filters using SurrealDB graph traversal syntax.
19786
- *
19787
- * Translates where conditions into `->link[WHERE ...]` / `<-link[WHERE ...]`
19788
- * filters that SurrealDB can optimize via graph indexes.
19994
+ * Determine if a property stores values as literal: IRIs (needs parse_literal for comparisons).
19995
+ * Properties with resolveLanguage === "literal" AND properties without resolveLanguage
19996
+ * both store values as literal: URIs. Only properties with a non-literal resolveLanguage
19997
+ * (e.g. file storage) or flag properties store raw URIs.
19998
+ */
19999
+ function isLiteralStoredProperty(propMeta) {
20000
+ if (propMeta.flag)
20001
+ return false;
20002
+ // If resolveLanguage is set to something other than "literal", it's a language expression URI
20003
+ if (propMeta.resolveLanguage && propMeta.resolveLanguage !== "literal")
20004
+ return false;
20005
+ // Everything else (resolveLanguage === "literal" or undefined) stores as literal: URIs
20006
+ return true;
20007
+ }
20008
+ /**
20009
+ * Escape a string for use as a SPARQL string literal.
20010
+ */
20011
+ function escapeSPARQL(value) {
20012
+ return value
20013
+ .replace(/\\/g, "\\\\")
20014
+ .replace(/"/g, '\\"')
20015
+ .replace(/\n/g, "\\n")
20016
+ .replace(/\r/g, "\\r")
20017
+ .replace(/\t/g, "\\t");
20018
+ }
20019
+ /**
20020
+ * Format a value as a SPARQL string literal (double-quoted).
20021
+ */
20022
+ function formatSPARQLValue(value) {
20023
+ if (typeof value === "string") {
20024
+ return `"${escapeSPARQL(value)}"`;
20025
+ }
20026
+ return `"${String(value)}"`;
20027
+ }
20028
+ /**
20029
+ * Format an AD4M URI as an RDF IRI for use in SPARQL triple patterns.
20030
+ * All AD4M link source/predicate/target values become IRIs in angle brackets.
20031
+ * The Rust SPARQL service transparently transforms these to valid IRI format.
20032
+ */
20033
+ function iri(value) {
20034
+ return `<${value}>`;
20035
+ }
20036
+ /**
20037
+ * Build a SPARQL query that returns all links belonging to instances of
20038
+ * the given model class, optionally filtered by `where` conditions.
19789
20039
  *
19790
- * @param metadata - Model metadata from `getModelMetadata()`
19791
- * @param allRelationsMetadata - Full relation metadata (needed for belongs-to
19792
- * direction detection)
19793
- * @param where - User-supplied where conditions
19794
- * @returns Combined AND-joined condition string, or empty string
20040
+ * Uses direct triple patterns: ?source ?predicate ?target
20041
+ * with named graph storage and metadata keyed by graph IRI.
20042
+ */
20043
+ function buildSPARQLQuery(metadata, allRelationsMetadata, query, modelClass) {
20044
+ const joinPatterns = [];
20045
+ const filterExpressions = [];
20046
+ // Parent filter — direct triple pattern
20047
+ if (query.parent) {
20048
+ const parentPredicate = resolveParentPredicate(query.parent, modelClass);
20049
+ joinPatterns.push(`
20050
+ ${iri(query.parent.id)} ${iri(parentPredicate)} ?source .`);
20051
+ }
20052
+ // Required property JOIN patterns — direct triple patterns
20053
+ let hasConformance = false;
20054
+ for (const [, propMeta] of Object.entries(metadata.properties)) {
20055
+ if (propMeta.required) {
20056
+ if (propMeta.getter)
20057
+ continue;
20058
+ hasConformance = true;
20059
+ if (propMeta.flag && propMeta.initial) {
20060
+ joinPatterns.push(`
20061
+ ?source ${iri(propMeta.predicate)} ${iri(propMeta.initial)} .`);
20062
+ }
20063
+ else {
20064
+ joinPatterns.push(`
20065
+ ?source ${iri(propMeta.predicate)} ?cfTarget_${propMeta.name} .`);
20066
+ }
20067
+ }
20068
+ }
20069
+ // Fallback: initial-value JOIN patterns
20070
+ if (!hasConformance) {
20071
+ for (const [, propMeta] of Object.entries(metadata.properties)) {
20072
+ if (propMeta.initial) {
20073
+ hasConformance = true;
20074
+ if (propMeta.flag) {
20075
+ joinPatterns.push(`
20076
+ ?source ${iri(propMeta.predicate)} ${iri(propMeta.initial)} .`);
20077
+ }
20078
+ else {
20079
+ joinPatterns.push(`
20080
+ ?source ${iri(propMeta.predicate)} ?cfInitTarget_${propMeta.name} .`);
20081
+ }
20082
+ break;
20083
+ }
20084
+ }
20085
+ }
20086
+ // Fallback: open-world structural matching
20087
+ // Use a subquery with DISTINCT to avoid row multiplication when the main
20088
+ // ?source ?predicate ?target pattern cross-joins with multiple structural matches.
20089
+ if (!hasConformance && joinPatterns.length === 0) {
20090
+ const knownPredicates = [];
20091
+ for (const [, propMeta] of Object.entries(metadata.properties)) {
20092
+ if (propMeta.predicate) {
20093
+ knownPredicates.push(iri(propMeta.predicate));
20094
+ }
20095
+ }
20096
+ if (metadata.relations) {
20097
+ for (const [, relMeta] of Object.entries(metadata.relations)) {
20098
+ if (relMeta.predicate) {
20099
+ knownPredicates.push(iri(relMeta.predicate));
20100
+ }
20101
+ }
20102
+ }
20103
+ if (knownPredicates.length > 0) {
20104
+ joinPatterns.push(`
20105
+ { SELECT DISTINCT ?source WHERE { ?source ?cf_structPred ?cf_structTarget . FILTER(?cf_structPred IN (${knownPredicates.join(", ")})) } }`);
20106
+ }
20107
+ }
20108
+ // Build WHERE clause filters from user query
20109
+ const { joins: userJoins, filters: userFilters } = buildSPARQLWhereFilters(metadata, allRelationsMetadata, query.where);
20110
+ joinPatterns.push(...userJoins);
20111
+ filterExpressions.push(...userFilters);
20112
+ // Main triple pattern — fetches all links for matched sources
20113
+ // The direct triple in named graph: GRAPH ?linkGraph { ?source ?predicate ?target }
20114
+ // FILTER(isIRI(?source)) excludes non-IRI subjects
20115
+ const joinClause = joinPatterns.join("\n");
20116
+ const filterClause = filterExpressions.length > 0
20117
+ ? `FILTER(\n ${filterExpressions.join(" &&\n ")}\n )`
20118
+ : "";
20119
+ return `
20120
+ SELECT ?source ?predicate ?target ?author ?timestamp WHERE {${joinClause}
20121
+ GRAPH ?linkGraph { ?source ?predicate ?target . }
20122
+ FILTER(isIRI(?source) && isIRI(?predicate))
20123
+ ?linkGraph <ad4m://ontology/author> ?author .
20124
+ ?linkGraph <ad4m://ontology/timestamp> ?timestamp .
20125
+ ${filterClause}
20126
+ }
20127
+ ${buildSPARQLOrderLimitOffset()}
20128
+ `.trim();
20129
+ }
20130
+ /**
20131
+ * Build ORDER BY / LIMIT / OFFSET clauses for the SPARQL query.
20132
+ */
20133
+ function buildSPARQLOrderLimitOffset(_metadata, _query) {
20134
+ return "";
20135
+ }
20136
+ /**
20137
+ * Build a SPARQL query to fetch all links for a single instance.
20138
+ */
20139
+ function buildSPARQLGetDataQuery(baseExpression) {
20140
+ return `
20141
+ SELECT ?source ?predicate ?target ?author ?timestamp WHERE {
20142
+ GRAPH ?linkGraph { ${iri(baseExpression)} ?predicate ?target . }
20143
+ FILTER(isIRI(?predicate))
20144
+ BIND(${iri(baseExpression)} AS ?source)
20145
+ ?linkGraph <ad4m://ontology/author> ?author .
20146
+ ?linkGraph <ad4m://ontology/timestamp> ?timestamp .
20147
+ }
20148
+ `.trim();
20149
+ }
20150
+ /**
20151
+ * Group flat SPARQL link rows into the same shape that SPARQL returned:
20152
+ * `{ source_uri: string, links: Array<{predicate, target, author, timestamp}> }`
20153
+ */
20154
+ function groupSPARQLResults(rows) {
20155
+ const grouped = new Map();
20156
+ for (const row of rows) {
20157
+ const key = row.source;
20158
+ if (!grouped.has(key)) {
20159
+ grouped.set(key, []);
20160
+ }
20161
+ grouped.get(key).push({
20162
+ predicate: row.predicate,
20163
+ target: row.target,
20164
+ author: row.author,
20165
+ timestamp: row.timestamp,
20166
+ });
20167
+ }
20168
+ return Array.from(grouped.entries()).map(([source_uri, links]) => ({
20169
+ source_uri,
20170
+ links,
20171
+ }));
20172
+ }
20173
+ /**
20174
+ * Build SPARQL FILTER expressions from user `where` conditions.
20175
+ * Uses direct triple patterns instead of link-node reification.
19795
20176
  */
19796
- function buildGraphTraversalWhereClause(metadata, allRelationsMetadata, where) {
20177
+ function buildSPARQLWhereFilters(metadata, _allRelationsMetadata, where) {
19797
20178
  if (!where)
19798
- return '';
19799
- const conditions = [];
20179
+ return { joins: [], filters: [] };
20180
+ const joins = [];
20181
+ const filters = [];
19800
20182
  for (const [propertyName, condition] of Object.entries(where)) {
19801
- const isSpecial = ['id', 'author', 'timestamp'].includes(propertyName);
19802
- if (isSpecial) {
19803
- if (propertyName === 'author' || propertyName === 'timestamp') {
19804
- continue; // Filtered post-query in JS
19805
- }
19806
- const columnName = 'uri';
20183
+ // 'base' maps to ?source
20184
+ if (propertyName === "base" || propertyName === "id") {
19807
20185
  if (Array.isArray(condition)) {
19808
- const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
19809
- conditions.push(`${columnName} IN [${formattedValues}]`);
20186
+ const formatted = condition.map(v => iri(v)).join(", ");
20187
+ filters.push(`?source IN (${formatted})`);
19810
20188
  }
19811
- else if (typeof condition === 'object' && condition !== null) {
20189
+ else if (typeof condition === "object" && condition !== null) {
19812
20190
  const ops = condition;
19813
20191
  if (ops.not !== undefined) {
19814
20192
  if (Array.isArray(ops.not)) {
19815
- const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
19816
- conditions.push(`${columnName} NOT IN [${formattedValues}]`);
20193
+ const formatted = ops.not.map(v => iri(v)).join(", ");
20194
+ filters.push(`!(?source IN (${formatted}))`);
19817
20195
  }
19818
20196
  else {
19819
- conditions.push(`${columnName} != ${formatSurrealValue(ops.not)}`);
20197
+ filters.push(`?source != ${iri(ops.not)}`);
19820
20198
  }
19821
20199
  }
19822
- if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
19823
- conditions.push(`${columnName} >= ${formatSurrealValue(ops.between[0])} AND ${columnName} <= ${formatSurrealValue(ops.between[1])}`);
19824
- }
19825
- if (ops.gt !== undefined) {
19826
- conditions.push(`${columnName} > ${formatSurrealValue(ops.gt)}`);
19827
- }
19828
- if (ops.gte !== undefined) {
19829
- conditions.push(`${columnName} >= ${formatSurrealValue(ops.gte)}`);
19830
- }
19831
- if (ops.lt !== undefined) {
19832
- conditions.push(`${columnName} < ${formatSurrealValue(ops.lt)}`);
19833
- }
19834
- if (ops.lte !== undefined) {
19835
- conditions.push(`${columnName} <= ${formatSurrealValue(ops.lte)}`);
19836
- }
19837
- if (ops.contains !== undefined) {
19838
- conditions.push(`${columnName} CONTAINS ${formatSurrealValue(ops.contains)}`);
19839
- }
19840
20200
  }
19841
20201
  else {
19842
- conditions.push(`${columnName} = ${formatSurrealValue(condition)}`);
20202
+ filters.push(`?source = ${iri(String(condition))}`);
19843
20203
  }
20204
+ continue;
19844
20205
  }
19845
- else {
19846
- // Regular properties — check relation metadata first for direction
19847
- const relMeta = allRelationsMetadata[propertyName];
19848
- const isBelongs = relMeta?.kind === 'belongsToOne' || relMeta?.kind === 'belongsToMany';
19849
- if (relMeta) {
19850
- const predicate = escapeSurrealString(relMeta.predicate);
19851
- if (Array.isArray(condition)) {
19852
- const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
19853
- if (isBelongs) {
19854
- conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) > 0`);
19855
- }
19856
- else {
19857
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) > 0`);
19858
- }
19859
- }
19860
- else if (typeof condition === 'object' && condition !== null) {
19861
- const ops = condition;
19862
- if (ops.not !== undefined) {
19863
- if (Array.isArray(ops.not)) {
19864
- const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
19865
- if (isBelongs) {
19866
- conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) = 0`);
19867
- }
19868
- else {
19869
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) = 0`);
19870
- }
19871
- }
19872
- else {
19873
- if (isBelongs) {
19874
- conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${formatSurrealValue(ops.not)}]) = 0`);
19875
- }
19876
- else {
19877
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${formatSurrealValue(ops.not)}]) = 0`);
19878
- }
19879
- }
19880
- }
19881
- }
19882
- else {
19883
- if (isBelongs) {
19884
- conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${formatSurrealValue(condition)}]) > 0`);
19885
- }
19886
- else {
19887
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${formatSurrealValue(condition)}]) > 0`);
19888
- }
19889
- }
19890
- continue;
19891
- }
19892
- const propMeta = metadata.properties[propertyName];
19893
- if (!propMeta)
19894
- continue;
19895
- const predicate = escapeSurrealString(propMeta.predicate);
19896
- const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(out.uri)' : 'out.uri';
19897
- if (Array.isArray(condition)) {
19898
- const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
19899
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
19900
- }
19901
- else if (typeof condition === 'object' && condition !== null) {
20206
+ if (propertyName === "author" || propertyName === "timestamp") {
20207
+ continue;
20208
+ }
20209
+ const propMeta = metadata.properties[propertyName];
20210
+ if (!propMeta)
20211
+ continue;
20212
+ // Skip reverse relations (belongsToOne / belongsToMany) — these are registered as
20213
+ // read-only properties but the link direction is reversed (target→source, not source→target).
20214
+ // Adding a forward join pattern would match nothing. These are filtered in JS post-filter.
20215
+ const relMeta = _allRelationsMetadata[propertyName];
20216
+ if (relMeta && (relMeta.kind === 'belongsToOne' || relMeta.kind === 'belongsToMany')) {
20217
+ continue;
20218
+ }
20219
+ // Determine if this property stores values as literal: IRIs
20220
+ const useParseLiteral = isLiteralStoredProperty(propMeta);
20221
+ // For literal-stored properties, skip SPARQL-level FILTER expressions entirely.
20222
+ // The parse_literal custom function is unreliable across oxigraph versions and
20223
+ // environments. All property-level where filtering is done in JS post-filter
20224
+ // (instancesFromQueryResult) after hydration resolves values to JS primitives.
20225
+ // We only add a JOIN pattern to ensure the property exists (conformance check).
20226
+ if (useParseLiteral) {
20227
+ // Just ensure the property exists — no value filtering in SPARQL
20228
+ if (typeof condition === "object" && condition !== null && !Array.isArray(condition)) {
19902
20229
  const ops = condition;
19903
- if (ops.not !== undefined) {
19904
- if (Array.isArray(ops.not)) {
19905
- const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
19906
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
19907
- }
19908
- else {
19909
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`);
19910
- }
19911
- }
19912
- const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
20230
+ const hasCompOps = ops.gt !== undefined || ops.gte !== undefined ||
19913
20231
  ops.lt !== undefined || ops.lte !== undefined ||
19914
- ops.between !== undefined || ops.contains !== undefined;
19915
- if (hasComparisonOps) {
19916
- conditions.push(`count(->link[WHERE predicate = '${predicate}']) > 0`);
20232
+ ops.between !== undefined || ops.contains !== undefined ||
20233
+ ops.not !== undefined;
20234
+ if (hasCompOps) {
20235
+ joins.push(`
20236
+ ?source ${iri(propMeta.predicate)} ?wTarget_cmp_${propertyName} .`);
19917
20237
  }
20238
+ // NOT filters: no SPARQL-level filtering — handled in JS
19918
20239
  }
19919
20240
  else {
19920
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(condition)}]) > 0`);
20241
+ // Simple equality or IN — add join for conformance.
20242
+ // NOTE: push-down FILTER with fn::parse_literal was attempted but removed because
20243
+ // Oxigraph's query parser rejects the fn:: custom function syntax at parse time
20244
+ // (custom functions are only available at execution time). All literal property
20245
+ // filtering is done in JS post-filter after hydration resolves values.
20246
+ joins.push(`
20247
+ ?source ${iri(propMeta.predicate)} ?wTarget_${propertyName} .`);
20248
+ }
20249
+ }
20250
+ else if (Array.isArray(condition)) {
20251
+ const formatted = condition.map(v => iri(v)).join(", ");
20252
+ joins.push(`
20253
+ ?source ${iri(propMeta.predicate)} ?wTarget_${propertyName} .`);
20254
+ filters.push(`?wTarget_${propertyName} IN (${formatted})`);
20255
+ }
20256
+ else if (typeof condition === "object" && condition !== null) {
20257
+ const ops = condition;
20258
+ if (ops.not !== undefined) {
20259
+ if (Array.isArray(ops.not)) {
20260
+ const formatted = ops.not.map(v => iri(v)).join(", ");
20261
+ filters.push(`
20262
+ NOT EXISTS {
20263
+ ?source ${iri(propMeta.predicate)} ?wTarget_not_${propertyName} .
20264
+ FILTER(?wTarget_not_${propertyName} IN (${formatted}))
20265
+ }
20266
+ `);
20267
+ }
20268
+ else {
20269
+ filters.push(`
20270
+ NOT EXISTS {
20271
+ ?source ${iri(propMeta.predicate)} ${iri(ops.not)} .
20272
+ }
20273
+ `);
20274
+ }
19921
20275
  }
20276
+ const hasCompOps = ops.gt !== undefined || ops.gte !== undefined ||
20277
+ ops.lt !== undefined || ops.lte !== undefined ||
20278
+ ops.between !== undefined || ops.contains !== undefined;
20279
+ if (hasCompOps) {
20280
+ joins.push(`
20281
+ ?source ${iri(propMeta.predicate)} ?wTarget_cmp_${propertyName} .`);
20282
+ }
20283
+ }
20284
+ else {
20285
+ // Simple equality — non-literal property, use exact IRI match
20286
+ joins.push(`
20287
+ ?source ${iri(propMeta.predicate)} ${iri(String(condition))} .`);
19922
20288
  }
19923
20289
  }
19924
- return conditions.join(' AND ');
20290
+ return { joins, filters };
19925
20291
  }
19926
- // ─── Main Query Builder ─────────────────────────────────────────────────────
20292
+
19927
20293
  /**
19928
- * Builds a complete SurrealQL query from a Query object and model metadata.
20294
+ * Subscription Pool — deduplicates identical SPARQL subscriptions.
19929
20295
  *
19930
- * This is the core implementation behind `Ad4mModel.queryToSurrealQL()`.
19931
- * It produces a graph-traversal query that:
19932
- * 1. Filters nodes by required predicates (conformance check)
19933
- * 2. Applies user WHERE conditions
19934
- * 3. Fetches all outgoing links for hydration
20296
+ * When multiple UI components subscribe to the same SPARQL query on the same
20297
+ * perspective, the pool shares a single `subscribeQuery()` call and distributes
20298
+ * results to all registered callbacks. Hydration happens once per result set,
20299
+ * then is shared across all subscribers.
19935
20300
  *
19936
- * @param metadata - Model metadata from `getModelMetadata()`
19937
- * @param allRelationsMetadata - Full relation registry (for belongs-to detection)
19938
- * @param query - Query parameters
19939
- * @param modelClass - The model class (for `resolveParentPredicate`)
19940
- * @returns Complete SurrealQL query string
20301
+ * Key: `perspectiveUUID + sparqlQuery`
19941
20302
  */
19942
- function buildSurrealQLQuery(metadata, allRelationsMetadata, query, modelClass) {
19943
- const { where } = query;
19944
- // Build graph traversal filters for required predicates
19945
- const graphTraversalFilters = [];
19946
- // Parent filter
19947
- if (query.parent) {
19948
- const parentPredicate = resolveParentPredicate(query.parent, modelClass);
19949
- graphTraversalFilters.push(`count(<-link[WHERE in.uri = ${formatSurrealValue(query.parent.id)} AND predicate = '${escapeSurrealString(parentPredicate)}']) > 0`);
19950
- }
19951
- // Required property filters
19952
- for (const [, propMeta] of Object.entries(metadata.properties)) {
19953
- if (propMeta.required) {
19954
- if (propMeta.getter)
19955
- continue;
19956
- if (propMeta.flag && propMeta.initial) {
19957
- graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
19958
- }
19959
- else {
19960
- graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
19961
- }
20303
+ const pool = new Map();
20304
+ function makeKey(perspectiveUUID, sparqlQuery) {
20305
+ return `${perspectiveUUID}::${sparqlQuery}`;
20306
+ }
20307
+ /**
20308
+ * Subscribe to a SPARQL query, sharing the underlying subscription
20309
+ * with any other subscribers using the same perspective + query.
20310
+ *
20311
+ * @param perspective - The perspective proxy
20312
+ * @param sparqlQuery - The SPARQL query text
20313
+ * @param hydrate - Async function that takes raw SPARQL results and returns hydrated results
20314
+ * @param onResult - Callback for subsequent result updates (hydrated)
20315
+ * @returns PooledSubscription with initial result and dispose function
20316
+ */
20317
+ async function pooledSubscribe(perspective, sparqlQuery, hydrate, onResult) {
20318
+ const uuid = perspective.uuid || perspective.handle?.uuid || '';
20319
+ const key = makeKey(uuid, sparqlQuery);
20320
+ const entry = pool.get(key);
20321
+ const subscriber = { onResult, hydrate };
20322
+ if (entry) {
20323
+ // Join existing subscription
20324
+ entry.callbacks.add(subscriber);
20325
+ entry.refCount++;
20326
+ // Hydrate latest result for this new subscriber
20327
+ let initialResult;
20328
+ if (entry.latestHydrated !== undefined) {
20329
+ initialResult = entry.latestHydrated;
20330
+ }
20331
+ else if (entry.latestRaw !== undefined) {
20332
+ initialResult = await hydrate(entry.latestRaw);
19962
20333
  }
20334
+ return {
20335
+ initialResult,
20336
+ dispose: () => disposeSubscriber(key, subscriber),
20337
+ };
19963
20338
  }
19964
- // Fallback: initial-value filters
19965
- if (graphTraversalFilters.length === 0) {
19966
- for (const [, propMeta] of Object.entries(metadata.properties)) {
19967
- if (propMeta.initial) {
19968
- if (propMeta.flag) {
19969
- graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
19970
- }
19971
- else {
19972
- graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
20339
+ // Create new subscription
20340
+ const subscription = await perspective.subscribeQuery(sparqlQuery);
20341
+ const newEntry = {
20342
+ subscription,
20343
+ callbacks: new Set([subscriber]),
20344
+ latestRaw: subscription.result,
20345
+ latestHydrated: undefined,
20346
+ hydrating: false,
20347
+ refCount: 1,
20348
+ };
20349
+ pool.set(key, newEntry);
20350
+ // Set up shared result handler
20351
+ subscription.onResult(async (rawResult) => {
20352
+ newEntry.latestRaw = rawResult;
20353
+ newEntry.hydrating = true;
20354
+ try {
20355
+ // Hydrate ONCE using the first subscriber's hydrate function
20356
+ const firstSub = newEntry.callbacks.values().next().value;
20357
+ if (firstSub) {
20358
+ const hydrated = await firstSub.hydrate(rawResult);
20359
+ newEntry.latestHydrated = hydrated;
20360
+ // Distribute to all callbacks
20361
+ for (const cb of newEntry.callbacks) {
20362
+ try {
20363
+ cb.onResult(hydrated);
20364
+ }
20365
+ catch (e) { /* subscriber error */ }
19973
20366
  }
19974
- break;
19975
20367
  }
19976
20368
  }
19977
- }
19978
- // Fallback: open-world structural matching
19979
- if (graphTraversalFilters.length === 0) {
19980
- const structuralPredicates = [];
19981
- for (const [, propMeta] of Object.entries(metadata.properties)) {
19982
- if (propMeta.predicate) {
19983
- structuralPredicates.push(`predicate = '${escapeSurrealString(propMeta.predicate)}'`);
19984
- }
20369
+ finally {
20370
+ newEntry.hydrating = false;
19985
20371
  }
19986
- if (metadata.relations) {
19987
- for (const [, relMeta] of Object.entries(metadata.relations)) {
19988
- if (relMeta.predicate) {
19989
- structuralPredicates.push(`predicate = '${escapeSurrealString(relMeta.predicate)}'`);
19990
- }
19991
- }
19992
- }
19993
- if (structuralPredicates.length > 0) {
19994
- graphTraversalFilters.push(`count(->link[WHERE (${structuralPredicates.join(' OR ')})]) > 0`);
20372
+ });
20373
+ // Hydrate initial result
20374
+ const initialResult = await hydrate(subscription.result);
20375
+ newEntry.latestHydrated = initialResult;
20376
+ return {
20377
+ initialResult,
20378
+ dispose: () => disposeSubscriber(key, subscriber),
20379
+ };
20380
+ }
20381
+ function disposeSubscriber(key, subscriber) {
20382
+ const entry = pool.get(key);
20383
+ if (!entry)
20384
+ return;
20385
+ entry.callbacks.delete(subscriber);
20386
+ entry.refCount--;
20387
+ if (entry.refCount <= 0) {
20388
+ // Last subscriber — tear down the underlying subscription
20389
+ if (entry.subscription?.dispose) {
20390
+ entry.subscription.dispose();
19995
20391
  }
20392
+ pool.delete(key);
19996
20393
  }
19997
- // User WHERE clause
19998
- const userWhereClause = buildGraphTraversalWhereClause(metadata, allRelationsMetadata, where);
19999
- const whereConditions = [];
20000
- whereConditions.push(...graphTraversalFilters);
20001
- if (userWhereClause) {
20002
- whereConditions.push(userWhereClause);
20394
+ }
20395
+ /**
20396
+ * Clear the entire pool (for testing).
20397
+ */
20398
+ function clearSubscriptionPool() {
20399
+ for (const entry of pool.values()) {
20400
+ if (entry.subscription?.dispose) {
20401
+ entry.subscription.dispose();
20402
+ }
20003
20403
  }
20004
- whereConditions.push(`count(->link) > 0`);
20005
- const fullQuery = `
20006
- SELECT
20007
- id AS source,
20008
- uri AS source_uri,
20009
- ->link AS links
20010
- FROM node
20011
- WHERE ${whereConditions.join(' AND ')}
20012
- FETCH links
20013
- `.trim();
20014
- return fullQuery;
20404
+ pool.clear();
20405
+ }
20406
+ /**
20407
+ * Get the current pool size (for testing).
20408
+ */
20409
+ function subscriptionPoolSize() {
20410
+ return pool.size;
20015
20411
  }
20016
20412
 
20017
20413
  /**
@@ -20044,7 +20440,7 @@ class ModelQueryBuilder {
20044
20440
  constructor(perspective, ctor, query) {
20045
20441
  this.queryParams = {};
20046
20442
  this.modelClassName = null;
20047
- this.useSurrealDBFlag = true;
20443
+ this.engineFlag = 'sparql';
20048
20444
  this.perspective = perspective;
20049
20445
  this.ctor = ctor;
20050
20446
  if (query)
@@ -20252,32 +20648,10 @@ class ModelQueryBuilder {
20252
20648
  return this;
20253
20649
  }
20254
20650
  /**
20255
- * Enables or disables SurrealDB query path.
20256
- *
20257
- * @param enabled - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
20258
- * @returns The query builder for chaining
20259
- *
20260
- * @example
20261
- * ```typescript
20262
- * // Use SurrealDB (default)
20263
- * const recipes = await Recipe.query(perspective)
20264
- * .where({ category: "Dessert" })
20265
- * .useSurrealDB(true)
20266
- * .get();
20267
- *
20268
- * // Use Prolog (legacy)
20269
- * const recipesProlog = await Recipe.query(perspective)
20270
- * .where({ category: "Dessert" })
20271
- * .useSurrealDB(false)
20272
- * .get();
20273
- * ```
20274
- *
20275
- * @remarks
20276
- * Note: Subscriptions (subscribe(), countSubscribe(), paginateSubscribe()) default to SurrealDB live queries
20277
- * if useSurrealDB(true) is set (default).
20651
+ * Sets the query engine to use.
20278
20652
  */
20279
- useSurrealDB(enabled = true) {
20280
- this.useSurrealDBFlag = enabled;
20653
+ engine(eng) {
20654
+ this.engineFlag = eng;
20281
20655
  return this;
20282
20656
  }
20283
20657
  /**
@@ -20294,10 +20668,8 @@ class ModelQueryBuilder {
20294
20668
  */
20295
20669
  async get() {
20296
20670
  let results;
20297
- if (this.useSurrealDBFlag) {
20298
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
20299
- const result = await this.perspective.querySurrealDB(surrealQuery);
20300
- ({ results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result));
20671
+ if (this.engineFlag === 'sparql') {
20672
+ results = await this.executeSparqlQuery();
20301
20673
  }
20302
20674
  else {
20303
20675
  const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
@@ -20306,6 +20678,29 @@ class ModelQueryBuilder {
20306
20678
  }
20307
20679
  return results;
20308
20680
  }
20681
+ /**
20682
+ * Executes the query once using SPARQL and returns the results.
20683
+ */
20684
+ async getSparql() {
20685
+ return this.executeSparqlQuery();
20686
+ }
20687
+ /**
20688
+ * Shared SPARQL query execution logic used by both get() and getSparql().
20689
+ */
20690
+ async executeSparqlQuery() {
20691
+ const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, this.queryParams);
20692
+ const rawResult = await this.perspective.querySparql(sparqlQuery);
20693
+ const { results } = await this.processSparqlResult(rawResult);
20694
+ return results;
20695
+ }
20696
+ /**
20697
+ * Groups raw SPARQL results and hydrates them into model instances.
20698
+ * Centralises the repeated groupSPARQLResults → instancesFromQueryResult pipeline.
20699
+ */
20700
+ async processSparqlResult(rawResult, queryOverride) {
20701
+ const grouped = groupSPARQLResults(Array.isArray(rawResult) ? rawResult : []);
20702
+ return await this.ctor.instancesFromQueryResult(this.perspective, queryOverride || this.queryParams, grouped);
20703
+ }
20309
20704
  /**
20310
20705
  * Returns the first matching instance, or `null` if none match.
20311
20706
  *
@@ -20329,7 +20724,7 @@ class ModelQueryBuilder {
20329
20724
  * Subscribes to the query and receives updates when results change.
20330
20725
  *
20331
20726
  * This method:
20332
- * 1. Creates and initializes a SurrealDB live query subscription (default)
20727
+ * 1. Creates and initializes a SPARQL live query subscription (default)
20333
20728
  * 2. Sets up the callback to process future updates
20334
20729
  * 3. Returns the initial results immediately
20335
20730
  *
@@ -20353,26 +20748,40 @@ class ModelQueryBuilder {
20353
20748
  * ```
20354
20749
  *
20355
20750
  * @remarks
20356
- * By default, this uses SurrealDB live queries for real-time updates.
20357
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
20751
+ * By default, this uses SPARQL live queries for real-time updates.
20752
+ * Prolog subscriptions remain available via `.useSPARQL(false)`.
20358
20753
  */
20359
20754
  async subscribe(callback) {
20360
20755
  // Clean up any existing subscription
20361
20756
  this.dispose();
20362
20757
  const ctor = this.ctor;
20363
- if (this.useSurrealDBFlag) {
20364
- const surrealQuery = await ctor.queryToSurrealQL(this.perspective, this.queryParams);
20365
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
20366
- const processResults = async (result) => {
20367
- const { results } = await ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
20368
- callback(results);
20758
+ if (this.engineFlag === 'sparql') {
20759
+ const sparqlQuery = await ctor.queryToSPARQL(this.perspective, this.queryParams);
20760
+ // Track last emitted result fingerprint to suppress duplicate callbacks
20761
+ let lastResultFingerprint = null;
20762
+ const buildFingerprint = (results) => {
20763
+ if (results.length === 0)
20764
+ return '0:';
20765
+ const ids = results.map((r) => r.id || '').sort().join(',');
20766
+ const ts = results.map((r) => r.updatedAt || r.timestamp || '').join(',');
20767
+ return `${results.length}:${ids}:${ts}`;
20369
20768
  };
20370
- this.currentSubscription.onResult(processResults);
20371
- // Process initial result
20372
- const { results } = await ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
20373
- // Also invoke callback with initial results so subscribers see them
20374
- callback(results);
20375
- return results;
20769
+ const hydrate = async (rawResult) => {
20770
+ const { results } = await this.processSparqlResult(rawResult);
20771
+ return results;
20772
+ };
20773
+ const pooled = await pooledSubscribe(this.perspective, sparqlQuery, hydrate, (hydratedResults) => {
20774
+ const fp = buildFingerprint(hydratedResults);
20775
+ if (fp === lastResultFingerprint)
20776
+ return;
20777
+ lastResultFingerprint = fp;
20778
+ callback(hydratedResults);
20779
+ });
20780
+ // Store dispose function as subscription
20781
+ this.currentSubscription = { dispose: pooled.dispose };
20782
+ const initialResults = pooled.initialResult;
20783
+ lastResultFingerprint = buildFingerprint(initialResults);
20784
+ return initialResults;
20376
20785
  }
20377
20786
  else {
20378
20787
  const query = await ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
@@ -20383,11 +20792,26 @@ class ModelQueryBuilder {
20383
20792
  };
20384
20793
  this.currentSubscription.onResult(processResults);
20385
20794
  const { results } = await ctor.instancesFromPrologResult(this.perspective, this.queryParams, this.currentSubscription.result);
20386
- // Also invoke callback with initial results so subscribers see them
20387
- callback(results);
20795
+ // Initial results returned via Promise only — callback is for subsequent updates
20388
20796
  return results;
20389
20797
  }
20390
20798
  }
20799
+ /**
20800
+ * Subscribes to the query and receives updates using SPARQL.
20801
+ */
20802
+ async subscribeSparql(callback) {
20803
+ this.dispose();
20804
+ const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, this.queryParams);
20805
+ this.currentSubscription = await this.perspective.subscribeQuery(sparqlQuery);
20806
+ const processResults = async (result) => {
20807
+ const { results } = await this.processSparqlResult(result);
20808
+ callback(results);
20809
+ };
20810
+ this.currentSubscription.onResult(processResults);
20811
+ const { results } = await this.processSparqlResult(this.currentSubscription.result);
20812
+ // Initial results returned via Promise only — callback is for subsequent updates
20813
+ return results;
20814
+ }
20391
20815
  /**
20392
20816
  * Gets the total count of matching entities.
20393
20817
  *
@@ -20401,13 +20825,10 @@ class ModelQueryBuilder {
20401
20825
  * ```
20402
20826
  */
20403
20827
  async count() {
20404
- if (this.useSurrealDBFlag) {
20405
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
20406
- const result = await this.perspective.querySurrealDB(surrealQuery);
20407
- // Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
20408
- // (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
20409
- // This ensures count() returns the same number as get().length
20410
- const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
20828
+ if (this.engineFlag === 'sparql') {
20829
+ const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, this.queryParams);
20830
+ const rawResult = await this.perspective.querySparql(sparqlQuery);
20831
+ const { totalCount } = await this.processSparqlResult(rawResult);
20411
20832
  return totalCount;
20412
20833
  }
20413
20834
  else {
@@ -20416,11 +20837,25 @@ class ModelQueryBuilder {
20416
20837
  return result?.[0]?.TotalCount || 0;
20417
20838
  }
20418
20839
  }
20840
+ /**
20841
+ * Gets the total count of matching entities using SPARQL.
20842
+ * Delegates to count() with SPARQL engine forced.
20843
+ */
20844
+ async countSparql() {
20845
+ const prev = this.engineFlag;
20846
+ this.engineFlag = 'sparql';
20847
+ try {
20848
+ return await this.count();
20849
+ }
20850
+ finally {
20851
+ this.engineFlag = prev;
20852
+ }
20853
+ }
20419
20854
  /**
20420
20855
  * Subscribes to count updates for matching entities.
20421
20856
  *
20422
20857
  * This method:
20423
- * 1. Creates and initializes a SurrealDB live query subscription for the count (default)
20858
+ * 1. Creates and initializes a SPARQL live query subscription for the count (default)
20424
20859
  * 2. Sets up the callback to process future count updates
20425
20860
  * 3. Returns the initial count immediately
20426
20861
  *
@@ -20444,22 +20879,22 @@ class ModelQueryBuilder {
20444
20879
  * ```
20445
20880
  *
20446
20881
  * @remarks
20447
- * By default, this uses SurrealDB live queries for real-time updates.
20448
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
20882
+ * By default, this uses SPARQL live queries for real-time updates.
20883
+ * Prolog subscriptions remain available via `.useSPARQL(false)`.
20449
20884
  */
20450
20885
  async countSubscribe(callback) {
20451
20886
  // Clean up any existing subscription
20452
20887
  this.dispose();
20453
- if (this.useSurrealDBFlag) {
20454
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
20455
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
20888
+ if (this.engineFlag === 'sparql') {
20889
+ const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, this.queryParams);
20890
+ this.currentSubscription = await this.perspective.subscribeQuery(sparqlQuery);
20456
20891
  const processResults = async (result) => {
20457
- const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
20892
+ const { totalCount } = await this.processSparqlResult(result);
20458
20893
  callback(totalCount);
20459
20894
  };
20460
20895
  this.currentSubscription.onResult(processResults);
20461
- const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
20462
- callback(totalCount);
20896
+ const { totalCount } = await this.processSparqlResult(this.currentSubscription.result);
20897
+ // Initial count returned via Promise — callback for updates only
20463
20898
  return totalCount;
20464
20899
  }
20465
20900
  else {
@@ -20471,10 +20906,26 @@ class ModelQueryBuilder {
20471
20906
  };
20472
20907
  this.currentSubscription.onResult(processResults);
20473
20908
  const initialCount = this.currentSubscription.result?.[0]?.TotalCount || 0;
20474
- callback(initialCount);
20909
+ // Initial count returned via Promise — callback for subsequent updates only
20475
20910
  return initialCount;
20476
20911
  }
20477
20912
  }
20913
+ /**
20914
+ * Subscribes to count updates using SPARQL.
20915
+ */
20916
+ async countSubscribeSparql(callback) {
20917
+ this.dispose();
20918
+ const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, this.queryParams);
20919
+ this.currentSubscription = await this.perspective.subscribeQuery(sparqlQuery);
20920
+ const processResults = async (result) => {
20921
+ const { totalCount } = await this.processSparqlResult(result);
20922
+ callback(totalCount);
20923
+ };
20924
+ this.currentSubscription.onResult(processResults);
20925
+ const { totalCount } = await this.processSparqlResult(this.currentSubscription.result);
20926
+ // Initial count returned via Promise — callback for updates only
20927
+ return totalCount;
20928
+ }
20478
20929
  /**
20479
20930
  * Gets a page of results with pagination metadata.
20480
20931
  *
@@ -20492,10 +20943,10 @@ class ModelQueryBuilder {
20492
20943
  */
20493
20944
  async paginate(pageSize, pageNumber) {
20494
20945
  const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
20495
- if (this.useSurrealDBFlag) {
20496
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
20497
- const result = await this.perspective.querySurrealDB(surrealQuery);
20498
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result));
20946
+ if (this.engineFlag === 'sparql') {
20947
+ const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, paginationQuery);
20948
+ const result = await this.perspective.querySparql(sparqlQuery);
20949
+ const { results, totalCount } = await this.processSparqlResult(result, paginationQuery);
20499
20950
  return { results, totalCount, pageSize, pageNumber };
20500
20951
  }
20501
20952
  else {
@@ -20505,11 +20956,25 @@ class ModelQueryBuilder {
20505
20956
  return { results, totalCount, pageSize, pageNumber };
20506
20957
  }
20507
20958
  }
20959
+ /**
20960
+ * Gets a page of results using SPARQL.
20961
+ * Delegates to paginate() with SPARQL engine forced.
20962
+ */
20963
+ async paginateSparql(pageSize, pageNumber) {
20964
+ const prev = this.engineFlag;
20965
+ this.engineFlag = 'sparql';
20966
+ try {
20967
+ return await this.paginate(pageSize, pageNumber);
20968
+ }
20969
+ finally {
20970
+ this.engineFlag = prev;
20971
+ }
20972
+ }
20508
20973
  /**
20509
20974
  * Subscribes to paginated results updates.
20510
20975
  *
20511
20976
  * This method:
20512
- * 1. Creates and initializes a SurrealDB live query subscription for the paginated results (default)
20977
+ * 1. Creates and initializes a SPARQL live query subscription for the paginated results (default)
20513
20978
  * 2. Sets up the callback to process future page updates
20514
20979
  * 3. Returns the initial page immediately
20515
20980
  *
@@ -20535,24 +21000,24 @@ class ModelQueryBuilder {
20535
21000
  * ```
20536
21001
  *
20537
21002
  * @remarks
20538
- * By default, this uses SurrealDB live queries for real-time updates.
20539
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
21003
+ * By default, this uses SPARQL live queries for real-time updates.
21004
+ * Prolog subscriptions remain available via `.useSPARQL(false)`.
20540
21005
  */
20541
21006
  async paginateSubscribe(pageSize, pageNumber, callback) {
20542
21007
  // Clean up any existing subscription
20543
21008
  this.dispose();
20544
21009
  const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
20545
- if (this.useSurrealDBFlag) {
20546
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
20547
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
21010
+ if (this.engineFlag === 'sparql') {
21011
+ const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, paginationQuery);
21012
+ this.currentSubscription = await this.perspective.subscribeQuery(sparqlQuery);
20548
21013
  const processResults = async (result) => {
20549
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result));
21014
+ const { results, totalCount } = await this.processSparqlResult(result, paginationQuery);
20550
21015
  callback({ results, totalCount, pageSize, pageNumber });
20551
21016
  };
20552
21017
  this.currentSubscription.onResult(processResults);
20553
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, this.currentSubscription.result));
21018
+ const { results, totalCount } = await this.processSparqlResult(this.currentSubscription.result, paginationQuery);
20554
21019
  const initialPage = { results, totalCount, pageSize, pageNumber };
20555
- callback(initialPage);
21020
+ // Initial page returned via Promise — callback for subsequent updates only
20556
21021
  return initialPage;
20557
21022
  }
20558
21023
  else {
@@ -20565,17 +21030,31 @@ class ModelQueryBuilder {
20565
21030
  this.currentSubscription.onResult(processResults);
20566
21031
  const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, this.currentSubscription.result));
20567
21032
  const initialPrologPage = { results, totalCount, pageSize, pageNumber };
20568
- callback(initialPrologPage);
21033
+ // Initial page returned via Promise — callback for subsequent updates only
20569
21034
  return initialPrologPage;
20570
21035
  }
20571
21036
  }
21037
+ /**
21038
+ * Subscribes to paginated results updates using SPARQL.
21039
+ * Delegates to paginateSubscribe() with SPARQL engine forced.
21040
+ */
21041
+ async paginateSubscribeSparql(pageSize, pageNumber, callback) {
21042
+ const prev = this.engineFlag;
21043
+ this.engineFlag = 'sparql';
21044
+ try {
21045
+ return await this.paginateSubscribe(pageSize, pageNumber, callback);
21046
+ }
21047
+ finally {
21048
+ this.engineFlag = prev;
21049
+ }
21050
+ }
20572
21051
  }
20573
21052
 
20574
21053
  /**
20575
21054
  * hydration.ts — Instance hydration helpers extracted from Ad4mModel.
20576
21055
  *
20577
21056
  * Pure / stateless functions that populate Ad4mModel instances from
20578
- * raw link arrays, Prolog tuples, or SurrealDB rows. None of these
21057
+ * raw link arrays, Prolog tuples, or query results. None of these
20579
21058
  * functions depend on the `Ad4mModel` class at runtime — they accept
20580
21059
  * the instance, metadata, or perspective as explicit parameters.
20581
21060
  */
@@ -20670,7 +21149,7 @@ async function hydratePropertyValue(target, propMeta, perspective, expectedType)
20670
21149
  if (propMeta.resolveLanguage != null &&
20671
21150
  propMeta.resolveLanguage !== 'literal' &&
20672
21151
  typeof target === 'string' &&
20673
- !target.startsWith('literal://')) {
21152
+ !target.startsWith('literal:')) {
20674
21153
  try {
20675
21154
  const expression = await perspective.getExpression(target);
20676
21155
  if (expression) {
@@ -20689,7 +21168,7 @@ async function hydratePropertyValue(target, propMeta, perspective, expectedType)
20689
21168
  // Literal URI parsing
20690
21169
  else if (propMeta.resolveLanguage === 'literal' &&
20691
21170
  typeof target === 'string' &&
20692
- target.startsWith('literal://')) {
21171
+ target.startsWith('literal:')) {
20693
21172
  try {
20694
21173
  const parsed = Literal.fromUrl(target).get();
20695
21174
  value = parsed.data !== undefined ? parsed.data : parsed;
@@ -20921,10 +21400,10 @@ async function assignValuesToInstance(perspective, instance, values) {
20921
21400
  Object.assign(instance, writableProps);
20922
21401
  }
20923
21402
  // ──────────────────────────────────────────────────────────
20924
- // SurrealQL custom getter evaluation
21403
+ // SPARQL custom getter evaluation
20925
21404
  // ──────────────────────────────────────────────────────────
20926
21405
  /**
20927
- * Builds a SurrealQL conformance getter for a relation whose `target` model
21406
+ * Builds a SPARQL conformance getter for a relation whose `target` model
20928
21407
  * is known but no explicit `getter` string was supplied.
20929
21408
  *
20930
21409
  * The generated getter traverses outgoing links matching the relation's
@@ -20936,7 +21415,7 @@ async function assignValuesToInstance(perspective, instance, values) {
20936
21415
  *
20937
21416
  * @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
20938
21417
  * @param targetClass - The target model class (result of calling the `target()` thunk)
20939
- * @returns A SurrealQL expression string, or `undefined` if no conformance
21418
+ * @returns A SPARQL expression string, or `undefined` if no conformance
20940
21419
  * conditions could be derived from the target model.
20941
21420
  */
20942
21421
  function buildConformanceGetter(relationPredicate, targetClass) {
@@ -20955,7 +21434,7 @@ function buildConformanceGetter(relationPredicate, targetClass) {
20955
21434
  * getter is auto-generated from the target model's metadata (unless `filter: false`).
20956
21435
  */
20957
21436
  async function evaluateCustomGettersForInstance(instance, perspective, metadata, options) {
20958
- const safeBaseExpression = formatSurrealValue(instance.id);
21437
+ `<${instance.id}>`;
20959
21438
  // Build projection filter — when requestedProperties is active, only
20960
21439
  // evaluate getters for fields that are requested (or included).
20961
21440
  const projectionActive = options?.requestedProperties && options.requestedProperties.length > 0;
@@ -20966,12 +21445,28 @@ async function evaluateCustomGettersForInstance(instance, perspective, metadata,
20966
21445
  continue;
20967
21446
  if (propMeta.getter) {
20968
21447
  try {
20969
- // Replace 'Base' placeholder with actual base expression
20970
- const query = propMeta.getter.replace(/Base/g, safeBaseExpression);
20971
- // Query from node table to have graph traversal context
20972
- const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
20973
- if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null && result[0].value !== 'None' && result[0].value !== '') {
20974
- instance[propName] = result[0].value;
21448
+ const rawGetter = propMeta.getter;
21449
+ const getterWithBase = rawGetter.replace(/\?source\b/g, `<${instance.id}>`).replace(/<Base>/g, `<${instance.id}>`).replace(/Base/g, `<${instance.id}>`);
21450
+ // If the getter is already SPARQL (starts with SELECT/ASK/CONSTRUCT), execute directly
21451
+ const trimmed = getterWithBase.trim().toUpperCase();
21452
+ if (trimmed.startsWith('SELECT') || trimmed.startsWith('ASK') || trimmed.startsWith('CONSTRUCT')) {
21453
+ const result = await perspective.querySparql(getterWithBase);
21454
+ if (trimmed.startsWith('ASK')) {
21455
+ instance[propName] = result === true || result === 'true';
21456
+ }
21457
+ else if (result && result.length > 0) {
21458
+ // Get first binding's first value
21459
+ const firstRow = result[0];
21460
+ const firstKey = Object.keys(firstRow)[0];
21461
+ const val = firstRow[firstKey]?.value ?? firstRow[firstKey];
21462
+ if (val !== undefined && val !== null && val !== 'None' && val !== '') {
21463
+ instance[propName] = val;
21464
+ }
21465
+ }
21466
+ }
21467
+ else {
21468
+ // Legacy SurrealDB-style getter — no longer supported
21469
+ console.warn(`Unsupported legacy getter syntax for property ${propName} — use native SPARQL (SELECT/ASK): ${rawGetter.slice(0, 100)}`);
20975
21470
  }
20976
21471
  }
20977
21472
  catch (error) {
@@ -20987,12 +21482,11 @@ async function evaluateCustomGettersForInstance(instance, perspective, metadata,
20987
21482
  const meta = relMeta;
20988
21483
  // Determine the getter to execute:
20989
21484
  // 1. Explicit `getter` always wins
20990
- // 2. `where` clause → compile DSL to SurrealQL getter
20991
- // 3. If `target` is set and `filter !== false`, auto-generate from target metadata
21485
+ // 2. If `target` is set and `filter !== false`, auto-generate conformance getter
20992
21486
  // BUT skip auto-generation for reverse relations (belongsToMany / belongsToOne)
20993
- // because buildConformanceGetter traverses outgoing links (->link) which is
20994
- // wrong for reverse relations. Their values are already populated by the
20995
- // reverse link lookup in instancesFromSurrealResult / getData.
21487
+ // because buildConformanceGetter traverses outgoing links which is wrong for
21488
+ // reverse relations. Their values are already populated by the reverse link
21489
+ // lookup in instancesFromQueryResult / getData.
20996
21490
  let getter = meta.getter;
20997
21491
  if (!getter && meta.where && meta.direction !== 'reverse') {
20998
21492
  try {
@@ -21000,14 +21494,35 @@ async function evaluateCustomGettersForInstance(instance, perspective, metadata,
21000
21494
  const targetMetadata = TargetClass
21001
21495
  ? TargetClass.getModelMetadata?.() ?? null
21002
21496
  : null;
21003
- const conditions = compileWhereClause(meta.where, targetMetadata);
21004
- if (conditions.length > 0) {
21005
- const escapedPred = escapeSurrealString(meta.predicate);
21006
- getter = `(->link[WHERE predicate = '${escapedPred}'].out[WHERE ${conditions.join(' AND ')}].uri)`;
21497
+ // Check if all where conditions can be SPARQL-filtered.
21498
+ // literal-resolved properties store signed expressions (literal:json:{…}),
21499
+ // not raw literal:string: IRIs, so SPARQL exact-match fails for them.
21500
+ let allSparqlFilterable = true;
21501
+ if (targetMetadata) {
21502
+ for (const propName of Object.keys(meta.where)) {
21503
+ if (['id', 'author', 'timestamp'].includes(propName))
21504
+ continue;
21505
+ const propMeta = targetMetadata.properties[propName];
21506
+ if (propMeta && (!propMeta.resolveLanguage || propMeta.resolveLanguage === 'literal')) {
21507
+ allSparqlFilterable = false;
21508
+ break;
21509
+ }
21510
+ }
21511
+ }
21512
+ else {
21513
+ allSparqlFilterable = false;
21007
21514
  }
21515
+ if (allSparqlFilterable) {
21516
+ const conditions = compileWhereClause(meta.where, targetMetadata);
21517
+ if (conditions.length > 0) {
21518
+ const escapedPredicate = escapeQueryString(meta.predicate);
21519
+ getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;
21520
+ }
21521
+ }
21522
+ // If not filterable, fall through to buildConformanceGetter + JS post-filter below
21008
21523
  }
21009
21524
  catch (e) {
21010
- // Target metadata may not be available yet
21525
+ console.warn(`[Ad4mModel] where-clause compilation failed for relation "${relName}":`, e);
21011
21526
  }
21012
21527
  }
21013
21528
  if (!getter && meta.target && meta.filter !== false && meta.direction !== 'reverse') {
@@ -21024,23 +21539,57 @@ async function evaluateCustomGettersForInstance(instance, perspective, metadata,
21024
21539
  }
21025
21540
  if (getter) {
21026
21541
  try {
21027
- // Replace 'Base' placeholder with actual base expression
21028
- const query = getter.replace(/Base/g, safeBaseExpression);
21029
- const fullQuery = `SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`;
21030
- // Query from node table to have graph traversal context
21031
- const result = await perspective.querySurrealDB(fullQuery);
21032
- if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null) {
21033
- // Filter out 'None' from relation results
21034
- const value = result[0].value;
21035
- instance[relName] = Array.isArray(value)
21036
- ? value.filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None')
21037
- : value;
21542
+ const getterWithBase = getter.replace(/\?source\b/g, `<${instance.id}>`).replace(/<Base>/g, `<${instance.id}>`).replace(/\bBase\b/g, `<${instance.id}>`);
21543
+ const trimmed = getterWithBase.trim().toUpperCase();
21544
+ if (trimmed.startsWith('SELECT') || trimmed.startsWith('ASK') || trimmed.startsWith('CONSTRUCT')) {
21545
+ // Native SPARQL getter — execute directly
21546
+ const result = await perspective.querySparql(getterWithBase);
21547
+ if (result && result.length > 0) {
21548
+ const values = result.map((r) => {
21549
+ const firstKey = Object.keys(r)[0];
21550
+ return r[firstKey]?.value ?? r[firstKey];
21551
+ }).filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None');
21552
+ instance[relName] = values;
21553
+ }
21554
+ }
21555
+ else {
21556
+ // Legacy SurrealDB-style getter — no longer supported
21557
+ console.warn(`Unsupported legacy getter syntax for relation ${relName} — use native SPARQL (SELECT/ASK): ${getter.slice(0, 100)}`);
21038
21558
  }
21039
21559
  }
21040
21560
  catch (error) {
21041
21561
  console.warn(`Failed to evaluate getter for ${relName}:`, error);
21042
21562
  }
21043
21563
  }
21564
+ // JS post-filter for where conditions that couldn't be SPARQL-filtered
21565
+ // (e.g. literal-resolved properties storing signed expressions)
21566
+ const currentValues = instance[relName];
21567
+ if (meta.where && Array.isArray(currentValues) && currentValues.length > 0) {
21568
+ const TargetClass = meta.target?.();
21569
+ if (TargetClass) {
21570
+ const filtered = [];
21571
+ for (const targetId of currentValues) {
21572
+ try {
21573
+ const inst = new TargetClass(perspective, targetId);
21574
+ await inst.get();
21575
+ let matches = true;
21576
+ for (const [prop, expected] of Object.entries(meta.where)) {
21577
+ if (inst[prop] !== expected) {
21578
+ matches = false;
21579
+ break;
21580
+ }
21581
+ }
21582
+ if (matches)
21583
+ filtered.push(targetId);
21584
+ }
21585
+ catch {
21586
+ // If we can't hydrate, keep the value (conservative)
21587
+ filtered.push(targetId);
21588
+ }
21589
+ }
21590
+ instance[relName] = filtered;
21591
+ }
21592
+ }
21044
21593
  }
21045
21594
  }
21046
21595
  /**
@@ -21555,7 +22104,7 @@ class Ad4mModel {
21555
22104
  * const recipe = new Recipe(perspective);
21556
22105
  *
21557
22106
  * // Create with specific base expression
21558
- * const recipe = new Recipe(perspective, "literal://...");
22107
+ * const recipe = new Recipe(perspective, "literal:...");
21559
22108
  * ```
21560
22109
  */
21561
22110
  constructor(perspective, baseExpression) {
@@ -21782,19 +22331,13 @@ class Ad4mModel {
21782
22331
  }
21783
22332
  async getData(opts) {
21784
22333
  // Builds an object with the author, timestamp, all properties, & all relations on the Ad4mModel and saves it to the instance
21785
- // Use SurrealDB for data queries
22334
+ // Use SPARQL for data queries
21786
22335
  try {
21787
22336
  const ctor = this.constructor;
21788
22337
  const metadata = ctor.getModelMetadata();
21789
22338
  // Query for all links from this specific node (base expression)
21790
- const safeBaseExpression = formatSurrealValue(this._baseExpression);
21791
- const linksQuery = `
21792
- SELECT id, predicate, out.uri AS target, author, timestamp
21793
- FROM link
21794
- WHERE in.uri = ${safeBaseExpression}
21795
- ORDER BY timestamp ASC
21796
- `;
21797
- const links = await this._perspective.querySurrealDB(linksQuery);
22339
+ const linksQuery = buildSPARQLGetDataQuery(this._baseExpression);
22340
+ const links = await this._perspective.querySparql(linksQuery);
21798
22341
  if (links && links.length > 0) {
21799
22342
  // Core hydration: properties (latest-wins), relations, timestamps/author
21800
22343
  const requestedProperties = opts?.properties && opts.properties.length > 0 ? opts.properties : undefined;
@@ -21819,7 +22362,7 @@ class Ad4mModel {
21819
22362
  this[relName] = sourceIds;
21820
22363
  }
21821
22364
  }
21822
- // Evaluate SurrealQL getters
22365
+ // Evaluate SPARQL getters
21823
22366
  const getterOpts = opts?.properties || opts?.include
21824
22367
  ? { requestedProperties: opts?.properties, include: opts?.include }
21825
22368
  : undefined;
@@ -21830,7 +22373,7 @@ class Ad4mModel {
21830
22373
  }
21831
22374
  }
21832
22375
  catch (e) {
21833
- console.error(`SurrealDB getData also failed for ${this._baseExpression}:`, e);
22376
+ console.error(`SPARQL getData also failed for ${this._baseExpression}:`, e);
21834
22377
  }
21835
22378
  this.takeSnapshot();
21836
22379
  return this;
@@ -21860,13 +22403,13 @@ class Ad4mModel {
21860
22403
  return fullQuery;
21861
22404
  }
21862
22405
  /**
21863
- * Generates a SurrealQL query from a Query object.
22406
+ * Generates a SPARQL query from a Query object.
21864
22407
  *
21865
22408
  * @description
21866
- * This method translates high-level query parameters into a SurrealQL query string
21867
- * that can be executed against the SurrealDB backend. Unlike Prolog queries which
21868
- * operate on SDNA-aware predicates, SurrealQL queries operate directly on raw links
21869
- * stored in SurrealDB.
22409
+ * This method translates high-level query parameters into a SPARQL query string
22410
+ * that can be executed against the SPARQL backend. Unlike Prolog queries which
22411
+ * operate on SDNA-aware predicates, SPARQL queries operate directly on raw links
22412
+ * stored in SPARQL.
21870
22413
  *
21871
22414
  * The generated query uses a CTE (Common Table Expression) pattern:
21872
22415
  * 1. First, identify candidate base expressions by filtering links based on where conditions
@@ -21874,7 +22417,7 @@ class Ad4mModel {
21874
22417
  * 3. Finally, apply ordering, pagination (LIMIT/START) at the SQL level
21875
22418
  *
21876
22419
  * Key architectural notes:
21877
- * - SurrealDB stores only raw links (source, predicate, target, author, timestamp)
22420
+ * - SPARQL stores only raw links (source, predicate, target, author, timestamp)
21878
22421
  * - No SDNA knowledge at the database level
21879
22422
  * - Properties are resolved via subqueries that look for links with specific predicates
21880
22423
  * - Relations are similar but return multiple values instead of one
@@ -21882,11 +22425,11 @@ class Ad4mModel {
21882
22425
  *
21883
22426
  * @param perspective - The perspective to query (used for metadata extraction)
21884
22427
  * @param query - Query parameters (where, order, limit, offset, properties, relations)
21885
- * @returns Complete SurrealQL query string ready for execution
22428
+ * @returns Complete SPARQL query string ready for execution
21886
22429
  *
21887
22430
  * @example
21888
22431
  * ```typescript
21889
- * const query = Recipe.queryToSurrealQL(perspective, {
22432
+ * const query = Recipe.queryToSPARQL(perspective, {
21890
22433
  * where: { name: "Pasta", rating: { gt: 4 } },
21891
22434
  * order: { timestamp: "DESC" },
21892
22435
  * limit: 10
@@ -21895,10 +22438,10 @@ class Ad4mModel {
21895
22438
  * // FROM link WHERE ... GROUP BY source ORDER BY timestamp DESC LIMIT 10
21896
22439
  * ```
21897
22440
  */
21898
- static async queryToSurrealQL(perspective, query) {
22441
+ static async queryToSPARQL(perspective, query) {
21899
22442
  const metadata = this.getModelMetadata();
21900
22443
  const allRelMeta = getRelationsMetadata(this);
21901
- return buildSurrealQLQuery(metadata, allRelMeta, query, this);
22444
+ return buildSPARQLQuery(metadata, allRelMeta, query, this);
21902
22445
  }
21903
22446
  static async instancesFromPrologResult(perspective, query, result) {
21904
22447
  if (!result?.[0]?.AllInstances)
@@ -21943,16 +22486,16 @@ class Ad4mModel {
21943
22486
  return { results: instances, totalCount: result[0].TotalCount };
21944
22487
  }
21945
22488
  /**
21946
- * Converts SurrealDB query results to Ad4mModel instances.
22489
+ * Converts SPARQL query results to Ad4mModel instances.
21947
22490
  *
21948
22491
  * @param perspective - The perspective context
21949
22492
  * @param query - The query parameters used
21950
- * @param result - Array of result objects from SurrealDB
22493
+ * @param result - Array of result objects from SPARQL
21951
22494
  * @returns Promise resolving to results with total count
21952
22495
  *
21953
22496
  * @internal
21954
22497
  */
21955
- static async instancesFromSurrealResult(perspective, query, result) {
22498
+ static async instancesFromQueryResult(perspective, query, result) {
21956
22499
  if (!result || result.length === 0)
21957
22500
  return { results: [], totalCount: 0 };
21958
22501
  const metadata = this.getModelMetadata();
@@ -21973,33 +22516,25 @@ class Ad4mModel {
21973
22516
  }
21974
22517
  const links = row.links || [];
21975
22518
  const instance = new this(perspective, base);
21976
- // Core hydration via unified helper (pass requestedProperties for sparse fieldset)
21977
- await hydrateFromLinks(instance, links, metadata, perspective, requestedProperties.length > 0 ? requestedProperties : undefined);
21978
- // When specific properties are requested, delete unrequested properties
21979
- // so they return undefined instead of their constructor defaults (e.g. 0, [])
21980
- if (requestedProperties.length > 0) {
21981
- const requested = new Set(requestedProperties);
21982
- for (const propName of Object.keys(metadata.properties)) {
21983
- if (!requested.has(propName)) {
21984
- delete instance[propName];
21985
- }
21986
- }
21987
- for (const relName of Object.keys(metadata.relations)) {
21988
- if (!requested.has(relName) && !(query.include && relName in query.include)) {
21989
- delete instance[relName];
21990
- }
21991
- }
21992
- // Also strip metadata fields unless explicitly requested
21993
- for (const metaField of ['author', 'createdAt', 'updatedAt']) {
21994
- if (!requested.has(metaField)) {
21995
- delete instance[metaField];
22519
+ // Core hydration via unified helper (pass requestedProperties for sparse fieldset).
22520
+ // Also hydrate any properties referenced in `where` so the JS post-filter can match them,
22521
+ // even if they're not in the user's `properties` projection.
22522
+ let hydrationProps = requestedProperties.length > 0 ? [...requestedProperties] : undefined;
22523
+ if (hydrationProps && query.where) {
22524
+ for (const key of Object.keys(query.where)) {
22525
+ if (!hydrationProps.includes(key)) {
22526
+ hydrationProps.push(key);
21996
22527
  }
21997
22528
  }
21998
22529
  }
22530
+ await hydrateFromLinks(instance, links, metadata, perspective, hydrationProps);
22531
+ // NOTE: Property deletion for sparse fieldsets is deferred until AFTER
22532
+ // where-filtering so that where conditions can reference any property,
22533
+ // even ones not in the `properties` projection.
21999
22534
  instances.push(instance);
22000
22535
  }
22001
22536
  catch (error) {
22002
- console.error(`Failed to process SurrealDB instance ${base}:`, error);
22537
+ console.error(`Failed to process SPARQL instance ${base}:`, error);
22003
22538
  }
22004
22539
  }
22005
22540
  // Populate reverse relation fields (belongsToOne / belongsToMany) as string IDs.
@@ -22032,17 +22567,19 @@ class Ad4mModel {
22032
22567
  for (const instance of instances) {
22033
22568
  await evaluateCustomGettersForInstance(instance, perspective, metadata, getterOpts);
22034
22569
  }
22035
- // Filter by where conditions that couldn't be filtered in SQL
22570
+ // Filter by where conditions that couldn't be filtered in SPARQL
22036
22571
  // This includes:
22037
22572
  // - author/timestamp (computed from grouped links)
22038
22573
  // - Properties with comparison operators (gt, gte, lt, lte, between, contains)
22039
- // because fn::parse_literal() comparisons in SurrealDB subqueries don't work reliably
22574
+ // because fn::parse_literal() comparisons in SPARQL subqueries don't work reliably
22575
+ // - Relation-based where clauses (e.g., { post: postId } for @BelongsToOne)
22576
+ // which require reverse-link resolution before filtering
22040
22577
  let filteredInstances = instances;
22041
22578
  if (query.where) {
22042
22579
  filteredInstances = instances.filter(instance => {
22043
22580
  for (const [propertyName, condition] of Object.entries(query.where)) {
22044
- // Skip 'base' as it's filtered in SQL
22045
- if (propertyName === 'base')
22581
+ // Skip 'base'/'id' as it's filtered in SPARQL
22582
+ if (propertyName === 'base' || propertyName === 'id')
22046
22583
  continue;
22047
22584
  // For author and timestamp, always filter in JS
22048
22585
  if (propertyName === 'author' || propertyName === 'timestamp') {
@@ -22051,19 +22588,20 @@ class Ad4mModel {
22051
22588
  }
22052
22589
  continue;
22053
22590
  }
22054
- // For regular properties, only filter comparison operators in JS
22055
- // Simple equality and NOT are handled in SQL, but gt/gte/lt/lte/between/contains need JS
22056
- if (typeof condition === 'object' && condition !== null && !Array.isArray(condition)) {
22057
- const ops = condition;
22058
- // Check if any comparison operators are present
22059
- const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
22060
- ops.lt !== undefined || ops.lte !== undefined ||
22061
- ops.between !== undefined || ops.contains !== undefined;
22062
- if (hasComparisonOps) {
22063
- if (!matchesCondition(instance[propertyName], condition)) {
22064
- return false;
22065
- }
22591
+ // Check if this is a relation field (not in properties metadata)
22592
+ const isPropField = propertyName in metadata.properties;
22593
+ if (!isPropField) {
22594
+ // Relation-based where — filter in JS against the populated field
22595
+ if (!matchesCondition(instance[propertyName], condition)) {
22596
+ return false;
22066
22597
  }
22598
+ continue;
22599
+ }
22600
+ // Filter ALL property conditions in JS (equality, NOT, IN, comparison operators).
22601
+ // SPARQL-level filtering with parse_literal is unreliable across environments,
22602
+ // so we do all property filtering here after hydration resolves values.
22603
+ if (!matchesCondition(instance[propertyName], condition)) {
22604
+ return false;
22067
22605
  }
22068
22606
  }
22069
22607
  return true;
@@ -22115,6 +22653,28 @@ class Ad4mModel {
22115
22653
  const end = query.limit ? start + query.limit : undefined;
22116
22654
  paginatedInstances = filteredInstances.slice(start, end);
22117
22655
  }
22656
+ // Now that where-filtering is done, strip unrequested properties for sparse fieldsets.
22657
+ // This must happen AFTER where-filtering so conditions can reference any property.
22658
+ if (requestedProperties.length > 0) {
22659
+ const requested = new Set(requestedProperties);
22660
+ for (const inst of paginatedInstances) {
22661
+ for (const propName of Object.keys(metadata.properties)) {
22662
+ if (!requested.has(propName)) {
22663
+ delete inst[propName];
22664
+ }
22665
+ }
22666
+ for (const relName of Object.keys(metadata.relations)) {
22667
+ if (!requested.has(relName) && !(query.include && relName in query.include)) {
22668
+ delete inst[relName];
22669
+ }
22670
+ }
22671
+ for (const metaField of ['author', 'createdAt', 'updatedAt']) {
22672
+ if (!requested.has(metaField)) {
22673
+ delete inst[metaField];
22674
+ }
22675
+ }
22676
+ }
22677
+ }
22118
22678
  // Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
22119
22679
  if (query.include && paginatedInstances.length > 0) {
22120
22680
  await hydrateRelations(this, paginatedInstances, perspective, query.include);
@@ -22139,15 +22699,15 @@ class Ad4mModel {
22139
22699
  *
22140
22700
  * @param perspective - The perspective to search in
22141
22701
  * @param query - Optional query parameters to filter results
22142
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
22702
+ * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
22143
22703
  * @returns Array of matching models
22144
22704
  *
22145
22705
  * @example
22146
22706
  * ```typescript
22147
- * // Get all recipes (uses SurrealDB by default)
22707
+ * // Get all recipes (uses SPARQL by default)
22148
22708
  * const allRecipes = await Recipe.findAll(perspective);
22149
22709
  *
22150
- * // Get recipes with specific criteria (uses SurrealDB)
22710
+ * // Get recipes with specific criteria (uses SPARQL)
22151
22711
  * const recipes = await Recipe.findAll(perspective, {
22152
22712
  * where: {
22153
22713
  * name: "Pasta",
@@ -22161,14 +22721,23 @@ class Ad4mModel {
22161
22721
  * const recipesProlog = await Recipe.findAll(perspective, {}, false);
22162
22722
  * ```
22163
22723
  */
22164
- static async findAll(perspective, query = {}, useSurrealDB = true) {
22724
+ static async findAll(perspective, query = {}, engine = 'sparql') {
22165
22725
  if (query.properties && query.properties.length === 0) {
22166
22726
  throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
22167
22727
  }
22168
- if (useSurrealDB) {
22169
- const surrealQuery = await this.queryToSurrealQL(perspective, query);
22170
- const result = await perspective.querySurrealDB(surrealQuery);
22171
- const { results } = await this.instancesFromSurrealResult(perspective, query, result);
22728
+ // Backward compatibility: boolean maps to sparql (true) or prolog (false)
22729
+ const resolvedEngine = typeof engine === 'boolean'
22730
+ ? (engine ? 'sparql' : 'prolog')
22731
+ : engine;
22732
+ if (resolvedEngine === 'sparql') {
22733
+ // Always use the regular SPARQL path + JS-level hydrateRelations for includes.
22734
+ // The batch SPARQL approach had issues with sub-queries (where/order/limit on includes),
22735
+ // non-conforming node filtering, and parse_literal compatibility.
22736
+ // hydrateRelations handles all of these correctly via per-relation findAll calls.
22737
+ const sparqlQuery = await this.queryToSPARQL(perspective, query);
22738
+ const rawResult = await perspective.querySparql(sparqlQuery);
22739
+ const grouped = groupSPARQLResults(rawResult);
22740
+ const { results } = await this.instancesFromQueryResult(perspective, query, grouped);
22172
22741
  return results;
22173
22742
  }
22174
22743
  else {
@@ -22185,7 +22754,7 @@ class Ad4mModel {
22185
22754
  *
22186
22755
  * @param perspective - The perspective to search in
22187
22756
  * @param query - Optional query parameters to filter results
22188
- * @param useSurrealDB - Whether to use SurrealDB (default: true) or Prolog (legacy)
22757
+ * @param useSPARQL - Whether to use SPARQL (default: true) or Prolog (legacy)
22189
22758
  * @returns The first matching instance, or `null`
22190
22759
  *
22191
22760
  * @example
@@ -22198,9 +22767,9 @@ class Ad4mModel {
22198
22767
  * }
22199
22768
  * ```
22200
22769
  */
22201
- static async findOne(perspective, query = {}, useSurrealDB = true) {
22770
+ static async findOne(perspective, query = {}, engine = 'sparql') {
22202
22771
  const limitedQuery = { ...query, limit: 1 };
22203
- const results = await this.findAll(perspective, limitedQuery, useSurrealDB);
22772
+ const results = await this.findAll(perspective, limitedQuery, engine);
22204
22773
  return results[0] ?? null;
22205
22774
  }
22206
22775
  /**
@@ -22208,7 +22777,7 @@ class Ad4mModel {
22208
22777
  *
22209
22778
  * @param perspective - The perspective to search in
22210
22779
  * @param query - Optional query parameters to filter results
22211
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
22780
+ * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
22212
22781
  * @returns Object containing results array and total count
22213
22782
  *
22214
22783
  * @example
@@ -22223,11 +22792,15 @@ class Ad4mModel {
22223
22792
  * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
22224
22793
  * ```
22225
22794
  */
22226
- static async findAllAndCount(perspective, query = {}, useSurrealDB = true) {
22227
- if (useSurrealDB) {
22228
- const surrealQuery = await this.queryToSurrealQL(perspective, query);
22229
- const result = await perspective.querySurrealDB(surrealQuery);
22230
- return await this.instancesFromSurrealResult(perspective, query, result);
22795
+ static async findAllAndCount(perspective, query = {}, engine = 'sparql') {
22796
+ const resolvedEngine = typeof engine === 'boolean'
22797
+ ? (engine ? 'sparql' : 'prolog')
22798
+ : engine;
22799
+ if (resolvedEngine === 'sparql') {
22800
+ const sparqlQuery = await this.queryToSPARQL(perspective, query);
22801
+ const rawResult = await perspective.querySparql(sparqlQuery);
22802
+ const grouped = groupSPARQLResults(rawResult);
22803
+ return await this.instancesFromQueryResult(perspective, query, grouped);
22231
22804
  }
22232
22805
  else {
22233
22806
  const prologQuery = await this.queryToProlog(perspective, query);
@@ -22242,7 +22815,7 @@ class Ad4mModel {
22242
22815
  * @param pageSize - Number of items per page
22243
22816
  * @param pageNumber - Which page to retrieve (1-based)
22244
22817
  * @param query - Optional additional query parameters
22245
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
22818
+ * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
22246
22819
  * @returns Paginated results with metadata
22247
22820
  *
22248
22821
  * @example
@@ -22256,12 +22829,16 @@ class Ad4mModel {
22256
22829
  * const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
22257
22830
  * ```
22258
22831
  */
22259
- static async paginate(perspective, pageSize, pageNumber, query, useSurrealDB = true) {
22832
+ static async paginate(perspective, pageSize, pageNumber, query, engine = 'sparql') {
22260
22833
  const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
22261
- if (useSurrealDB) {
22262
- const surrealQuery = await this.queryToSurrealQL(perspective, paginationQuery);
22263
- const result = await perspective.querySurrealDB(surrealQuery);
22264
- const { results, totalCount } = await this.instancesFromSurrealResult(perspective, paginationQuery, result);
22834
+ const resolvedEngine = typeof engine === 'boolean'
22835
+ ? (engine ? 'sparql' : 'prolog')
22836
+ : engine;
22837
+ if (resolvedEngine === 'sparql') {
22838
+ const sparqlQuery = await this.queryToSPARQL(perspective, paginationQuery);
22839
+ const rawResult = await perspective.querySparql(sparqlQuery);
22840
+ const grouped = groupSPARQLResults(rawResult);
22841
+ const { results, totalCount } = await this.instancesFromQueryResult(perspective, paginationQuery, grouped);
22265
22842
  return { results, totalCount, pageSize, pageNumber };
22266
22843
  }
22267
22844
  else {
@@ -22290,28 +22867,28 @@ class Ad4mModel {
22290
22867
  return fullQuery;
22291
22868
  }
22292
22869
  /**
22293
- * Generates a SurrealQL COUNT query for the model.
22870
+ * Generates a SPARQL COUNT query for the model.
22294
22871
  *
22295
22872
  * @param perspective - The perspective context
22296
22873
  * @param query - Query parameters to filter the count
22297
- * @returns SurrealQL COUNT query string
22874
+ * @returns SPARQL COUNT query string
22298
22875
  *
22299
22876
  * @private
22300
22877
  */
22301
- static async countQueryToSurrealQL(perspective, query) {
22878
+ static async countQueryToSPARQL(perspective, query) {
22302
22879
  // Use the same query as the main query (with GROUP BY), just without LIMIT/OFFSET
22303
22880
  // We'll count the number of rows returned (one row per source)
22304
22881
  const countQuery = { ...query };
22305
22882
  delete countQuery.limit;
22306
22883
  delete countQuery.offset;
22307
- return await this.queryToSurrealQL(perspective, countQuery);
22884
+ return await this.queryToSPARQL(perspective, countQuery);
22308
22885
  }
22309
22886
  /**
22310
22887
  * Gets a count of all matching instances.
22311
22888
  *
22312
22889
  * @param perspective - The perspective to search in
22313
22890
  * @param query - Optional query parameters to filter results
22314
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
22891
+ * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
22315
22892
  * @returns Total count of matching entities
22316
22893
  *
22317
22894
  * @example
@@ -22325,14 +22902,15 @@ class Ad4mModel {
22325
22902
  * const countProlog = await Recipe.count(perspective, {}, false);
22326
22903
  * ```
22327
22904
  */
22328
- static async count(perspective, query = {}, useSurrealDB = true) {
22329
- if (useSurrealDB) {
22330
- const surrealQuery = await this.queryToSurrealQL(perspective, query);
22331
- const result = await perspective.querySurrealDB(surrealQuery);
22332
- // Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
22333
- // (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
22334
- // This ensures count() returns the same number as findAll().length
22335
- const { totalCount } = await this.instancesFromSurrealResult(perspective, query, result);
22905
+ static async count(perspective, query = {}, engine = 'sparql') {
22906
+ const resolvedEngine = typeof engine === 'boolean'
22907
+ ? (engine ? 'sparql' : 'prolog')
22908
+ : engine;
22909
+ if (resolvedEngine === 'sparql') {
22910
+ const sparqlQuery = await this.queryToSPARQL(perspective, query);
22911
+ const rawResult = await perspective.querySparql(sparqlQuery);
22912
+ const grouped = groupSPARQLResults(rawResult);
22913
+ const { totalCount } = await this.instancesFromQueryResult(perspective, query, grouped);
22336
22914
  return totalCount;
22337
22915
  }
22338
22916
  else {
@@ -22350,7 +22928,7 @@ class Ad4mModel {
22350
22928
  const actions = this.generatePropertySetterAction(key, metadata);
22351
22929
  // Get resolve language from metadata (replaces Prolog query)
22352
22930
  let resolveLanguage = metadata.resolveLanguage;
22353
- // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal://string:)
22931
+ // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal:string:)
22354
22932
  if (value === undefined || value === null || value === "") {
22355
22933
  return;
22356
22934
  }
@@ -23217,6 +23795,16 @@ input CapabilityInput {
23217
23795
  with: ResourceInput!
23218
23796
  }
23219
23797
 
23798
+ type ComputeLogEntry {
23799
+ cost: Float!
23800
+ creditsAfter: Float!
23801
+ id: Float!
23802
+ operation: String!
23803
+ summary: String
23804
+ timestamp: String!
23805
+ userEmail: String!
23806
+ }
23807
+
23220
23808
  scalar DateTime
23221
23809
 
23222
23810
  type EntanglementProof {
@@ -23513,6 +24101,7 @@ type Mutation {
23513
24101
  runtimeRequestPayment(amountHOT: String!): PaymentRequestResult!
23514
24102
  runtimeRestartHolochain: Boolean!
23515
24103
  runtimeSendHot(amount: String!, recipient: String!): PaymentRequestResult!
24104
+ runtimeSetFreeHostingEnabled(enabled: Boolean!): Boolean!
23516
24105
  runtimeSetHotWalletAddress(address: String!): Boolean!
23517
24106
  runtimeSetMultiUserEnabled(enabled: Boolean!): Boolean!
23518
24107
  runtimeSetStatus(status: PerspectiveInput!): Boolean!
@@ -23624,9 +24213,10 @@ type Query {
23624
24213
  perspective(uuid: String!): PerspectiveHandle
23625
24214
  perspectiveQueryLinks(query: LinkQuery!, uuid: String!): [LinkExpression!]
23626
24215
  perspectiveQueryProlog(query: String!, uuid: String!): String!
23627
- perspectiveQuerySurrealDB(query: String!, uuid: String!): String!
23628
24216
  perspectiveSnapshot(uuid: String!): Perspective
23629
24217
  perspectives: [PerspectiveHandle!]!
24218
+ runtimeComputeLog(limit: Float, since: String, userEmail: String): [ComputeLogEntry!]!
24219
+ runtimeFreeHostingEnabled: Boolean!
23630
24220
  runtimeFriendStatus(did: String!): PerspectiveExpression
23631
24221
  runtimeFriends: [String!]!
23632
24222
  runtimeGetNetworkMetrics: String!
@@ -23642,6 +24232,7 @@ type Query {
23642
24232
  runtimeMessageOutbox(filter: String): [SentMessage!]!
23643
24233
  runtimeMultiUserEnabled: Boolean!
23644
24234
  runtimeNotifications: [Notification!]!
24235
+ runtimeUnytAgentKey: String!
23645
24236
  runtimeUnytVersionInfo: String!
23646
24237
  runtimeVerifyStringSignedByDid(data: String!, did: String!, didSigningKeyId: String!, signedData: String!): Boolean!
23647
24238
  }
@@ -24099,6 +24690,49 @@ exports.PaymentRequestResult = __decorate([
24099
24690
  ObjectType(),
24100
24691
  __metadata("design:paramtypes", [Boolean, String])
24101
24692
  ], exports.PaymentRequestResult);
24693
+ exports.ComputeLogEntry = class ComputeLogEntry {
24694
+ constructor(id, userEmail, timestamp, operation, cost, creditsAfter, summary) {
24695
+ this.id = id;
24696
+ this.userEmail = userEmail;
24697
+ this.timestamp = timestamp;
24698
+ this.operation = operation;
24699
+ this.cost = cost;
24700
+ this.creditsAfter = creditsAfter;
24701
+ this.summary = summary;
24702
+ }
24703
+ };
24704
+ __decorate([
24705
+ Field(),
24706
+ __metadata("design:type", Number)
24707
+ ], exports.ComputeLogEntry.prototype, "id", void 0);
24708
+ __decorate([
24709
+ Field(),
24710
+ __metadata("design:type", String)
24711
+ ], exports.ComputeLogEntry.prototype, "userEmail", void 0);
24712
+ __decorate([
24713
+ Field(),
24714
+ __metadata("design:type", String)
24715
+ ], exports.ComputeLogEntry.prototype, "timestamp", void 0);
24716
+ __decorate([
24717
+ Field(),
24718
+ __metadata("design:type", String)
24719
+ ], exports.ComputeLogEntry.prototype, "operation", void 0);
24720
+ __decorate([
24721
+ Field(),
24722
+ __metadata("design:type", String)
24723
+ ], exports.ComputeLogEntry.prototype, "summary", void 0);
24724
+ __decorate([
24725
+ Field(),
24726
+ __metadata("design:type", Number)
24727
+ ], exports.ComputeLogEntry.prototype, "cost", void 0);
24728
+ __decorate([
24729
+ Field(),
24730
+ __metadata("design:type", Number)
24731
+ ], exports.ComputeLogEntry.prototype, "creditsAfter", void 0);
24732
+ exports.ComputeLogEntry = __decorate([
24733
+ ObjectType(),
24734
+ __metadata("design:paramtypes", [Number, String, String, String, Number, Number, String])
24735
+ ], exports.ComputeLogEntry);
24102
24736
  /**
24103
24737
  * Resolver classes are used here to define the GraphQL schema
24104
24738
  * (through the type-graphql annotations)
@@ -24254,6 +24888,12 @@ let RuntimeResolver = class RuntimeResolver {
24254
24888
  runtimeSetMultiUserEnabled(enabled) {
24255
24889
  return enabled;
24256
24890
  }
24891
+ runtimeFreeHostingEnabled() {
24892
+ return true;
24893
+ }
24894
+ runtimeSetFreeHostingEnabled(enabled) {
24895
+ return enabled;
24896
+ }
24257
24897
  runtimeListUsers() {
24258
24898
  return [{
24259
24899
  email: "test@example.com",
@@ -24313,6 +24953,9 @@ let RuntimeResolver = class RuntimeResolver {
24313
24953
  runtimeHostingUserInfo() {
24314
24954
  return new exports.HostingUserInfo("test@example.com", "100000000", null, false);
24315
24955
  }
24956
+ runtimeComputeLog(since, limit, userEmail) {
24957
+ return [];
24958
+ }
24316
24959
  runtimeSetHotWalletAddress(address) {
24317
24960
  return true;
24318
24961
  }
@@ -24343,6 +24986,9 @@ let RuntimeResolver = class RuntimeResolver {
24343
24986
  runtimeHotAgentPubkey() {
24344
24987
  return "";
24345
24988
  }
24989
+ runtimeUnytAgentKey() {
24990
+ return "";
24991
+ }
24346
24992
  runtimeUnytVersionInfo() {
24347
24993
  return "";
24348
24994
  }
@@ -24592,6 +25238,19 @@ __decorate([
24592
25238
  __metadata("design:paramtypes", [Boolean]),
24593
25239
  __metadata("design:returntype", Boolean)
24594
25240
  ], RuntimeResolver.prototype, "runtimeSetMultiUserEnabled", null);
25241
+ __decorate([
25242
+ Query(),
25243
+ __metadata("design:type", Function),
25244
+ __metadata("design:paramtypes", []),
25245
+ __metadata("design:returntype", Boolean)
25246
+ ], RuntimeResolver.prototype, "runtimeFreeHostingEnabled", null);
25247
+ __decorate([
25248
+ Mutation(),
25249
+ __param(0, Arg()),
25250
+ __metadata("design:type", Function),
25251
+ __metadata("design:paramtypes", [Boolean]),
25252
+ __metadata("design:returntype", Boolean)
25253
+ ], RuntimeResolver.prototype, "runtimeSetFreeHostingEnabled", null);
24595
25254
  __decorate([
24596
25255
  Query(),
24597
25256
  __metadata("design:type", Function),
@@ -24679,6 +25338,15 @@ __decorate([
24679
25338
  __metadata("design:paramtypes", []),
24680
25339
  __metadata("design:returntype", exports.HostingUserInfo)
24681
25340
  ], RuntimeResolver.prototype, "runtimeHostingUserInfo", null);
25341
+ __decorate([
25342
+ Query(),
25343
+ __param(0, Arg()),
25344
+ __param(1, Arg()),
25345
+ __param(2, Arg()),
25346
+ __metadata("design:type", Function),
25347
+ __metadata("design:paramtypes", [String, Number, String]),
25348
+ __metadata("design:returntype", Array)
25349
+ ], RuntimeResolver.prototype, "runtimeComputeLog", null);
24682
25350
  __decorate([
24683
25351
  Mutation(),
24684
25352
  __param(0, Arg()),
@@ -24750,6 +25418,12 @@ __decorate([
24750
25418
  __metadata("design:paramtypes", []),
24751
25419
  __metadata("design:returntype", String)
24752
25420
  ], RuntimeResolver.prototype, "runtimeHotAgentPubkey", null);
25421
+ __decorate([
25422
+ Query(),
25423
+ __metadata("design:type", Function),
25424
+ __metadata("design:paramtypes", []),
25425
+ __metadata("design:returntype", String)
25426
+ ], RuntimeResolver.prototype, "runtimeUnytAgentKey", null);
24753
25427
  __decorate([
24754
25428
  Query(),
24755
25429
  __metadata("design:type", Function),
@@ -24795,7 +25469,6 @@ exports.buildAuthorAndTimestampQuery = buildAuthorAndTimestampQuery;
24795
25469
  exports.buildConformanceFilter = buildConformanceFilter;
24796
25470
  exports.buildConformanceGetter = buildConformanceGetter;
24797
25471
  exports.buildCountQuery = buildCountQuery;
24798
- exports.buildGraphTraversalWhereClause = buildGraphTraversalWhereClause;
24799
25472
  exports.buildLimitQuery = buildLimitQuery;
24800
25473
  exports.buildModelFromJSONSchema = buildModelFromJSONSchema;
24801
25474
  exports.buildOffsetQuery = buildOffsetQuery;
@@ -24804,23 +25477,34 @@ exports.buildParentQuery = buildParentQuery;
24804
25477
  exports.buildPropertiesQuery = buildPropertiesQuery;
24805
25478
  exports.buildSDNA = buildSDNA;
24806
25479
  exports.buildSHACL = buildSHACL;
24807
- exports.buildSurrealQLQuery = buildSurrealQLQuery;
25480
+ exports.buildSPARQLGetDataQuery = buildSPARQLGetDataQuery;
25481
+ exports.buildSPARQLQuery = buildSPARQLQuery;
25482
+ exports.buildWhereCondition = buildWhereCondition;
24808
25483
  exports.buildWhereQuery = buildWhereQuery;
24809
25484
  exports.capSentence = capSentence;
25485
+ exports.clearQueryCache = clearQueryCache;
25486
+ exports.clearSubscriptionPool = clearSubscriptionPool;
25487
+ exports.compileWhereClause = compileWhereClause;
24810
25488
  exports.determineNamespace = determineNamespace;
24811
25489
  exports.determinePredicate = determinePredicate;
24812
- exports.escapeSurrealString = escapeSurrealString;
25490
+ exports.escapeQueryString = escapeQueryString;
24813
25491
  exports.evaluateCustomGettersForInstance = evaluateCustomGettersForInstance;
24814
25492
  exports.exprRef2String = exprRef2String;
24815
25493
  exports.formatList = formatList;
25494
+ exports.formatQueryValue = formatQueryValue;
25495
+ exports.formatSPARQLValue = formatSPARQLValue;
24816
25496
  exports.generatePrologFacts = generatePrologFacts;
25497
+ exports.getCachedResult = getCachedResult;
24817
25498
  exports.getDefaultValueForType = getDefaultValueForType;
25499
+ exports.getMemoizedSHACL = getMemoizedSHACL;
24818
25500
  exports.getPropertiesMetadata = getPropertiesMetadata;
24819
25501
  exports.getPropertyOption = getPropertyOption;
24820
25502
  exports.getRelationsMetadata = getRelationsMetadata;
25503
+ exports.groupSPARQLResults = groupSPARQLResults;
24821
25504
  exports.hydrateFromLinks = hydrateFromLinks;
24822
25505
  exports.hydratePropertyValue = hydratePropertyValue;
24823
25506
  exports.hydrateRelations = hydrateRelations;
25507
+ exports.invalidatePerspectiveCache = invalidatePerspectiveCache;
24824
25508
  exports.isArrayType = isArrayType;
24825
25509
  exports.isExpression = isExpression;
24826
25510
  exports.isLink = isLink;
@@ -24833,7 +25517,11 @@ exports.normalizeNamespaceString = normalizeNamespaceString;
24833
25517
  exports.normalizeSchemaType = normalizeSchemaType;
24834
25518
  exports.normalizeValue = normalizeValue;
24835
25519
  exports.parseExprUrl = parseExprUrl;
25520
+ exports.pooledSubscribe = pooledSubscribe;
25521
+ exports.queryCacheSize = queryCacheSize;
24836
25522
  exports.resolveParentPredicate = resolveParentPredicate;
25523
+ exports.setCachedResult = setCachedResult;
24837
25524
  exports.setPropertyRegistryEntry = setPropertyRegistryEntry;
24838
25525
  exports.setRelationRegistryEntry = setRelationRegistryEntry;
25526
+ exports.subscriptionPoolSize = subscriptionPoolSize;
24839
25527
  exports.typeDefsString = typeDefsString;