@coasys/ad4m 0.11.2-dev-multi-user-email-2 → 0.11.2-dev-sdna-only-prolog

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
@@ -4494,36 +4494,44 @@ class Subject {
4494
4494
  Object.defineProperty(this, p, {
4495
4495
  configurable: true,
4496
4496
  get: async () => {
4497
- 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)`);
4498
- if (results && results.length > 0) {
4499
- let expressionURI = results[0].Value;
4500
- if (resolveExpressionURI) {
4501
- try {
4502
- if (expressionURI) {
4503
- const expression = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").getExpression(expressionURI);
4504
- try {
4505
- return JSON.parse(expression.data);
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
+ }
4506
4512
  }
4507
- catch (e) {
4508
- return expression.data;
4513
+ else {
4514
+ return expressionURI;
4509
4515
  }
4510
4516
  }
4511
- else {
4517
+ catch (err) {
4512
4518
  return expressionURI;
4513
4519
  }
4514
4520
  }
4515
- catch (err) {
4521
+ else {
4516
4522
  return expressionURI;
4517
4523
  }
4518
4524
  }
4519
- else {
4520
- return expressionURI;
4521
- }
4522
4525
  }
4523
- else if (results) {
4524
- return results;
4526
+ catch (err) {
4527
+ // Prolog query failed, fall through to SurrealDB
4525
4528
  }
4526
- else {
4529
+ // Fallback to SurrealDB if Prolog returned nothing (SdnaOnly mode)
4530
+ try {
4531
+ return await __classPrivateFieldGet$b(this, _Subject_perspective, "f").getPropertyValueViaSurreal(__classPrivateFieldGet$b(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$b(this, _Subject_subjectClassName, "f"), p);
4532
+ }
4533
+ catch (err) {
4534
+ console.warn(`Failed to get property ${p} via SurrealDB:`, err);
4527
4535
  return undefined;
4528
4536
  }
4529
4537
  }
@@ -4557,12 +4565,25 @@ class Subject {
4557
4565
  Object.defineProperty(this, c, {
4558
4566
  configurable: true,
4559
4567
  get: async () => {
4560
- 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)`);
4561
- if (results && results.length > 0 && results[0].Value) {
4562
- let collectionContent = results[0].Value.filter((v) => v !== "" && v !== '');
4563
- return collectionContent;
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
+ }
4564
4577
  }
4565
- else {
4578
+ catch (err) {
4579
+ // Prolog query failed, fall through to SurrealDB
4580
+ }
4581
+ // Fallback to SurrealDB if Prolog returned nothing (SdnaOnly mode)
4582
+ try {
4583
+ return await __classPrivateFieldGet$b(this, _Subject_perspective, "f").getCollectionValuesViaSurreal(__classPrivateFieldGet$b(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$b(this, _Subject_subjectClassName, "f"), c);
4584
+ }
4585
+ catch (err) {
4586
+ console.warn(`Failed to get collection ${c} via SurrealDB:`, err);
4566
4587
  return [];
4567
4588
  }
4568
4589
  }
@@ -5582,14 +5603,48 @@ class PerspectiveProxy {
5582
5603
  */
5583
5604
  async isSubjectInstance(expression, subjectClass) {
5584
5605
  let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);
5585
- let isInstance = false;
5586
- const maxAttempts = 5;
5587
- let attempts = 0;
5588
- while (attempts < maxAttempts && !isInstance) {
5589
- isInstance = await this.infer(`subject_class("${className}", C), instance(C, "${expression}")`);
5590
- attempts++;
5606
+ // Get metadata from SDNA using Prolog metaprogramming
5607
+ const metadata = await this.getSubjectClassMetadataFromSDNA(className);
5608
+ if (!metadata) {
5609
+ return false;
5610
+ }
5611
+ // If no required triples, any expression with links is an instance
5612
+ 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);
5616
+ const result = await this.querySurrealDB(checkQuery);
5617
+ console.log("result", result);
5618
+ const count = result[0]?.count ?? 0;
5619
+ const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
5620
+ return countValue > 0;
5621
+ }
5622
+ // Check if the expression has all required triples (predicate + optional exact target)
5623
+ for (const triple of metadata.requiredTriples) {
5624
+ console.log("checking triple", triple);
5625
+ let checkQuery;
5626
+ if (triple.target) {
5627
+ // 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}'`;
5629
+ }
5630
+ else {
5631
+ // Property: just check predicate exists
5632
+ checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${expression}' AND predicate = '${triple.predicate}'`;
5633
+ }
5634
+ console.log("checkQuery", checkQuery);
5635
+ const result = await this.querySurrealDB(checkQuery);
5636
+ console.log("result", result);
5637
+ if (!result || result.length === 0) {
5638
+ return false;
5639
+ }
5640
+ const count = result[0]?.count ?? 0;
5641
+ // Handle potential object response like {Int: 0}
5642
+ const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
5643
+ if (countValue === 0) {
5644
+ return false;
5645
+ }
5591
5646
  }
5592
- return isInstance;
5647
+ return true;
5593
5648
  }
5594
5649
  /** For an existing subject instance (existing in the perspective's links)
5595
5650
  * this function returns a proxy object that can be used to access the subject's
@@ -5609,6 +5664,254 @@ class PerspectiveProxy {
5609
5664
  await subject.init();
5610
5665
  return subject;
5611
5666
  }
5667
+ /**
5668
+ * Extracts subject class metadata from SDNA by parsing the Prolog text.
5669
+ * Parses the instance rule to extract required predicates.
5670
+ * Returns required predicates that define what makes something an instance,
5671
+ * plus a map of property/collection names to their predicates.
5672
+ */
5673
+ async getSubjectClassMetadataFromSDNA(className) {
5674
+ try {
5675
+ // Get SDNA code from perspective - it's stored as a link
5676
+ const sdnaLinks = await this.get(new exports.LinkQuery({
5677
+ source: `literal://string:${className}`,
5678
+ predicate: "ad4m://sdna"
5679
+ }));
5680
+ //console.log(`getSubjectClassMetadataFromSDNA: sdnaLinks for ${className}:`, sdnaLinks);
5681
+ if (!sdnaLinks || sdnaLinks.length === 0) {
5682
+ console.warn(`No SDNA found for class ${className}`);
5683
+ return null;
5684
+ }
5685
+ if (!sdnaLinks[0].data.target) {
5686
+ console.error(`SDNA link for ${className} has no target:`, sdnaLinks[0]);
5687
+ return null;
5688
+ }
5689
+ // Extract SDNA code from the literal
5690
+ const sdnaCode = Literal.fromUrl(sdnaLinks[0].data.target).get();
5691
+ //console.log("sdnaCode for", className, ":", sdnaCode.substring(0, 200));
5692
+ // Store required triples as {predicate, target?}
5693
+ // target is only set for flags (exact matches), otherwise undefined
5694
+ const requiredTriples = [];
5695
+ // Parse the instance rule from the SDNA code
5696
+ // 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) {
5699
+ const ruleBody = instanceRuleMatch[1];
5700
+ console.log("instance rule body:", ruleBody);
5701
+ // Extract all triple(Base, "predicate", Target) patterns
5702
+ // Match both: triple(Base, "pred", _) and triple(Base, "pred", "value")
5703
+ const tripleRegex = /triple\([^,]+,\s*"([^"]+)",\s*(?:"([^"]+)"|_)\)/g;
5704
+ let match;
5705
+ while ((match = tripleRegex.exec(ruleBody)) !== null) {
5706
+ const predicate = match[1];
5707
+ const target = match[2]; // undefined if matched "_"
5708
+ requiredTriples.push({ predicate, target });
5709
+ console.log(`Extracted triple: predicate="${predicate}", target="${target}"`);
5710
+ }
5711
+ }
5712
+ else {
5713
+ console.warn(`No instance rule found in SDNA for ${className}`);
5714
+ }
5715
+ // For backward compatibility, also maintain requiredPredicates array
5716
+ const requiredPredicates = requiredTriples.map(t => t.predicate);
5717
+ console.log("extracted requiredTriples:", requiredTriples);
5718
+ // Extract property metadata
5719
+ const properties = new Map();
5720
+ const propertyResults = await this.infer(`subject_class("${className}", C), property(C, P)`);
5721
+ //console.log("propertyResults", propertyResults);
5722
+ if (propertyResults) {
5723
+ for (const result of propertyResults) {
5724
+ const propName = result.P;
5725
+ let predicate = null;
5726
+ // Try to extract predicate from property_setter first
5727
+ const setterResults = await this.infer(`subject_class("${className}", C), property_setter(C, "${propName}", Setter)`);
5728
+ if (setterResults && setterResults.length > 0) {
5729
+ const setterString = setterResults[0].Setter;
5730
+ const predicateMatch = setterString.match(/predicate:\s*"([^"]+)"|predicate:\s*([^,}\]]+)/);
5731
+ if (predicateMatch) {
5732
+ predicate = predicateMatch[1] || predicateMatch[2];
5733
+ }
5734
+ }
5735
+ // If no setter, try to extract from SDNA property_getter Prolog code
5736
+ if (!predicate) {
5737
+ // Parse the SDNA code for property_getter definition
5738
+ const getterMatch = sdnaCode.match(new RegExp(`property_getter\\([^,]+,\\s*[^,]+,\\s*"${propName}"[^)]*\\)\\s*:-\\s*triple\\([^,]+,\\s*"([^"]+)"`));
5739
+ if (getterMatch) {
5740
+ predicate = getterMatch[1];
5741
+ }
5742
+ }
5743
+ if (predicate) {
5744
+ // Check if property has resolveLanguage
5745
+ const resolveResults = await this.infer(`subject_class("${className}", C), property_resolve_language(C, "${propName}", Lang)`);
5746
+ const resolveLanguage = resolveResults && resolveResults.length > 0 ? resolveResults[0].Lang : undefined;
5747
+ properties.set(propName, { predicate, resolveLanguage });
5748
+ }
5749
+ }
5750
+ }
5751
+ //console.log("properties", properties);
5752
+ // Extract collection metadata
5753
+ const collections = new Map();
5754
+ const collectionResults = await this.infer(`subject_class("${className}", C), collection(C, Coll)`);
5755
+ //console.log("collectionResults", collectionResults);
5756
+ if (collectionResults) {
5757
+ for (const result of collectionResults) {
5758
+ const collName = result.Coll;
5759
+ let predicate = null;
5760
+ let instanceFilter = undefined;
5761
+ // Try to extract predicate from collection_adder first
5762
+ const adderResults = await this.infer(`subject_class("${className}", C), collection_adder(C, "${collName}", Adder)`);
5763
+ if (adderResults && adderResults.length > 0) {
5764
+ const adderString = adderResults[0].Adder;
5765
+ const predicateMatch = adderString.match(/predicate:\s*"([^"]+)"|predicate:\s*([^,}\]]+)/);
5766
+ if (predicateMatch) {
5767
+ predicate = predicateMatch[1] || predicateMatch[2];
5768
+ }
5769
+ }
5770
+ // Parse collection_getter from SDNA to extract predicate and instanceFilter
5771
+ // Format 1 (findall): collection_getter(c, Base, "comments", List) :- findall(C, triple(Base, "todo://comment", C), List).
5772
+ // Format 2 (setof): collection_getter(c, Base, "messages", List) :- setof(Target, (triple(Base, "flux://entry_type", Target), ...), List).
5773
+ // Use a line-based match to avoid capturing multiple collections
5774
+ const getterLinePattern = new RegExp(`collection_getter\\([^,]+,\\s*[^,]+,\\s*"${collName}"[^)]*\\)\\s*:-[^.]+\\.`);
5775
+ const getterLineMatch = sdnaCode.match(getterLinePattern);
5776
+ if (getterLineMatch) {
5777
+ const getterLine = getterLineMatch[0];
5778
+ // Extract the body between setof/findall and the final ).
5779
+ // Pattern: findall(Var, Body, List) or setof(Var, (Body), List)
5780
+ const bodyPattern = /(?:setof|findall)\([^,]+,\s*(.+),\s*\w+\)\./;
5781
+ const bodyMatch = getterLine.match(bodyPattern);
5782
+ if (bodyMatch) {
5783
+ let getterBody = bodyMatch[1];
5784
+ // Remove outer parentheses if present (setof case)
5785
+ if (getterBody.startsWith('(') && getterBody.endsWith(')')) {
5786
+ getterBody = getterBody.substring(1, getterBody.length - 1);
5787
+ }
5788
+ console.log(`Collection "${collName}" getter body:`, getterBody);
5789
+ // Extract predicate from triple(Base, "predicate", Target)
5790
+ if (!predicate) {
5791
+ const tripleMatch = getterBody.match(/triple\([^,]+,\s*"([^"]+)"/);
5792
+ if (tripleMatch) {
5793
+ predicate = tripleMatch[1];
5794
+ }
5795
+ }
5796
+ // Check for instance filter: subject_class("ClassName", OtherClass)
5797
+ const instanceMatch = getterBody.match(/subject_class\("([^"]+)"/);
5798
+ if (instanceMatch) {
5799
+ instanceFilter = instanceMatch[1];
5800
+ console.log(`Collection "${collName}" has instanceFilter: ${instanceFilter}`);
5801
+ }
5802
+ }
5803
+ }
5804
+ if (predicate) {
5805
+ collections.set(collName, { predicate, instanceFilter });
5806
+ }
5807
+ }
5808
+ }
5809
+ //console.log("collections", collections);
5810
+ return { requiredPredicates, requiredTriples, properties, collections };
5811
+ }
5812
+ catch (e) {
5813
+ console.error(`Error getting metadata for ${className}:`, e);
5814
+ return null;
5815
+ }
5816
+ }
5817
+ /**
5818
+ * Generates a SurrealDB query to find instances based on class metadata.
5819
+ */
5820
+ generateSurrealInstanceQuery(metadata) {
5821
+ console.log("generateSurrealInstanceQuery called with requiredTriples:", metadata.requiredTriples);
5822
+ if (metadata.requiredTriples.length === 0) {
5823
+ // 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;
5827
+ }
5828
+ // Generate WHERE conditions for each required triple (predicate + optional exact target)
5829
+ const whereConditions = metadata.requiredTriples.map(triple => {
5830
+ if (triple.target) {
5831
+ // Flag: must match both predicate AND exact target value
5832
+ return `count(->link[WHERE predicate = '${triple.predicate}' AND out.uri = '${triple.target}']) > 0`;
5833
+ }
5834
+ else {
5835
+ // Property: just check predicate exists
5836
+ return `count(->link[WHERE predicate = '${triple.predicate}']) > 0`;
5837
+ }
5838
+ }).join(' AND ');
5839
+ const query = `SELECT uri AS base FROM node WHERE ${whereConditions}`;
5840
+ console.log("Generated query:", query);
5841
+ return query;
5842
+ }
5843
+ /**
5844
+ * Gets a property value using SurrealDB when Prolog fails.
5845
+ * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
5846
+ */
5847
+ async getPropertyValueViaSurreal(baseExpression, className, propertyName) {
5848
+ const metadata = await this.getSubjectClassMetadataFromSDNA(className);
5849
+ if (!metadata) {
5850
+ return undefined;
5851
+ }
5852
+ const propMeta = metadata.properties.get(propertyName);
5853
+ if (!propMeta) {
5854
+ return undefined;
5855
+ }
5856
+ const query = `SELECT out.uri AS value FROM link WHERE in.uri = '${baseExpression}' AND predicate = '${propMeta.predicate}' LIMIT 1`;
5857
+ const result = await this.querySurrealDB(query);
5858
+ if (!result || result.length === 0) {
5859
+ return undefined;
5860
+ }
5861
+ const value = result[0].value;
5862
+ // Handle expression resolution if needed
5863
+ if (propMeta.resolveLanguage && value) {
5864
+ try {
5865
+ const expression = await this.getExpression(value);
5866
+ try {
5867
+ return JSON.parse(expression.data);
5868
+ }
5869
+ catch (e) {
5870
+ return expression.data;
5871
+ }
5872
+ }
5873
+ catch (err) {
5874
+ return value;
5875
+ }
5876
+ }
5877
+ return value;
5878
+ }
5879
+ /**
5880
+ * Gets collection values using SurrealDB when Prolog fails.
5881
+ * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
5882
+ */
5883
+ async getCollectionValuesViaSurreal(baseExpression, className, collectionName) {
5884
+ const metadata = await this.getSubjectClassMetadataFromSDNA(className);
5885
+ if (!metadata) {
5886
+ return [];
5887
+ }
5888
+ const collMeta = metadata.collections.get(collectionName);
5889
+ if (!collMeta) {
5890
+ return [];
5891
+ }
5892
+ const query = `SELECT out.uri AS value, timestamp FROM link WHERE in.uri = '${baseExpression}' AND predicate = '${collMeta.predicate}' ORDER BY timestamp ASC`;
5893
+ const result = await this.querySurrealDB(query);
5894
+ if (!result || result.length === 0) {
5895
+ return [];
5896
+ }
5897
+ 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
5900
+ 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}`);
5906
+ if (isInstance) {
5907
+ filteredValues.push(value);
5908
+ }
5909
+ }
5910
+ console.log(` After filtering: ${filteredValues.length} values`);
5911
+ return filteredValues;
5912
+ }
5913
+ return values;
5914
+ }
5612
5915
  /** Returns all subject instances of the given subject class as proxy objects.
5613
5916
  * @param subjectClass Either a string with the name of the subject class, or an object
5614
5917
  * with the properties of the subject class. In the latter case, all subject classes
@@ -5624,10 +5927,29 @@ class PerspectiveProxy {
5624
5927
  }
5625
5928
  let instances = [];
5626
5929
  for (let className of classes) {
5627
- let instanceBaseExpressions = await this.infer(`subject_class("${className}", C), instance(C, X)`);
5628
- let newInstances = await Promise.all(instanceBaseExpressions.map(async (x) => await this.getSubjectProxy(x.X, className)));
5629
- instances = instances.concat(newInstances);
5930
+ //console.log(`getAllSubjectInstances: Processing class ${className}`);
5931
+ // Query SDNA for metadata, then query SurrealDB for instances
5932
+ const metadata = await this.getSubjectClassMetadataFromSDNA(className);
5933
+ //console.log(`getAllSubjectInstances: Got metadata for ${className}:`, metadata);
5934
+ if (metadata) {
5935
+ const surrealQuery = this.generateSurrealInstanceQuery(metadata);
5936
+ const results = await this.querySurrealDB(surrealQuery);
5937
+ // console.log(`getAllSubjectInstances: SurrealDB returned ${results?.length || 0} results`);
5938
+ for (const result of results || []) {
5939
+ //console.log(`getAllSubjectInstances: Creating subject for base ${result.base}`);
5940
+ try {
5941
+ let subject = new Subject(this, result.base, className);
5942
+ await subject.init();
5943
+ instances.push(subject);
5944
+ //console.log(`getAllSubjectInstances: Successfully created subject for ${result.base}`);
5945
+ }
5946
+ catch (e) {
5947
+ //console.warn(`Failed to create subject for ${result.base}:`, e);
5948
+ }
5949
+ }
5950
+ }
5630
5951
  }
5952
+ //console.log(`getAllSubjectInstances: Returning ${instances.length} instances`);
5631
5953
  return instances;
5632
5954
  }
5633
5955
  /** Returns all subject proxies of the given subject class.
@@ -5645,8 +5967,24 @@ class PerspectiveProxy {
5645
5967
  }
5646
5968
  let instances = [];
5647
5969
  for (let className of classes) {
5648
- instances = await this.infer(`subject_class("${className}", C), instance(C, X)`);
5970
+ //console.log(`getAllSubjectProxies: Processing class ${className}`);
5971
+ // Query SDNA for metadata, then query SurrealDB for instances
5972
+ const metadata = await this.getSubjectClassMetadataFromSDNA(className);
5973
+ //console.log(`getAllSubjectProxies: Got metadata for ${className}`);
5974
+ if (metadata) {
5975
+ const surrealQuery = this.generateSurrealInstanceQuery(metadata);
5976
+ console.log("surrealQuery", surrealQuery);
5977
+ 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}`);
5985
+ }
5649
5986
  }
