@coasys/ad4m 0.11.2-dev-sdna-only-prolog → 0.11.2-dev.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.
package/lib/index.cjs CHANGED
@@ -4490,43 +4490,11 @@ class Subject {
4490
4490
  let results = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), property(C, Property)`);
4491
4491
  let properties = results.map(result => result.Property);
4492
4492
  for (let p of properties) {
4493
- const resolveExpressionURI = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), property_resolve(C, "${p}")`);
4493
+ await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), property_resolve(C, "${p}")`);
4494
4494
  Object.defineProperty(this, p, {
4495
4495
  configurable: true,
4496
4496
  get: async () => {
4497
- // Try Prolog first
4498
- try {
4499
- let results = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), property_getter(C, "${__classPrivateFieldGet$b(this, _Subject_baseExpression, "f")}", "${p}", Value)`);
4500
- if (results && results.length > 0 && results[0].Value !== undefined && results[0].Value !== null && results[0].Value !== '') {
4501
- let expressionURI = results[0].Value;
4502
- if (resolveExpressionURI) {
4503
- try {
4504
- if (expressionURI) {
4505
- const expression = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").getExpression(expressionURI);
4506
- try {
4507
- return JSON.parse(expression.data);
4508
- }
4509
- catch (e) {
4510
- return expression.data;
4511
- }
4512
- }
4513
- else {
4514
- return expressionURI;
4515
- }
4516
- }
4517
- catch (err) {
4518
- return expressionURI;
4519
- }
4520
- }
4521
- else {
4522
- return expressionURI;
4523
- }
4524
- }
4525
- }
4526
- catch (err) {
4527
- // Prolog query failed, fall through to SurrealDB
4528
- }
4529
- // Fallback to SurrealDB if Prolog returned nothing (SdnaOnly mode)
4497
+ // Use SurrealDB for data queries
4530
4498
  try {
4531
4499
  return await __classPrivateFieldGet$b(this, _Subject_perspective, "f").getPropertyValueViaSurreal(__classPrivateFieldGet$b(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$b(this, _Subject_subjectClassName, "f"), p);
4532
4500
  }
@@ -4565,20 +4533,7 @@ class Subject {
4565
4533
  Object.defineProperty(this, c, {
4566
4534
  configurable: true,
4567
4535
  get: async () => {
4568
- // Try Prolog first
4569
- try {
4570
- let results = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), collection_getter(C, "${__classPrivateFieldGet$b(this, _Subject_baseExpression, "f")}", "${c}", Value)`);
4571
- if (results && results.length > 0 && results[0].Value && Array.isArray(results[0].Value) && results[0].Value.length > 0) {
4572
- let collectionContent = results[0].Value.filter((v) => v !== "" && v !== '');
4573
- if (collectionContent.length > 0) {
4574
- return collectionContent;
4575
- }
4576
- }
4577
- }
4578
- catch (err) {
4579
- // Prolog query failed, fall through to SurrealDB
4580
- }
4581
- // Fallback to SurrealDB if Prolog returned nothing (SdnaOnly mode)
4536
+ // Use SurrealDB for data queries
4582
4537
  try {
4583
4538
  return await __classPrivateFieldGet$b(this, _Subject_perspective, "f").getCollectionValuesViaSurreal(__classPrivateFieldGet$b(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$b(this, _Subject_subjectClassName, "f"), c);
4584
4539
  }
@@ -4647,6 +4602,58 @@ class Subject {
4647
4602
  }
4648
4603
  _Subject_baseExpression = new WeakMap(), _Subject_subjectClassName = new WeakMap(), _Subject_perspective = new WeakMap();
4649
4604
 
4605
+ function formatList(list) {
4606
+ if (!list?.length) {
4607
+ return "";
4608
+ }
4609
+ if (list.length === 1) {
4610
+ return list.toString();
4611
+ }
4612
+ if (list.length === 2) {
4613
+ return list.join(' and ');
4614
+ }
4615
+ return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);
4616
+ }
4617
+ function capSentence(cap) {
4618
+ const can = cap.can.includes("*") ? ["READ", "WRITE", "UPDATE"] : cap.can;
4619
+ const domain = cap.with.domain === "*" ? "" : cap.with.domain;
4620
+ const pointers = cap.with.pointers.includes("*")
4621
+ ? ["all AD4M data"]
4622
+ : cap.with.pointers;
4623
+ return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
4624
+ }
4625
+ /**
4626
+ * Escapes a string value for safe use in SurrealQL queries.
4627
+ *
4628
+ * @description
4629
+ * Prevents SQL injection by properly escaping special characters in string values
4630
+ * that will be interpolated into SurrealQL queries. This handles the most common
4631
+ * special characters that could break SQL queries or enable injection attacks.
4632
+ *
4633
+ * Single quotes, backslashes, and other special characters are escaped using
4634
+ * backslash notation, which is the standard escaping mechanism for SurrealQL.
4635
+ *
4636
+ * @param value - The string value to escape
4637
+ * @returns The escaped string safe for SurrealQL interpolation (without surrounding quotes)
4638
+ *
4639
+ * @example
4640
+ * ```typescript
4641
+ * const userInput = "user's input with 'quotes'";
4642
+ * const escaped = escapeSurrealString(userInput);
4643
+ * const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
4644
+ * // Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''
4645
+ * ```
4646
+ */
4647
+ function escapeSurrealString(value) {
4648
+ return value
4649
+ .replace(/\\/g, '\\\\') // Backslash -> \\
4650
+ .replace(/'/g, "\\'") // Single quote -> \'
4651
+ .replace(/"/g, '\\"') // Double quote -> \"
4652
+ .replace(/\n/g, '\\n') // Newline -> \n
4653
+ .replace(/\r/g, '\\r') // Carriage return -> \r
4654
+ .replace(/\t/g, '\\t'); // Tab -> \t
4655
+ }
4656
+
4650
4657
  var __classPrivateFieldSet$a = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
4651
4658
  if (kind === "m") throw new TypeError("Private method is not writable");
4652
4659
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
@@ -5003,6 +5010,18 @@ class PerspectiveProxy {
5003
5010
  __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addPerspectiveLinkUpdatedListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f"));
5004
5011
  __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addPerspectiveSyncStateChangeListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, "f"));
5005
5012
  }
5013
+ /**
5014
+ * Escapes special regex characters in a string to prevent ReDoS attacks
5015
+ * and regex injection when building dynamic regular expressions.
5016
+ *
5017
+ * @param str - The string to escape
5018
+ * @returns The escaped string safe for use in RegExp constructor
5019
+ *
5020
+ * @private
5021
+ */
5022
+ escapeRegExp(str) {
5023
+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
5024
+ }
5006
5025
  /**
5007
5026
  * Executes a set of actions on an expression with optional parameters.
5008
5027
  * Used internally by Social DNA flows and subject class operations.
@@ -5606,34 +5625,43 @@ class PerspectiveProxy {
5606
5625
  // Get metadata from SDNA using Prolog metaprogramming
5607
5626
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
5608
5627
  if (!metadata) {
5609
- return false;
5628
+ // Fallback to Prolog check if SDNA metadata isn't available
5629
+ // This handles cases where classes exist in Prolog but not in SDNA
5630
+ try {
5631
+ const escapedClassName = className.replace(/"/g, '\\"');
5632
+ const escapedExpression = expression.replace(/"/g, '\\"');
5633
+ const result = await this.infer(`subject_class("${escapedClassName}", C), instance(C, "${escapedExpression}")`);
5634
+ return result && result.length > 0;
5635
+ }
5636
+ catch (e) {
5637
+ console.warn(`Failed to check instance via Prolog for class ${className}:`, e);
5638
+ return false;
5639
+ }
5610
5640
  }
5611
5641
  // If no required triples, any expression with links is an instance
5612
5642
  if (metadata.requiredTriples.length === 0) {
5613
- console.log("no required triples, checking surrealDB");
5614
- const checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${expression}'`;
5615
- console.log("checkQuery", checkQuery);
5643
+ const escapedExpression = escapeSurrealString(expression);
5644
+ const checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}'`;
5616
5645
  const result = await this.querySurrealDB(checkQuery);
5617
- console.log("result", result);
5618
5646
  const count = result[0]?.count ?? 0;
5619
5647
  const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
5620
5648
  return countValue > 0;
5621
5649
  }
5622
5650
  // Check if the expression has all required triples (predicate + optional exact target)
5623
5651
  for (const triple of metadata.requiredTriples) {
5624
- console.log("checking triple", triple);
5652
+ const escapedExpression = escapeSurrealString(expression);
5653
+ const escapedPredicate = escapeSurrealString(triple.predicate);
5625
5654
  let checkQuery;
5626
5655
  if (triple.target) {
5627
5656
  // Flag: must match both predicate AND exact target value
5628
- checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${expression}' AND predicate = '${triple.predicate}' AND out.uri = '${triple.target}'`;
5657
+ const escapedTarget = escapeSurrealString(triple.target);
5658
+ checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}' AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}'`;
5629
5659
  }
5630
5660
  else {
5631
5661
  // Property: just check predicate exists
5632
- checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${expression}' AND predicate = '${triple.predicate}'`;
5662
+ checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}' AND predicate = '${escapedPredicate}'`;
5633
5663
  }
5634
- console.log("checkQuery", checkQuery);
5635
5664
  const result = await this.querySurrealDB(checkQuery);
5636
- console.log("result", result);
5637
5665
  if (!result || result.length === 0) {
5638
5666
  return false;
5639
5667
  }
@@ -5673,8 +5701,9 @@ class PerspectiveProxy {
5673
5701
  async getSubjectClassMetadataFromSDNA(className) {
5674
5702
  try {
5675
5703
  // Get SDNA code from perspective - it's stored as a link
5704
+ // Use canonical Literal.from() to construct the source URL
5676
5705
  const sdnaLinks = await this.get(new exports.LinkQuery({
5677
- source: `literal://string:${className}`,
5706
+ source: Literal.from(className).toUrl(),
5678
5707
  predicate: "ad4m://sdna"
5679
5708
  }));
5680
5709
  //console.log(`getSubjectClassMetadataFromSDNA: sdnaLinks for ${className}:`, sdnaLinks);
@@ -5694,10 +5723,14 @@ class PerspectiveProxy {
5694
5723
  const requiredTriples = [];
5695
5724
  // Parse the instance rule from the SDNA code
5696
5725
  // Format: instance(c, Base) :- triple(Base, "pred1", _), triple(Base, "pred2", "exact_value").
5697
- const instanceRuleMatch = sdnaCode.match(/instance\([^,]+,\s*\w+\)\s*:-\s*(.+?)\./s);
5698
- if (instanceRuleMatch) {
5726
+ // Use a more robust pattern that handles complex rule bodies
5727
+ // Match from "instance(" to the closing "." using non-greedy matching
5728
+ const instanceRulePattern = /instance\([^)]+\)\s*:-\s*([^.]+)\./g;
5729
+ let instanceRuleMatch;
5730
+ let foundInstanceRule = false;
5731
+ while ((instanceRuleMatch = instanceRulePattern.exec(sdnaCode)) !== null) {
5732
+ foundInstanceRule = true;
5699
5733
  const ruleBody = instanceRuleMatch[1];
5700
- console.log("instance rule body:", ruleBody);
5701
5734
  // Extract all triple(Base, "predicate", Target) patterns
5702
5735
  // Match both: triple(Base, "pred", _) and triple(Base, "pred", "value")
5703
5736
  const tripleRegex = /triple\([^,]+,\s*"([^"]+)",\s*(?:"([^"]+)"|_)\)/g;
@@ -5706,15 +5739,13 @@ class PerspectiveProxy {
5706
5739
  const predicate = match[1];
5707
5740
  const target = match[2]; // undefined if matched "_"
5708
5741
  requiredTriples.push({ predicate, target });
5709
- console.log(`Extracted triple: predicate="${predicate}", target="${target}"`);
5710
5742
  }
5711
5743
  }
5712
- else {
5744
+ if (!foundInstanceRule) {
5713
5745
  console.warn(`No instance rule found in SDNA for ${className}`);
5714
5746
  }
5715
5747
  // For backward compatibility, also maintain requiredPredicates array
5716
5748
  const requiredPredicates = requiredTriples.map(t => t.predicate);
5717
- console.log("extracted requiredTriples:", requiredTriples);
5718
5749
  // Extract property metadata
5719
5750
  const properties = new Map();
5720
5751
  const propertyResults = await this.infer(`subject_class("${className}", C), property(C, P)`);
@@ -5735,7 +5766,9 @@ class PerspectiveProxy {
5735
5766
  // If no setter, try to extract from SDNA property_getter Prolog code
5736
5767
  if (!predicate) {
5737
5768
  // Parse the SDNA code for property_getter definition
5738
- const getterMatch = sdnaCode.match(new RegExp(`property_getter\\([^,]+,\\s*[^,]+,\\s*"${propName}"[^)]*\\)\\s*:-\\s*triple\\([^,]+,\\s*"([^"]+)"`));
5769
+ // Escape propName to prevent regex injection and ReDoS attacks
5770
+ const escapedPropName = this.escapeRegExp(propName);
5771
+ const getterMatch = sdnaCode.match(new RegExp(`property_getter\\([^,]+,\\s*[^,]+,\\s*"${escapedPropName}"[^)]*\\)\\s*:-\\s*triple\\([^,]+,\\s*"([^"]+)"`));
5739
5772
  if (getterMatch) {
5740
5773
  predicate = getterMatch[1];
5741
5774
  }
@@ -5771,7 +5804,9 @@ class PerspectiveProxy {
5771
5804
  // Format 1 (findall): collection_getter(c, Base, "comments", List) :- findall(C, triple(Base, "todo://comment", C), List).
5772
5805
  // Format 2 (setof): collection_getter(c, Base, "messages", List) :- setof(Target, (triple(Base, "flux://entry_type", Target), ...), List).
5773
5806
  // Use a line-based match to avoid capturing multiple collections
5774
- const getterLinePattern = new RegExp(`collection_getter\\([^,]+,\\s*[^,]+,\\s*"${collName}"[^)]*\\)\\s*:-[^.]+\\.`);
5807
+ // Escape collName to prevent regex injection and ReDoS attacks
5808
+ const escapedCollName = this.escapeRegExp(collName);
5809
+ const getterLinePattern = new RegExp(`collection_getter\\([^,]+,\\s*[^,]+,\\s*"${escapedCollName}"[^)]*\\)\\s*:-[^.]+\\.`);
5775
5810
  const getterLineMatch = sdnaCode.match(getterLinePattern);
5776
5811
  if (getterLineMatch) {
5777
5812
  const getterLine = getterLineMatch[0];
@@ -5785,7 +5820,6 @@ class PerspectiveProxy {
5785
5820
  if (getterBody.startsWith('(') && getterBody.endsWith(')')) {
5786
5821
  getterBody = getterBody.substring(1, getterBody.length - 1);
5787
5822
  }
5788
- console.log(`Collection "${collName}" getter body:`, getterBody);
5789
5823
  // Extract predicate from triple(Base, "predicate", Target)
5790
5824
  if (!predicate) {
5791
5825
  const tripleMatch = getterBody.match(/triple\([^,]+,\s*"([^"]+)"/);
@@ -5797,7 +5831,6 @@ class PerspectiveProxy {
5797
5831
  const instanceMatch = getterBody.match(/subject_class\("([^"]+)"/);
5798
5832
  if (instanceMatch) {
5799
5833
  instanceFilter = instanceMatch[1];
5800
- console.log(`Collection "${collName}" has instanceFilter: ${instanceFilter}`);
5801
5834
  }
5802
5835
  }
5803
5836
  }
@@ -5818,27 +5851,24 @@ class PerspectiveProxy {
5818
5851
  * Generates a SurrealDB query to find instances based on class metadata.
5819
5852
  */
5820
5853
  generateSurrealInstanceQuery(metadata) {
5821
- console.log("generateSurrealInstanceQuery called with requiredTriples:", metadata.requiredTriples);
5822
5854
  if (metadata.requiredTriples.length === 0) {
5823
5855
  // No required triples - any node with links is an instance
5824
- const query = `SELECT DISTINCT uri AS base FROM node WHERE count(->link) > 0`;
5825
- console.log("Generated query (no required triples):", query);
5826
- return query;
5856
+ return `SELECT DISTINCT uri AS base FROM node WHERE count(->link) > 0`;
5827
5857
  }
5828
5858
  // Generate WHERE conditions for each required triple (predicate + optional exact target)
5829
5859
  const whereConditions = metadata.requiredTriples.map(triple => {
5860
+ const escapedPredicate = escapeSurrealString(triple.predicate);
5830
5861
  if (triple.target) {
5831
5862
  // Flag: must match both predicate AND exact target value
5832
- return `count(->link[WHERE predicate = '${triple.predicate}' AND out.uri = '${triple.target}']) > 0`;
5863
+ const escapedTarget = escapeSurrealString(triple.target);
5864
+ return `count(->link[WHERE predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}']) > 0`;
5833
5865
  }
5834
5866
  else {
5835
5867
  // Property: just check predicate exists
5836
- return `count(->link[WHERE predicate = '${triple.predicate}']) > 0`;
5868
+ return `count(->link[WHERE predicate = '${escapedPredicate}']) > 0`;
5837
5869
  }
5838
5870
  }).join(' AND ');
5839
- const query = `SELECT uri AS base FROM node WHERE ${whereConditions}`;
5840
- console.log("Generated query:", query);
5841
- return query;
5871
+ return `SELECT uri AS base FROM node WHERE ${whereConditions}`;
5842
5872
  }
5843
5873
  /**
5844
5874
  * Gets a property value using SurrealDB when Prolog fails.
@@ -5853,7 +5883,9 @@ class PerspectiveProxy {
5853
5883
  if (!propMeta) {
5854
5884
  return undefined;
5855
5885
  }
5856
- const query = `SELECT out.uri AS value FROM link WHERE in.uri = '${baseExpression}' AND predicate = '${propMeta.predicate}' LIMIT 1`;
5886
+ const escapedBaseExpression = escapeSurrealString(baseExpression);
5887
+ const escapedPredicate = escapeSurrealString(propMeta.predicate);
5888
+ const query = `SELECT out.uri AS value FROM link WHERE in.uri = '${escapedBaseExpression}' AND predicate = '${escapedPredicate}' LIMIT 1`;
5857
5889
  const result = await this.querySurrealDB(query);
5858
5890
  if (!result || result.length === 0) {
5859
5891
  return undefined;
@@ -5889,28 +5921,91 @@ class PerspectiveProxy {
5889
5921
  if (!collMeta) {
5890
5922
  return [];
5891
5923
  }
5892
- const query = `SELECT out.uri AS value, timestamp FROM link WHERE in.uri = '${baseExpression}' AND predicate = '${collMeta.predicate}' ORDER BY timestamp ASC`;
5924
+ const escapedBaseExpression = escapeSurrealString(baseExpression);
5925
+ const escapedPredicate = escapeSurrealString(collMeta.predicate);
5926
+ const query = `SELECT out.uri AS value, timestamp FROM link WHERE in.uri = '${escapedBaseExpression}' AND predicate = '${escapedPredicate}' ORDER BY timestamp ASC`;
5893
5927
  const result = await this.querySurrealDB(query);
5894
5928
  if (!result || result.length === 0) {
5895
5929
  return [];
5896
5930
  }
5897
5931
  let values = result.map(r => r.value).filter(v => v !== "" && v !== '');
5898
- console.log(`getCollectionValuesViaSurreal: base="${baseExpression}", collection="${collectionName}", predicate="${collMeta.predicate}", found ${values.length} values:`, values);
5899
- // Apply instance filter if present
5932
+ // Apply instance filter if present - batch-check all values at once
5900
5933
  if (collMeta.instanceFilter) {
5901
- console.log(` Applying instance filter "${collMeta.instanceFilter}" to collection "${collectionName}"`);
5902
- const filteredValues = [];
5903
- for (const value of values) {
5904
- const isInstance = await this.isSubjectInstance(value, collMeta.instanceFilter);
5905
- console.log(` Checking if "${value}" is instance of "${collMeta.instanceFilter}": ${isInstance}`);
5934
+ try {
5935
+ const filterMetadata = await this.getSubjectClassMetadataFromSDNA(collMeta.instanceFilter);
5936
+ if (!filterMetadata) {
5937
+ // Fallback to sequential checks if metadata isn't available
5938
+ return this.filterInstancesSequential(values, collMeta.instanceFilter);
5939
+ }
5940
+ return await this.batchCheckSubjectInstances(values, filterMetadata);
5941
+ }
5942
+ catch (err) {
5943
+ // Fallback to sequential checks on error
5944
+ return this.filterInstancesSequential(values, collMeta.instanceFilter);
5945
+ }
5946
+ }
5947
+ return values;
5948
+ }
5949
+ /**
5950
+ * Batch-checks multiple expressions against subject class metadata using a single or limited SurrealDB queries.
5951
+ * This avoids N+1 query problems by checking all values at once.
5952
+ */
5953
+ async batchCheckSubjectInstances(expressions, metadata) {
5954
+ if (expressions.length === 0) {
5955
+ return [];
5956
+ }
5957
+ // If no required triples, check which expressions have any links
5958
+ if (metadata.requiredTriples.length === 0) {
5959
+ const escapedExpressions = expressions.map(e => `'${escapeSurrealString(e)}'`).join(', ');
5960
+ const checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] GROUP BY in.uri HAVING count() > 0`;
5961
+ const result = await this.querySurrealDB(checkQuery);
5962
+ return result.map(r => r.uri);
5963
+ }
5964
+ // For each required triple, build a query that finds matching expressions
5965
+ const validExpressionSets = [];
5966
+ for (const triple of metadata.requiredTriples) {
5967
+ const escapedExpressions = expressions.map(e => `'${escapeSurrealString(e)}'`).join(', ');
5968
+ const escapedPredicate = escapeSurrealString(triple.predicate);
5969
+ let checkQuery;
5970
+ if (triple.target) {
5971
+ // Flag: must match both predicate AND exact target value
5972
+ const escapedTarget = escapeSurrealString(triple.target);
5973
+ checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}' GROUP BY in.uri`;
5974
+ }
5975
+ else {
5976
+ // Property: just check predicate exists
5977
+ checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}' GROUP BY in.uri`;
5978
+ }
5979
+ const result = await this.querySurrealDB(checkQuery);
5980
+ validExpressionSets.push(new Set(result.map(r => r.uri)));
5981
+ }
5982
+ // Find intersection: expressions that passed ALL required triple checks
5983
+ if (validExpressionSets.length === 0) {
5984
+ return expressions;
5985
+ }
5986
+ const validExpressions = expressions.filter(expr => {
5987
+ return validExpressionSets.every(set => set.has(expr));
5988
+ });
5989
+ return validExpressions;
5990
+ }
5991
+ /**
5992
+ * Fallback sequential instance checking when batch checking isn't available.
5993
+ */
5994
+ async filterInstancesSequential(values, instanceFilter) {
5995
+ const filteredValues = [];
5996
+ for (const value of values) {
5997
+ try {
5998
+ const isInstance = await this.isSubjectInstance(value, instanceFilter);
5906
5999
  if (isInstance) {
5907
6000
  filteredValues.push(value);
5908
6001
  }
5909
6002
  }
5910
- console.log(` After filtering: ${filteredValues.length} values`);
5911
- return filteredValues;
6003
+ catch (err) {
6004
+ // Skip values that fail instance check
6005
+ continue;
6006
+ }
5912
6007
  }
5913
- return values;
6008
+ return filteredValues;
5914
6009
  }
5915
6010
  /** Returns all subject instances of the given subject class as proxy objects.
5916
6011
  * @param subjectClass Either a string with the name of the subject class, or an object
@@ -5952,7 +6047,7 @@ class PerspectiveProxy {
5952
6047
  //console.log(`getAllSubjectInstances: Returning ${instances.length} instances`);
5953
6048
  return instances;
5954
6049
  }
5955
- /** Returns all subject proxies of the given subject class.
6050
+ /** Returns all subject proxies of the given subject class as proxy objects.
5956
6051
  * @param subjectClass Either a string with the name of the subject class, or an object
5957
6052
  * with the properties of the subject class. In the latter case, all subject classes
5958
6053
  * that match the given properties will be used.
@@ -5967,24 +6062,23 @@ class PerspectiveProxy {
5967
6062
  }
5968
6063
  let instances = [];
5969
6064
  for (let className of classes) {
5970
- //console.log(`getAllSubjectProxies: Processing class ${className}`);
5971
6065
  // Query SDNA for metadata, then query SurrealDB for instances
5972
6066
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
5973
- //console.log(`getAllSubjectProxies: Got metadata for ${className}`);
5974
6067
  if (metadata) {
5975
6068
  const surrealQuery = this.generateSurrealInstanceQuery(metadata);
5976
- console.log("surrealQuery", surrealQuery);
5977
6069
  const results = await this.querySurrealDB(surrealQuery);
5978
- console.log(`getAllSubjectProxies: SurrealDB returned ${results?.length || 0} results`);
5979
- const newInstance = results.map(r => ({ X: r.base }));
5980
- console.log("newInstance", newInstance);
5981
- instances = instances.concat(newInstance);
5982
- }
5983
- else {
5984
- console.warn(`getAllSubjectProxies: No metadata found for ${className}`);
6070
+ for (const result of results || []) {
6071
+ try {
6072
+ let subject = new Subject(this, result.base, className);
6073
+ await subject.init();
6074
+ instances.push(subject);
6075
+ }
6076
+ catch (e) {
6077
+ // Skip subjects that fail to initialize
6078
+ }
6079
+ }
5985
6080
  }
5986
6081
  }
5987
- //console.log(`getAllSubjectProxies: Returning ${instances.length} proxies`);
5988
6082
  return instances;
5989
6083
  }
5990
6084
  buildQueryFromTemplate(obj) {
@@ -17619,27 +17713,6 @@ input VoiceActivityParamsInput {
17619
17713
  }
17620
17714
  `;
17621
17715
 
17622
- function formatList(list) {
17623
- if (!list?.length) {
17624
- return "";
17625
- }
17626
- if (list.length === 1) {
17627
- return list.toString();
17628
- }
17629
- if (list.length === 2) {
17630
- return list.join(' and ');
17631
- }
17632
- return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);
17633
- }
17634
- function capSentence(cap) {
17635
- const can = cap.can.includes("*") ? ["READ", "WRITE", "UPDATE"] : cap.can;
17636
- const domain = cap.with.domain === "*" ? "" : cap.with.domain;
17637
- const pointers = cap.with.pointers.includes("*")
17638
- ? ["all AD4M data"]
17639
- : cap.with.pointers;
17640
- return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
17641
- }
17642
-
17643
17716
  var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
17644
17717
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17645
17718
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -18965,6 +19038,10 @@ class Ad4mModel {
18965
19038
  * @private
18966
19039
  */
18967
19040
  generatePropertySetterAction(key, metadata) {
19041
+ // Check if property is read-only
19042
+ if (metadata.writable === false) {
19043
+ throw new Error(`Property "${key}" is read-only and cannot be written`);
19044
+ }
18968
19045
  if (metadata.setter) {
18969
19046
  // Custom setter - throw error for now (Phase 2)
18970
19047
  throw new Error(`Custom setter for property "${key}" not yet supported without Prolog. ` +
@@ -19057,34 +19134,20 @@ class Ad4mModel {
19057
19134
  }
19058
19135
  async getData() {
19059
19136
  // Builds an object with the author, timestamp, all properties, & all collections on the Ad4mModel and saves it to the instance
19060
- const subQueries = [buildAuthorAndTimestampQuery(), buildPropertiesQuery(), buildCollectionsQuery()];
19061
- const fullQuery = `
19062
- Base = "${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}",
19063
- subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", SubjectClass),
19064
- ${subQueries.join(", ")}
19065
- `;
19066
- // Try Prolog first
19067
- try {
19068
- const result = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(fullQuery);
19069
- if (result?.[0] && result[0].Properties && result[0].Properties.length > 0) {
19070
- const { Properties, Collections, Timestamp, Author } = result[0];
19071
- const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
19072
- await Ad4mModel.assignValuesToInstance(__classPrivateFieldGet(this, _Ad4mModel_perspective, "f"), this, values);
19073
- return this;
19074
- }
19075
- }
19076
- catch (e) {
19077
- console.log(`Prolog getData failed for ${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}, falling back to SurrealDB`);
19078
- }
19079
- // Fallback to SurrealDB (SdnaOnly mode)
19137
+ // Use SurrealDB for data queries
19080
19138
  try {
19081
19139
  const ctor = this.constructor;
19082
19140
  const metadata = ctor.getModelMetadata();
19083
19141
  // Query for all links from this specific node (base expression)
19142
+ // Using formatSurrealValue to prevent SQL injection by properly escaping the value
19143
+ const safeBaseExpression = ctor.formatSurrealValue(__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"));
19144
+ // Note: We use ORDER BY timestamp ASC because:
19145
+ // - For collections: we want chronological order (oldest to newest)
19146
+ // - For properties: we select the LAST element to get "latest wins" semantics
19084
19147
  const linksQuery = `
19085
19148
  SELECT id, predicate, out.uri AS target, author, timestamp
19086
19149
  FROM link
19087
- WHERE in.uri = '${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}'
19150
+ WHERE in.uri = ${safeBaseExpression}
19088
19151
  ORDER BY timestamp ASC
19089
19152
  `;
19090
19153
  const links = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").querySurrealDB(linksQuery);
@@ -19095,7 +19158,9 @@ class Ad4mModel {
19095
19158
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
19096
19159
  const matching = links.filter((l) => l.predicate === propMeta.predicate);
19097
19160
  if (matching.length > 0) {
19098
- const link = matching[0]; // Take first/latest
19161
+ // "Latest wins" semantics: select the last element since links are ordered ASC.
19162
+ // The last element has the most recent timestamp and represents the current property value.
19163
+ const link = matching[matching.length - 1];
19099
19164
  let value = link.target;
19100
19165
  // Track timestamp/author
19101
19166
  if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
@@ -19139,7 +19204,8 @@ class Ad4mModel {
19139
19204
  // Process collections
19140
19205
  for (const [collName, collMeta] of Object.entries(metadata.collections)) {
19141
19206
  const matching = links.filter((l) => l.predicate === collMeta.predicate);
19142
- // Links are already sorted by timestamp ASC from the query, so map preserves order
19207
+ // Collections preserve chronological order: links are sorted ASC by timestamp,
19208
+ // so the collection reflects the order in which items were added (oldest to newest).
19143
19209
  this[collName] = matching.map((l) => l.target);
19144
19210
  }
19145
19211
  // Set author and timestamp
@@ -19230,10 +19296,10 @@ class Ad4mModel {
19230
19296
  if (propMeta.required) {
19231
19297
  // For flag properties, also filter by the target value
19232
19298
  if (propMeta.flag && propMeta.initial) {
19233
- graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}' AND out.uri = '${propMeta.initial}']) > 0`);
19299
+ graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
19234
19300
  }
19235
19301
  else {
19236
- graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}']) > 0`);
19302
+ graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
19237
19303
  }
19238
19304
  }
19239
19305
  }
@@ -19244,10 +19310,10 @@ class Ad4mModel {
19244
19310
  if (propMeta.initial) {
19245
19311
  // For flag properties, also filter by the target value
19246
19312
  if (propMeta.flag) {
19247
- graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}' AND out.uri = '${propMeta.initial}']) > 0`);
19313
+ graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
19248
19314
  }
19249
19315
  else {
19250
- graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}']) > 0`);
19316
+ graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
19251
19317
  }
19252
19318
  break; // Just need one defining property
19253
19319
  }
@@ -19359,7 +19425,7 @@ WHERE ${whereConditions.join(' AND ')}
19359
19425
  const propMeta = metadata.properties[propertyName];
19360
19426
  if (!propMeta)
19361
19427
  continue; // Skip if property not found in metadata
19362
- const predicate = propMeta.predicate;
19428
+ const predicate = escapeSurrealString(propMeta.predicate);
19363
19429
  // Use fn::parse_literal() for properties with resolveLanguage
19364
19430
  const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(out.uri)' : 'out.uri';
19365
19431
  if (Array.isArray(condition)) {
@@ -19491,7 +19557,7 @@ WHERE ${whereConditions.join(' AND ')}
19491
19557
  const propMeta = metadata.properties[propertyName];
19492
19558
  if (!propMeta)
19493
19559
  continue; // Skip if property not found in metadata
19494
- const predicate = propMeta.predicate;
19560
+ const predicate = escapeSurrealString(propMeta.predicate);
19495
19561
  // Use fn::parse_literal() for properties with resolveLanguage
19496
19562
  const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(target)' : 'target';
19497
19563
  if (Array.isArray(condition)) {
@@ -19566,7 +19632,8 @@ WHERE ${whereConditions.join(' AND ')}
19566
19632
  if (!propMeta)
19567
19633
  continue; // Skip if not found
19568
19634
  // Reference source directly since we're selecting from link table
19569
- fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${propMeta.predicate}' LIMIT 1) AS ${propName}`);
19635
+ const escapedPredicate = escapeSurrealString(propMeta.predicate);
19636
+ fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}' LIMIT 1) AS ${propName}`);
19570
19637
  }
19571
19638
  // Determine collections to fetch
19572
19639
  const collsToFetch = collections || Object.keys(metadata.collections);
@@ -19575,7 +19642,8 @@ WHERE ${whereConditions.join(' AND ')}
19575
19642
  if (!collMeta)
19576
19643
  continue; // Skip if not found
19577
19644
  // Reference source directly since we're selecting from link table
19578
- fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${collMeta.predicate}') AS ${collName}`);
19645
+ const escapedPredicate = escapeSurrealString(collMeta.predicate);
19646
+ fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}') AS ${collName}`);
19579
19647
  }
19580
19648
  // Always add author and timestamp fields
19581
19649
  fields.push(`(SELECT VALUE author FROM link WHERE source = source LIMIT 1) AS author`);
@@ -19597,7 +19665,8 @@ WHERE ${whereConditions.join(' AND ')}
19597
19665
  if (!propMeta)
19598
19666
  continue; // Skip if not found
19599
19667
  // Use array::first to get the first target value for this predicate
19600
- fields.push(`array::first(target[WHERE predicate = '${propMeta.predicate}']) AS ${propName}`);
19668
+ const escapedPredicate = escapeSurrealString(propMeta.predicate);
19669
+ fields.push(`array::first(target[WHERE predicate = '${escapedPredicate}']) AS ${propName}`);
19601
19670
  }
19602
19671
  // Determine collections to fetch
19603
19672
  const collsToFetch = collections || Object.keys(metadata.collections);
@@ -19606,7 +19675,8 @@ WHERE ${whereConditions.join(' AND ')}
19606
19675
  if (!collMeta)
19607
19676
  continue; // Skip if not found
19608
19677
  // Use array filtering to get all target values for this predicate
19609
- fields.push(`target[WHERE predicate = '${collMeta.predicate}'] AS ${collName}`);
19678
+ const escapedPredicate = escapeSurrealString(collMeta.predicate);
19679
+ fields.push(`target[WHERE predicate = '${escapedPredicate}'] AS ${collName}`);
19610
19680
  }
19611
19681
  // Always add author and timestamp fields using array::first
19612
19682
  fields.push(`array::first(author) AS author`);
@@ -20225,7 +20295,7 @@ WHERE ${whereConditions.join(' AND ')}
20225
20295
  }
20226
20296
  // Generate actions from metadata (replaces Prolog query)
20227
20297
  const actions = this.generateCollectionAction(key, 'setter');
20228
- if (value) {
20298
+ if (value != null) {
20229
20299
  if (Array.isArray(value)) {
20230
20300
  await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), value.map((v) => ({ name: "value", value: v })), batchId);
20231
20301
  }
@@ -20243,7 +20313,7 @@ WHERE ${whereConditions.join(' AND ')}
20243
20313
  }
20244
20314
  // Generate actions from metadata (replaces Prolog query)
20245
20315
  const actions = this.generateCollectionAction(key, 'adder');
20246
- if (value) {
20316
+ if (value != null) {
20247
20317
  if (Array.isArray(value)) {
20248
20318
  await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
20249
20319
  }
@@ -20261,7 +20331,7 @@ WHERE ${whereConditions.join(' AND ')}
20261
20331
  }
20262
20332
  // Generate actions from metadata (replaces Prolog query)
20263
20333
  const actions = this.generateCollectionAction(key, 'remover');
20264
- if (value) {
20334
+ if (value != null) {
20265
20335
  if (Array.isArray(value)) {
20266
20336
  await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
20267
20337
  }
@@ -20351,11 +20421,8 @@ WHERE ${whereConditions.join(' AND ')}
20351
20421
  }
20352
20422
  }
20353
20423
  else if (Array.isArray(value)) {
20354
- // Handle all arrays as collections, even empty ones
20355
- if (value.length > 0) {
20356
- await this.setCollectionSetter(key, value, batchId);
20357
- }
20358
- // Skip empty arrays - don't try to set them as properties
20424
+ // Handle all arrays as collections, including empty ones (which clears the collection)
20425
+ await this.setCollectionSetter(key, value, batchId);
20359
20426
  }
20360
20427
  else if (value !== undefined && value !== null && value !== "") {
20361
20428
  if (setProperties) {
@@ -21255,6 +21322,7 @@ exports.SmartLiteral = SmartLiteral;
21255
21322
  exports.Subject = Subject;
21256
21323
  exports.addLink = addLink;
21257
21324
  exports.capSentence = capSentence;
21325
+ exports.escapeSurrealString = escapeSurrealString;
21258
21326
  exports.exprRef2String = exprRef2String;
21259
21327
  exports.formatList = formatList;
21260
21328
  exports.hasLink = hasLink;