5987
+ //console.log(`getAllSubjectProxies: Returning ${instances.length} proxies`);
5650
5988
  return instances;
5651
5989
  }
5652
5990
  buildQueryFromTemplate(obj) {
@@ -16058,20 +16396,46 @@ function InstanceQuery(options) {
16058
16396
  if (options && options.condition) {
16059
16397
  query += ', ' + options.condition;
16060
16398
  }
16061
- let results = await perspective.infer(query);
16062
- if (results == false) {
16063
- return instances;
16399
+ // Try Prolog first
16400
+ try {
16401
+ let results = await perspective.infer(query);
16402
+ if (results && results !== false && typeof results !== "string" && results.length > 0) {
16403
+ for (let result of results) {
16404
+ let instance = result.Instance;
16405
+ let subject = new Subject(perspective, instance, subjectClassName);
16406
+ await subject.init();
16407
+ instances.push(subject);
16408
+ }
16409
+ return instances;
16410
+ }
16064
16411
  }
16065
- if (typeof results == "string") {
16066
- throw results;
16412
+ catch (e) {
16413
+ // Prolog failed, fall through to SurrealDB
16067
16414
  }
16068
- for (let result of results) {
16069
- let instance = result.Instance;
16070
- let subject = new Subject(perspective, instance, subjectClassName);
16071
- await subject.init();
16072
- instances.push(subject);
16415
+ // Fallback to SurrealDB (SdnaOnly mode)
16416
+ // Get all instances first
16417
+ let allInstances = await perspective.getAllSubjectInstances(subjectClassName);
16418
+ // Filter by where clause if provided
16419
+ if (options && options.where) {
16420
+ let filtered = [];
16421
+ for (let instance of allInstances) {
16422
+ let matches = true;
16423
+ for (let prop in options.where) {
16424
+ let expectedValue = options.where[prop];
16425
+ //@ts-ignore
16426
+ let actualValue = await instance[prop];
16427
+ if (actualValue !== expectedValue) {
16428
+ matches = false;
16429
+ break;
16430
+ }
16431
+ }
16432
+ if (matches) {
16433
+ filtered.push(instance);
16434
+ }
16435
+ }
16436
+ return filtered;
16073
16437
  }
16074
- return instances;
16438
+ return allInstances;
16075
16439
  };
16076
16440
  };
16077
16441
  }
@@ -18579,6 +18943,70 @@ class Ad4mModel {
18579
18943
  get perspective() {
18580
18944
  return __classPrivateFieldGet(this, _Ad4mModel_perspective, "f");
18581
18945
  }
18946
+ /**
18947
+ * Get property metadata from decorator (Phase 1: Prolog-free refactor)
18948
+ * @private
18949
+ */
18950
+ getPropertyMetadata(key) {
18951
+ const proto = Object.getPrototypeOf(this);
18952
+ return proto.__properties?.[key];
18953
+ }
18954
+ /**
18955
+ * Get collection metadata from decorator (Phase 1: Prolog-free refactor)
18956
+ * @private
18957
+ */
18958
+ getCollectionMetadata(key) {
18959
+ const proto = Object.getPrototypeOf(this);
18960
+ return proto.__collections?.[key];
18961
+ }
18962
+ /**
18963
+ * Generate property setter action from metadata (Phase 1: Prolog-free refactor)
18964
+ * Replaces Prolog query: property_setter(C, key, Setter)
18965
+ * @private
18966
+ */
18967
+ generatePropertySetterAction(key, metadata) {
18968
+ if (metadata.setter) {
18969
+ // Custom setter - throw error for now (Phase 2)
18970
+ throw new Error(`Custom setter for property "${key}" not yet supported without Prolog. ` +
18971
+ `Use standard @Property decorator or enable Prolog for custom setters.`);
18972
+ }
18973
+ if (!metadata.through) {
18974
+ throw new Error(`Property "${key}" has no 'through' predicate defined`);
18975
+ }
18976
+ return [{
18977
+ action: "setSingleTarget",
18978
+ source: "this",
18979
+ predicate: metadata.through,
18980
+ target: "value",
18981
+ ...(metadata.local && { local: true })
18982
+ }];
18983
+ }
18984
+ /**
18985
+ * Generate collection action from metadata (Phase 1: Prolog-free refactor)
18986
+ * Replaces Prolog queries: collection_adder, collection_remover, collection_setter
18987
+ * @private
18988
+ */
18989
+ generateCollectionAction(key, actionType) {
18990
+ const metadata = this.getCollectionMetadata(key);
18991
+ if (!metadata) {
18992
+ throw new Error(`Collection "${key}" has no metadata defined`);
18993
+ }
18994
+ if (!metadata.through) {
18995
+ throw new Error(`Collection "${key}" has no 'through' predicate defined`);
18996
+ }
18997
+ const actionMap = {
18998
+ adder: "addLink",
18999
+ remover: "removeLink",
19000
+ setter: "collectionSetter"
19001
+ };
19002
+ return [{
19003
+ action: actionMap[actionType],
19004
+ source: "this",
19005
+ predicate: metadata.through,
19006
+ target: "value",
19007
+ ...(metadata.local && { local: true })
19008
+ }];
19009
+ }
18582
19010
  static async assignValuesToInstance(perspective, instance, values) {
18583
19011
  // Map properties to object
18584
19012
  const propsObject = Object.fromEntries(await Promise.all(values.map(async ([name, value, resolve]) => {
@@ -18635,11 +19063,96 @@ class Ad4mModel {
18635
19063
  subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", SubjectClass),
18636
19064
  ${subQueries.join(", ")}
18637
19065
  `;
18638
- const result = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(fullQuery);
18639
- if (result?.[0]) {
18640
- const { Properties, Collections, Timestamp, Author } = result?.[0];
18641
- const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
18642
- await Ad4mModel.assignValuesToInstance(__classPrivateFieldGet(this, _Ad4mModel_perspective, "f"), this, values);
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)
19080
+ try {
19081
+ const ctor = this.constructor;
19082
+ const metadata = ctor.getModelMetadata();
19083
+ // Query for all links from this specific node (base expression)
19084
+ const linksQuery = `
19085
+ SELECT id, predicate, out.uri AS target, author, timestamp
19086
+ FROM link
19087
+ WHERE in.uri = '${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}'
19088
+ ORDER BY timestamp ASC
19089
+ `;
19090
+ const links = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").querySurrealDB(linksQuery);
19091
+ if (links && links.length > 0) {
19092
+ let maxTimestamp = null;
19093
+ let latestAuthor = null;
19094
+ // Process properties
19095
+ for (const [propName, propMeta] of Object.entries(metadata.properties)) {
19096
+ const matching = links.filter((l) => l.predicate === propMeta.predicate);
19097
+ if (matching.length > 0) {
19098
+ const link = matching[0]; // Take first/latest
19099
+ let value = link.target;
19100
+ // Track timestamp/author
19101
+ if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
19102
+ maxTimestamp = link.timestamp;
19103
+ latestAuthor = link.author;
19104
+ }
19105
+ // Handle resolveLanguage
19106
+ if (propMeta.resolveLanguage && propMeta.resolveLanguage !== 'literal') {
19107
+ try {
19108
+ const expression = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").getExpression(value);
19109
+ if (expression) {
19110
+ try {
19111
+ value = JSON.parse(expression.data);
19112
+ }
19113
+ catch {
19114
+ value = expression.data;
19115
+ }
19116
+ }
19117
+ }
19118
+ catch (e) {
19119
+ console.warn(`Failed to resolve expression for ${propName}:`, e);
19120
+ }
19121
+ }
19122
+ else if (typeof value === 'string' && value.startsWith('literal://')) {
19123
+ // Parse literal URL
19124
+ try {
19125
+ const parsed = Literal.fromUrl(value).get();
19126
+ value = parsed.data !== undefined ? parsed.data : parsed;
19127
+ }
19128
+ catch (e) {
19129
+ // Keep original value
19130
+ }
19131
+ }
19132
+ // Apply transform if exists
19133
+ if (propMeta.transform && typeof propMeta.transform === 'function') {
19134
+ value = propMeta.transform(value);
19135
+ }
19136
+ this[propName] = value;
19137
+ }
19138
+ }
19139
+ // Process collections
19140
+ for (const [collName, collMeta] of Object.entries(metadata.collections)) {
19141
+ const matching = links.filter((l) => l.predicate === collMeta.predicate);
19142
+ // Links are already sorted by timestamp ASC from the query, so map preserves order
19143
+ this[collName] = matching.map((l) => l.target);
19144
+ }
19145
+ // Set author and timestamp
19146
+ if (latestAuthor) {
19147
+ this.author = latestAuthor;
19148
+ }
19149
+ if (maxTimestamp) {
19150
+ this.timestamp = maxTimestamp;
19151
+ }
19152
+ }
19153
+ }
19154
+ catch (e) {
19155
+ console.error(`SurrealDB getData also failed for ${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}:`, e);
18643
19156
  }
18644
19157
  return this;
18645
19158
  }
@@ -19223,7 +19736,7 @@ WHERE ${whereConditions.join(' AND ')}
19223
19736
  if (!currentValue || currentValue === "" || currentValue === 0 || isEmptyObject) {
19224
19737
  let convertedValue = target;
19225
19738
  // Only process if target has a value
19226
- if (target !== undefined && target !== null) {
19739
+ if (target !== undefined && target !== null && target !== '') {
19227
19740
  // Check if we need to resolve a non-literal language expression
19228
19741
  if (propMeta.resolveLanguage != undefined && propMeta.resolveLanguage !== 'literal' && typeof target === 'string') {
19229
19742
  // For non-literal languages, resolve the expression via perspective.getExpression()
@@ -19242,7 +19755,8 @@ WHERE ${whereConditions.join(' AND ')}
19242
19755
  }
19243
19756
  }
19244
19757
  catch (e) {
19245
- console.warn(`Failed to resolve expression for ${propName}:`, e);
19758
+ console.warn(`Failed to resolve expression for ${propName} with target "${target}":`, e);
19759
+ console.warn("Falling back to raw value");
19246
19760
  convertedValue = target; // Fall back to raw value
19247
19761
  }
19248
19762
  }
@@ -19687,65 +20201,72 @@ WHERE ${whereConditions.join(' AND ')}
19687
20201
  }
19688
20202
  }
19689
20203
  async setProperty(key, value, batchId) {
19690
- const setters = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), property_setter(C, "${key}", Setter)`);
19691
- if (setters && setters.length > 0) {
19692
- const actions = eval(setters[0].Setter);
19693
- const resolveLanguageResults = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), property_resolve_language(C, "${key}", Language)`);
19694
- let resolveLanguage;
19695
- if (resolveLanguageResults && resolveLanguageResults.length > 0) {
19696
- resolveLanguage = resolveLanguageResults[0].Language;
19697
- }
19698
- if (resolveLanguage) {
19699
- value = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").createExpression(value, resolveLanguage);
19700
- }
19701
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
20204
+ // Phase 1: Use metadata instead of Prolog queries
20205
+ const metadata = this.getPropertyMetadata(key);
20206
+ if (!metadata) {
20207
+ console.warn(`Property "${key}" has no metadata, skipping`);
20208
+ return;
20209
+ }
20210
+ // Generate actions from metadata (replaces Prolog query)
20211
+ const actions = this.generatePropertySetterAction(key, metadata);
20212
+ // Get resolve language from metadata (replaces Prolog query)
20213
+ let resolveLanguage = metadata.resolveLanguage;
20214
+ if (resolveLanguage) {
20215
+ value = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").createExpression(value, resolveLanguage);
19702
20216
  }
20217
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
19703
20218
  }
19704
20219
  async setCollectionSetter(key, value, batchId) {
19705
- let collectionSetters = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), collection_setter(C, "${singularToPlural(key)}", Setter)`);
19706
- if (!collectionSetters)
19707
- collectionSetters = [];
19708
- if (collectionSetters.length > 0) {
19709
- const actions = eval(collectionSetters[0].Setter);
19710
- if (value) {
19711
- if (Array.isArray(value)) {
19712
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), value.map((v) => ({ name: "value", value: v })), batchId);
19713
- }
19714
- else {
19715
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
19716
- }
20220
+ // Phase 1: Use metadata instead of Prolog queries
20221
+ const metadata = this.getCollectionMetadata(key);
20222
+ if (!metadata) {
20223
+ console.warn(`Collection "${key}" has no metadata, skipping`);
20224
+ return;
20225
+ }
20226
+ // Generate actions from metadata (replaces Prolog query)
20227
+ const actions = this.generateCollectionAction(key, 'setter');
20228
+ if (value) {
20229
+ if (Array.isArray(value)) {
20230
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), value.map((v) => ({ name: "value", value: v })), batchId);
20231
+ }
20232
+ else {
20233
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
19717
20234
  }
19718
20235
  }
19719
20236
  }
19720
20237
  async setCollectionAdder(key, value, batchId) {
19721
- let adders = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), collection_adder(C, "${singularToPlural(key)}", Adder)`);
19722
- if (!adders)
19723
- adders = [];
19724
- if (adders.length > 0) {
19725
- const actions = eval(adders[0].Adder);
19726
- if (value) {
19727
- if (Array.isArray(value)) {
19728
- await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
19729
- }
19730
- else {
19731
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
19732
- }
20238
+ // Phase 1: Use metadata instead of Prolog queries
20239
+ const metadata = this.getCollectionMetadata(key);
20240
+ if (!metadata) {
20241
+ console.warn(`Collection "${key}" has no metadata, skipping`);
20242
+ return;
20243
+ }
20244
+ // Generate actions from metadata (replaces Prolog query)
20245
+ const actions = this.generateCollectionAction(key, 'adder');
20246
+ if (value) {
20247
+ if (Array.isArray(value)) {
20248
+ await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
20249
+ }
20250
+ else {
20251
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
19733
20252
  }
19734
20253
  }
19735
20254
  }
19736
20255
  async setCollectionRemover(key, value, batchId) {
19737
- let removers = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), collection_remover(C, "${singularToPlural(key)}", Remover)`);
19738
- if (!removers)
19739
- removers = [];
19740
- if (removers.length > 0) {
19741
- const actions = eval(removers[0].Remover);
19742
- if (value) {
19743
- if (Array.isArray(value)) {
19744
- await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
19745
- }
19746
- else {
19747
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
19748
- }
20256
+ // Phase 1: Use metadata instead of Prolog queries
20257
+ const metadata = this.getCollectionMetadata(key);
20258
+ if (!metadata) {
20259
+ console.warn(`Collection "${key}" has no metadata, skipping`);
20260
+ return;
20261
+ }
20262
+ // Generate actions from metadata (replaces Prolog query)
20263
+ const actions = this.generateCollectionAction(key, 'remover');
20264
+ if (value) {
20265
+ if (Array.isArray(value)) {
20266
+ await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
20267
+ }
20268
+ else {
20269
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
19749
20270
  }
19750
20271
  }
19751
20272
  }
@@ -19829,11 +20350,21 @@ WHERE ${whereConditions.join(' AND ')}
19829
20350
  break;
19830
20351
  }
19831
20352
  }
19832
- else if (Array.isArray(value) && value.length > 0) {
19833
- await this.setCollectionSetter(key, value, batchId);
20353
+ 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
19834
20359
  }
19835
20360
  else if (value !== undefined && value !== null && value !== "") {
19836
20361
  if (setProperties) {
20362
+ // Check if this is a collection property (has collection metadata)
20363
+ const collMetadata = this.getCollectionMetadata(key);
20364
+ if (collMetadata) {
20365
+ // Skip - it's a collection, not a regular property
20366
+ continue;
20367
+ }
19837
20368
  await this.setProperty(key, value, batchId);
19838
20369
  }
19839
20370
  }