@coasys/ad4m 0.11.2-dev.4 → 0.11.2-dev.6
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 +181 -69
- package/lib/index.js +181 -69
- package/lib/src/model/Ad4mModel.d.ts +6 -5
- package/lib/src/model/Ad4mModel.js +107 -41
- package/lib/src/model/Ad4mModel.test.js +10 -10
- package/lib/src/model/decorators.d.ts +26 -18
- package/lib/src/model/decorators.js +40 -25
- package/lib/src/perspectives/PerspectiveProxy.d.ts +3 -0
- package/lib/src/perspectives/PerspectiveProxy.js +34 -3
- package/package.json +1 -1
- package/src/model/Ad4mModel.test.ts +10 -10
- package/src/model/Ad4mModel.ts +115 -43
- package/src/model/decorators.ts +48 -34
- package/src/perspectives/PerspectiveProxy.ts +43 -7
package/lib/index.js
CHANGED
|
@@ -5787,6 +5787,7 @@ class PerspectiveProxy {
|
|
|
5787
5787
|
const collName = result.Coll;
|
|
5788
5788
|
let predicate = null;
|
|
5789
5789
|
let instanceFilter = undefined;
|
|
5790
|
+
let condition = undefined;
|
|
5790
5791
|
// Try to extract predicate from collection_adder first
|
|
5791
5792
|
const adderResults = await this.infer(`subject_class("${className}", C), collection_adder(C, "${collName}", Adder)`);
|
|
5792
5793
|
if (adderResults && adderResults.length > 0) {
|
|
@@ -5796,6 +5797,8 @@ class PerspectiveProxy {
|
|
|
5796
5797
|
predicate = predicateMatch[1] || predicateMatch[2];
|
|
5797
5798
|
}
|
|
5798
5799
|
}
|
|
5800
|
+
// Note: condition is not stored in SDNA, it's read from class metadata
|
|
5801
|
+
// It will be populated by augmentMetadataWithCollectionOptions() when needed
|
|
5799
5802
|
// Parse collection_getter from SDNA to extract predicate and instanceFilter
|
|
5800
5803
|
// Format 1 (findall): collection_getter(c, Base, "comments", List) :- findall(C, triple(Base, "todo://comment", C), List).
|
|
5801
5804
|
// Format 2 (setof): collection_getter(c, Base, "messages", List) :- setof(Target, (triple(Base, "flux://entry_type", Target), ...), List).
|
|
@@ -5831,7 +5834,7 @@ class PerspectiveProxy {
|
|
|
5831
5834
|
}
|
|
5832
5835
|
}
|
|
5833
5836
|
if (predicate) {
|
|
5834
|
-
collections.set(collName, { predicate, instanceFilter });
|
|
5837
|
+
collections.set(collName, { predicate, instanceFilter, condition });
|
|
5835
5838
|
}
|
|
5836
5839
|
}
|
|
5837
5840
|
}
|
|
@@ -5907,6 +5910,7 @@ class PerspectiveProxy {
|
|
|
5907
5910
|
/**
|
|
5908
5911
|
* Gets collection values using SurrealDB when Prolog fails.
|
|
5909
5912
|
* This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
|
|
5913
|
+
* Note: This is used by Subject.ts (legacy pattern). Ad4mModel.ts uses getModelMetadata() instead.
|
|
5910
5914
|
*/
|
|
5911
5915
|
async getCollectionValuesViaSurreal(baseExpression, className, collectionName) {
|
|
5912
5916
|
const metadata = await this.getSubjectClassMetadataFromSDNA(className);
|
|
@@ -5925,6 +5929,31 @@ class PerspectiveProxy {
|
|
|
5925
5929
|
return [];
|
|
5926
5930
|
}
|
|
5927
5931
|
let values = result.map(r => r.value).filter(v => v !== "" && v !== '');
|
|
5932
|
+
// Apply condition filtering if present
|
|
5933
|
+
if (collMeta.condition && values.length > 0) {
|
|
5934
|
+
try {
|
|
5935
|
+
const filteredValues = [];
|
|
5936
|
+
for (const value of values) {
|
|
5937
|
+
let condition = collMeta.condition
|
|
5938
|
+
.replace(/\$perspective/g, `'${this.uuid}'`)
|
|
5939
|
+
.replace(/\$base/g, `'${baseExpression}'`)
|
|
5940
|
+
.replace(/Target/g, `'${value.replace(/'/g, "\\'")}'`);
|
|
5941
|
+
// If condition starts with WHERE, wrap in array length check
|
|
5942
|
+
if (condition.trim().startsWith('WHERE')) {
|
|
5943
|
+
condition = `array::len(SELECT * FROM link ${condition}) > 0`;
|
|
5944
|
+
}
|
|
5945
|
+
const filterResult = await this.querySurrealDB(`RETURN ${condition}`);
|
|
5946
|
+
const isTrue = filterResult === true || (Array.isArray(filterResult) && filterResult.length > 0 && filterResult[0] === true);
|
|
5947
|
+
if (isTrue) {
|
|
5948
|
+
filteredValues.push(value);
|
|
5949
|
+
}
|
|
5950
|
+
}
|
|
5951
|
+
values = filteredValues;
|
|
5952
|
+
}
|
|
5953
|
+
catch (error) {
|
|
5954
|
+
console.warn(`Failed to apply condition filter for ${collectionName}:`, error);
|
|
5955
|
+
}
|
|
5956
|
+
}
|
|
5928
5957
|
// Apply instance filter if present - batch-check all values at once
|
|
5929
5958
|
if (collMeta.instanceFilter) {
|
|
5930
5959
|
try {
|
|
@@ -5966,11 +5995,13 @@ class PerspectiveProxy {
|
|
|
5966
5995
|
if (triple.target) {
|
|
5967
5996
|
// Flag: must match both predicate AND exact target value
|
|
5968
5997
|
const escapedTarget = escapeSurrealString(triple.target);
|
|
5969
|
-
|
|
5998
|
+
// Note: Removed GROUP BY because it was causing SurrealDB to only return one result
|
|
5999
|
+
checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}'`;
|
|
5970
6000
|
}
|
|
5971
6001
|
else {
|
|
5972
6002
|
// Property: just check predicate exists
|
|
5973
|
-
|
|
6003
|
+
// Note: Removed GROUP BY because it was causing SurrealDB to only return one result
|
|
6004
|
+
checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}'`;
|
|
5974
6005
|
}
|
|
5975
6006
|
const result = await this.querySurrealDB(checkQuery);
|
|
5976
6007
|
validExpressionSets.push(new Set(result.map(r => r.uri)));
|
|
@@ -16457,14 +16488,14 @@ function hasLink(predicate) {
|
|
|
16457
16488
|
* static async findByName(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
|
|
16458
16489
|
*
|
|
16459
16490
|
* // Get highly rated recipes using a custom condition
|
|
16460
|
-
* @InstanceQuery({
|
|
16491
|
+
* @InstanceQuery({ prologCondition: "triple(Instance, 'recipe://rating', Rating), Rating > 4" })
|
|
16461
16492
|
* static async topRated(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
|
|
16462
16493
|
* }
|
|
16463
16494
|
* ```
|
|
16464
16495
|
*
|
|
16465
16496
|
* @param {Object} [options] - Query options
|
|
16466
16497
|
* @param {object} [options.where] - Object with property-value pairs to match
|
|
16467
|
-
* @param {string} [options.
|
|
16498
|
+
* @param {string} [options.prologCondition] - Custom Prolog condition for more complex queries
|
|
16468
16499
|
*/
|
|
16469
16500
|
function InstanceQuery(options) {
|
|
16470
16501
|
return function (target, key, descriptor) {
|
|
@@ -16483,8 +16514,8 @@ function InstanceQuery(options) {
|
|
|
16483
16514
|
query += `, property_getter(C, Instance, "${prop}", "${value}")`;
|
|
16484
16515
|
}
|
|
16485
16516
|
}
|
|
16486
|
-
if (options && options.
|
|
16487
|
-
query += ', ' + options.
|
|
16517
|
+
if (options && options.prologCondition) {
|
|
16518
|
+
query += ', ' + options.prologCondition;
|
|
16488
16519
|
}
|
|
16489
16520
|
// Try Prolog first
|
|
16490
16521
|
try {
|
|
@@ -16604,8 +16635,8 @@ function InstanceQuery(options) {
|
|
|
16604
16635
|
* @param {boolean} [opts.required] - Whether the property must have a value
|
|
16605
16636
|
* @param {boolean} [opts.writable=true] - Whether the property can be modified
|
|
16606
16637
|
* @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
|
|
16607
|
-
* @param {string} [opts.
|
|
16608
|
-
* @param {string} [opts.
|
|
16638
|
+
* @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
|
|
16639
|
+
* @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
|
|
16609
16640
|
* @param {boolean} [opts.local] - Whether the property should only be stored locally
|
|
16610
16641
|
*/
|
|
16611
16642
|
function Optional(opts) {
|
|
@@ -16616,8 +16647,8 @@ function Optional(opts) {
|
|
|
16616
16647
|
if (opts.required && !opts.initial) {
|
|
16617
16648
|
throw new Error("SubjectProperty requires an 'initial' option if 'required' is true");
|
|
16618
16649
|
}
|
|
16619
|
-
if (!opts.through && !opts.
|
|
16620
|
-
throw new Error("SubjectProperty requires either 'through' or '
|
|
16650
|
+
if (!opts.through && !opts.prologGetter) {
|
|
16651
|
+
throw new Error("SubjectProperty requires either 'through' or 'prologGetter' option");
|
|
16621
16652
|
}
|
|
16622
16653
|
target["__properties"] = target["__properties"] || {};
|
|
16623
16654
|
target["__properties"][key] = target["__properties"][key] || {};
|
|
@@ -16743,13 +16774,20 @@ function Flag(opts) {
|
|
|
16743
16774
|
* })
|
|
16744
16775
|
* comments: string[] = [];
|
|
16745
16776
|
*
|
|
16746
|
-
* // Collection with custom filter condition
|
|
16777
|
+
* // Collection with custom Prolog filter condition
|
|
16747
16778
|
* @Collection({
|
|
16748
16779
|
* through: "recipe://step",
|
|
16749
|
-
* where: {
|
|
16780
|
+
* where: { prologCondition: `triple(Target, "step://order", Order), Order < 3` }
|
|
16750
16781
|
* })
|
|
16751
16782
|
* firstSteps: string[] = [];
|
|
16752
16783
|
*
|
|
16784
|
+
* // Collection with custom SurrealDB filter condition
|
|
16785
|
+
* @Collection({
|
|
16786
|
+
* through: "recipe://entries",
|
|
16787
|
+
* where: { condition: `WHERE in.uri = Target AND predicate = 'recipe://has_ingredient' AND out.uri = 'recipe://test')`
|
|
16788
|
+
* })
|
|
16789
|
+
* ingredients: string[] = [];
|
|
16790
|
+
*
|
|
16753
16791
|
* // Local-only collection not shared with network
|
|
16754
16792
|
* @Collection({
|
|
16755
16793
|
* through: "recipe://note",
|
|
@@ -16769,7 +16807,7 @@ function Flag(opts) {
|
|
|
16769
16807
|
* @param {string} opts.through - The predicate URI for collection links
|
|
16770
16808
|
* @param {WhereOptions} [opts.where] - Filter conditions for collection values
|
|
16771
16809
|
* @param {any} [opts.where.isInstance] - Model class to filter instances by
|
|
16772
|
-
* @param {string} [opts.where.
|
|
16810
|
+
* @param {string} [opts.where.prologCondition] - Custom Prolog condition for filtering
|
|
16773
16811
|
* @param {boolean} [opts.local] - Whether collection links are stored locally only
|
|
16774
16812
|
*/
|
|
16775
16813
|
function Collection(opts) {
|
|
@@ -16869,13 +16907,13 @@ function ModelOptions(opts) {
|
|
|
16869
16907
|
let properties = obj.__properties || {};
|
|
16870
16908
|
for (let property in properties) {
|
|
16871
16909
|
let propertyCode = `property(${uuid}, "${property}").\n`;
|
|
16872
|
-
let { through, initial, required, resolveLanguage, writable, flag,
|
|
16910
|
+
let { through, initial, required, resolveLanguage, writable, flag, prologGetter, prologSetter, local } = properties[property];
|
|
16873
16911
|
if (resolveLanguage) {
|
|
16874
16912
|
propertyCode += `property_resolve(${uuid}, "${property}").\n`;
|
|
16875
16913
|
propertyCode += `property_resolve_language(${uuid}, "${property}", "${resolveLanguage}").\n`;
|
|
16876
16914
|
}
|
|
16877
|
-
if (
|
|
16878
|
-
propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- ${
|
|
16915
|
+
if (prologGetter) {
|
|
16916
|
+
propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- ${prologGetter}.\n`;
|
|
16879
16917
|
}
|
|
16880
16918
|
else if (through) {
|
|
16881
16919
|
propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- triple(Base, "${through}", Value).\n`;
|
|
@@ -16888,8 +16926,8 @@ function ModelOptions(opts) {
|
|
|
16888
16926
|
}
|
|
16889
16927
|
}
|
|
16890
16928
|
}
|
|
16891
|
-
if (
|
|
16892
|
-
propertyCode += `property_setter(${uuid}, "${property}", Actions) :- ${
|
|
16929
|
+
if (prologSetter) {
|
|
16930
|
+
propertyCode += `property_setter(${uuid}, "${property}", Actions) :- ${prologSetter}.\n`;
|
|
16893
16931
|
}
|
|
16894
16932
|
else if (writable && through) {
|
|
16895
16933
|
let setter = obj[propertyNameToSetterName(property)];
|
|
@@ -16927,8 +16965,8 @@ function ModelOptions(opts) {
|
|
|
16927
16965
|
let { through, where, local } = collections[collection];
|
|
16928
16966
|
if (through) {
|
|
16929
16967
|
if (where) {
|
|
16930
|
-
if (!where.isInstance && !where.condition) {
|
|
16931
|
-
throw "'where' needs one of 'isInstance' or 'condition'";
|
|
16968
|
+
if (!where.isInstance && !where.prologCondition && !where.condition) {
|
|
16969
|
+
throw "'where' needs one of 'isInstance', 'prologCondition', or 'condition'";
|
|
16932
16970
|
}
|
|
16933
16971
|
let conditions = [];
|
|
16934
16972
|
if (where.isInstance) {
|
|
@@ -16941,11 +16979,19 @@ function ModelOptions(opts) {
|
|
|
16941
16979
|
}
|
|
16942
16980
|
conditions.push(`instance(OtherClass, Target), subject_class("${otherClass}", OtherClass)`);
|
|
16943
16981
|
}
|
|
16944
|
-
if (where.
|
|
16945
|
-
conditions.push(where.
|
|
16982
|
+
if (where.prologCondition) {
|
|
16983
|
+
conditions.push(where.prologCondition);
|
|
16984
|
+
}
|
|
16985
|
+
// If there are Prolog conditions (isInstance or prologCondition), use setof with conditions
|
|
16986
|
+
// If only condition is present, use simple findall (SurrealDB will filter later)
|
|
16987
|
+
if (conditions.length > 0) {
|
|
16988
|
+
const conditionString = conditions.join(", ");
|
|
16989
|
+
collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- setof(Target, (triple(Base, "${through}", Target), ${conditionString}), List).\n`;
|
|
16990
|
+
}
|
|
16991
|
+
else {
|
|
16992
|
+
// Only SurrealDB condition present (no Prolog filtering)
|
|
16993
|
+
collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- findall(C, triple(Base, "${through}", C), List).\n`;
|
|
16946
16994
|
}
|
|
16947
|
-
const conditionString = conditions.join(", ");
|
|
16948
|
-
collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- setof(Target, (triple(Base, "${through}", Target), ${conditionString}), List).\n`;
|
|
16949
16995
|
}
|
|
16950
16996
|
else {
|
|
16951
16997
|
collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- findall(C, triple(Base, "${through}", C), List).\n`;
|
|
@@ -17047,8 +17093,8 @@ function ModelOptions(opts) {
|
|
|
17047
17093
|
* @param {string} opts.through - The predicate URI for the property
|
|
17048
17094
|
* @param {string} [opts.initial] - Initial value (defaults to "literal://string:uninitialized")
|
|
17049
17095
|
* @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
|
|
17050
|
-
* @param {string} [opts.
|
|
17051
|
-
* @param {string} [opts.
|
|
17096
|
+
* @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
|
|
17097
|
+
* @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
|
|
17052
17098
|
* @param {boolean} [opts.local] - Whether the property should only be stored locally
|
|
17053
17099
|
*/
|
|
17054
17100
|
function Property(opts) {
|
|
@@ -17111,7 +17157,7 @@ function Property(opts) {
|
|
|
17111
17157
|
* @param {string} opts.through - The predicate URI for the property
|
|
17112
17158
|
* @param {string} [opts.initial] - Initial value (if property should have one)
|
|
17113
17159
|
* @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
|
|
17114
|
-
* @param {string} [opts.
|
|
17160
|
+
* @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
|
|
17115
17161
|
* @param {boolean} [opts.local] - Whether the property should only be stored locally
|
|
17116
17162
|
*/
|
|
17117
17163
|
function ReadOnly(opts) {
|
|
@@ -18918,9 +18964,9 @@ class Ad4mModel {
|
|
|
18918
18964
|
writable: options.writable || false,
|
|
18919
18965
|
...(options.initial !== undefined && { initial: options.initial }),
|
|
18920
18966
|
...(options.resolveLanguage !== undefined && { resolveLanguage: options.resolveLanguage }),
|
|
18967
|
+
...(options.prologGetter !== undefined && { prologGetter: options.prologGetter }),
|
|
18921
18968
|
...(options.getter !== undefined && { getter: options.getter }),
|
|
18922
|
-
...(options.
|
|
18923
|
-
...(options.setter !== undefined && { setter: options.setter }),
|
|
18969
|
+
...(options.prologSetter !== undefined && { prologSetter: options.prologSetter }),
|
|
18924
18970
|
...(options.local !== undefined && { local: options.local }),
|
|
18925
18971
|
...(options.transform !== undefined && { transform: options.transform }),
|
|
18926
18972
|
...(options.flag !== undefined && { flag: options.flag })
|
|
@@ -18936,7 +18982,7 @@ class Ad4mModel {
|
|
|
18936
18982
|
predicate: options.through || "",
|
|
18937
18983
|
...(options.where !== undefined && { where: options.where }),
|
|
18938
18984
|
...(options.local !== undefined && { local: options.local }),
|
|
18939
|
-
...(options.
|
|
18985
|
+
...(options.getter !== undefined && { getter: options.getter })
|
|
18940
18986
|
};
|
|
18941
18987
|
}
|
|
18942
18988
|
// Fallback: If both structures are empty but a JSON schema is attached, derive from it
|
|
@@ -19047,9 +19093,9 @@ class Ad4mModel {
|
|
|
19047
19093
|
if (metadata.writable === false) {
|
|
19048
19094
|
throw new Error(`Property "${key}" is read-only and cannot be written`);
|
|
19049
19095
|
}
|
|
19050
|
-
if (metadata.
|
|
19051
|
-
// Custom setter - throw error for now (Phase 2)
|
|
19052
|
-
throw new Error(`Custom setter for property "${key}" not yet supported without Prolog. ` +
|
|
19096
|
+
if (metadata.prologSetter) {
|
|
19097
|
+
// Custom Prolog setter - throw error for now (Phase 2)
|
|
19098
|
+
throw new Error(`Custom Prolog setter for property "${key}" not yet supported without Prolog. ` +
|
|
19053
19099
|
`Use standard @Property decorator or enable Prolog for custom setters.`);
|
|
19054
19100
|
}
|
|
19055
19101
|
if (!metadata.through) {
|
|
@@ -19134,8 +19180,26 @@ class Ad4mModel {
|
|
|
19134
19180
|
}
|
|
19135
19181
|
return [name, finalValue];
|
|
19136
19182
|
})));
|
|
19183
|
+
// Filter out properties that are read-only (getters without setters)
|
|
19184
|
+
const writableProps = Object.fromEntries(Object.entries(propsObject).filter(([key]) => {
|
|
19185
|
+
const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(instance), key);
|
|
19186
|
+
if (!descriptor) {
|
|
19187
|
+
// No descriptor means it's a regular property on the instance, allow it
|
|
19188
|
+
return true;
|
|
19189
|
+
}
|
|
19190
|
+
// Check if it's an accessor descriptor (has get/set) vs data descriptor (has value/writable)
|
|
19191
|
+
const isAccessor = descriptor.get !== undefined || descriptor.set !== undefined;
|
|
19192
|
+
if (isAccessor) {
|
|
19193
|
+
// Accessor descriptor: only allow if it has a setter
|
|
19194
|
+
return descriptor.set !== undefined;
|
|
19195
|
+
}
|
|
19196
|
+
else {
|
|
19197
|
+
// Data descriptor: only allow if writable is not explicitly false
|
|
19198
|
+
return descriptor.writable !== false;
|
|
19199
|
+
}
|
|
19200
|
+
}));
|
|
19137
19201
|
// Assign properties to instance
|
|
19138
|
-
Object.assign(instance,
|
|
19202
|
+
Object.assign(instance, writableProps);
|
|
19139
19203
|
}
|
|
19140
19204
|
async getData() {
|
|
19141
19205
|
// Builds an object with the author, timestamp, all properties, & all collections on the Ad4mModel and saves it to the instance
|
|
@@ -19161,10 +19225,10 @@ class Ad4mModel {
|
|
|
19161
19225
|
let maxTimestamp = null;
|
|
19162
19226
|
let latestAuthor = null;
|
|
19163
19227
|
let originalAuthor = null;
|
|
19164
|
-
// Process properties (skip those with
|
|
19228
|
+
// Process properties (skip those with custom getter)
|
|
19165
19229
|
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
19166
|
-
if (propMeta.
|
|
19167
|
-
continue; // Handle via
|
|
19230
|
+
if (propMeta.getter)
|
|
19231
|
+
continue; // Handle via custom getter evaluation
|
|
19168
19232
|
const matching = links.filter((l) => l.predicate === propMeta.predicate);
|
|
19169
19233
|
if (matching.length > 0) {
|
|
19170
19234
|
// "Latest wins" semantics: select the last element since links are ordered ASC.
|
|
@@ -19216,14 +19280,44 @@ class Ad4mModel {
|
|
|
19216
19280
|
this[propName] = value;
|
|
19217
19281
|
}
|
|
19218
19282
|
}
|
|
19219
|
-
// Process collections (skip those with
|
|
19283
|
+
// Process collections (skip those with custom getter)
|
|
19220
19284
|
for (const [collName, collMeta] of Object.entries(metadata.collections)) {
|
|
19221
|
-
if (collMeta.
|
|
19222
|
-
continue; // Handle via
|
|
19285
|
+
if (collMeta.getter)
|
|
19286
|
+
continue; // Handle via custom getter evaluation
|
|
19223
19287
|
const matching = links.filter((l) => l.predicate === collMeta.predicate);
|
|
19224
19288
|
// Collections preserve chronological order: links are sorted ASC by timestamp,
|
|
19225
19289
|
// so the collection reflects the order in which items were added (oldest to newest).
|
|
19226
19290
|
let values = matching.map((l) => l.target);
|
|
19291
|
+
// Apply where.condition filtering if present
|
|
19292
|
+
if (collMeta.where?.condition && values.length > 0) {
|
|
19293
|
+
try {
|
|
19294
|
+
// Filter values by evaluating condition for each value
|
|
19295
|
+
const filteredValues = [];
|
|
19296
|
+
for (const value of values) {
|
|
19297
|
+
let condition = collMeta.where.condition
|
|
19298
|
+
.replace(/\$perspective/g, `'${__classPrivateFieldGet(this, _Ad4mModel_perspective, "f").uuid}'`)
|
|
19299
|
+
.replace(/\$base/g, `'${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}'`)
|
|
19300
|
+
.replace(/Target/g, `'${value.replace(/'/g, "\\'")}'`);
|
|
19301
|
+
// If condition starts with WHERE, wrap it in array length check pattern
|
|
19302
|
+
// Using array::len() to properly count matching links
|
|
19303
|
+
if (condition.trim().startsWith('WHERE')) {
|
|
19304
|
+
condition = `array::len(SELECT * FROM link ${condition}) > 0`;
|
|
19305
|
+
}
|
|
19306
|
+
const filterQuery = `RETURN ${condition}`;
|
|
19307
|
+
const result = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").querySurrealDB(filterQuery);
|
|
19308
|
+
// RETURN can return the value directly or in an array
|
|
19309
|
+
const isTrue = result === true || (Array.isArray(result) && result.length > 0 && result[0] === true);
|
|
19310
|
+
if (isTrue) {
|
|
19311
|
+
filteredValues.push(value);
|
|
19312
|
+
}
|
|
19313
|
+
}
|
|
19314
|
+
values = filteredValues;
|
|
19315
|
+
}
|
|
19316
|
+
catch (error) {
|
|
19317
|
+
console.warn(`Failed to apply condition filter for ${collName}:`, error);
|
|
19318
|
+
// Keep unfiltered values on error
|
|
19319
|
+
}
|
|
19320
|
+
}
|
|
19227
19321
|
// Apply where.isInstance filtering if present
|
|
19228
19322
|
if (collMeta.where?.isInstance && values.length > 0) {
|
|
19229
19323
|
try {
|
|
@@ -19253,7 +19347,26 @@ class Ad4mModel {
|
|
|
19253
19347
|
}
|
|
19254
19348
|
}
|
|
19255
19349
|
// Evaluate SurrealQL getters
|
|
19256
|
-
await ctor.
|
|
19350
|
+
await ctor.evaluateCustomGettersForInstance(this, __classPrivateFieldGet(this, _Ad4mModel_perspective, "f"), metadata);
|
|
19351
|
+
// Apply where.isInstance filtering to getter collections
|
|
19352
|
+
// (non-getter collections were already filtered above)
|
|
19353
|
+
for (const [collName, collMeta] of Object.entries(metadata.collections)) {
|
|
19354
|
+
if (collMeta.getter && collMeta.where?.isInstance && this[collName]?.length > 0) {
|
|
19355
|
+
try {
|
|
19356
|
+
const className = typeof collMeta.where.isInstance === 'string'
|
|
19357
|
+
? collMeta.where.isInstance
|
|
19358
|
+
: collMeta.where.isInstance.name;
|
|
19359
|
+
const filterMetadata = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").getSubjectClassMetadataFromSDNA(className);
|
|
19360
|
+
if (filterMetadata) {
|
|
19361
|
+
const filtered = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").batchCheckSubjectInstances(this[collName], filterMetadata);
|
|
19362
|
+
this[collName] = filtered;
|
|
19363
|
+
}
|
|
19364
|
+
}
|
|
19365
|
+
catch (error) {
|
|
19366
|
+
// Keep unfiltered values on error
|
|
19367
|
+
}
|
|
19368
|
+
}
|
|
19369
|
+
}
|
|
19257
19370
|
}
|
|
19258
19371
|
catch (e) {
|
|
19259
19372
|
console.error(`SurrealDB getData also failed for ${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}:`, e);
|
|
@@ -19286,14 +19399,14 @@ class Ad4mModel {
|
|
|
19286
19399
|
* Evaluates custom SurrealQL getters for properties and collections on a specific instance.
|
|
19287
19400
|
* @private
|
|
19288
19401
|
*/
|
|
19289
|
-
static async
|
|
19402
|
+
static async evaluateCustomGettersForInstance(instance, perspective, metadata) {
|
|
19290
19403
|
const safeBaseExpression = this.formatSurrealValue(instance.baseExpression);
|
|
19291
|
-
// Evaluate property
|
|
19404
|
+
// Evaluate property getters
|
|
19292
19405
|
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
19293
|
-
if (propMeta.
|
|
19406
|
+
if (propMeta.getter) {
|
|
19294
19407
|
try {
|
|
19295
19408
|
// Replace 'Base' placeholder with actual base expression
|
|
19296
|
-
const query = propMeta.
|
|
19409
|
+
const query = propMeta.getter.replace(/Base/g, safeBaseExpression);
|
|
19297
19410
|
// Query from node table to have graph traversal context
|
|
19298
19411
|
const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
|
|
19299
19412
|
if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null && result[0].value !== 'None' && result[0].value !== '') {
|
|
@@ -19301,28 +19414,28 @@ class Ad4mModel {
|
|
|
19301
19414
|
}
|
|
19302
19415
|
}
|
|
19303
19416
|
catch (error) {
|
|
19304
|
-
console.warn(`Failed to evaluate
|
|
19417
|
+
console.warn(`Failed to evaluate getter for ${propName}:`, error);
|
|
19305
19418
|
}
|
|
19306
19419
|
}
|
|
19307
19420
|
}
|
|
19308
|
-
// Evaluate collection
|
|
19421
|
+
// Evaluate collection getters
|
|
19309
19422
|
for (const [collName, collMeta] of Object.entries(metadata.collections)) {
|
|
19310
|
-
if (collMeta.
|
|
19423
|
+
if (collMeta.getter) {
|
|
19311
19424
|
try {
|
|
19312
19425
|
// Replace 'Base' placeholder with actual base expression
|
|
19313
|
-
const query = collMeta.
|
|
19426
|
+
const query = collMeta.getter.replace(/Base/g, safeBaseExpression);
|
|
19314
19427
|
// Query from node table to have graph traversal context
|
|
19315
19428
|
const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
|
|
19316
19429
|
if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null) {
|
|
19317
19430
|
// Filter out 'None' from collection results
|
|
19318
19431
|
const value = result[0].value;
|
|
19319
19432
|
instance[collName] = Array.isArray(value)
|
|
19320
|
-
? value.filter((v) => v && v !== '' && v !== 'None')
|
|
19433
|
+
? value.filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None')
|
|
19321
19434
|
: value;
|
|
19322
19435
|
}
|
|
19323
19436
|
}
|
|
19324
19437
|
catch (error) {
|
|
19325
|
-
console.warn(`Failed to evaluate
|
|
19438
|
+
console.warn(`Failed to evaluate getter for ${collName}:`, error);
|
|
19326
19439
|
}
|
|
19327
19440
|
}
|
|
19328
19441
|
}
|
|
@@ -19820,7 +19933,7 @@ WHERE ${whereConditions.join(' AND ')}
|
|
|
19820
19933
|
});
|
|
19821
19934
|
}
|
|
19822
19935
|
// Collect values to assign to instance
|
|
19823
|
-
const values = [...Properties, ...Collections, ["
|
|
19936
|
+
const values = [...Properties, ...Collections, ["createdAt", Timestamp], ["author", Author]];
|
|
19824
19937
|
await Ad4mModel.assignValuesToInstance(perspective, instance, values);
|
|
19825
19938
|
return instance;
|
|
19826
19939
|
}
|
|
@@ -19888,11 +20001,11 @@ WHERE ${whereConditions.join(' AND ')}
|
|
|
19888
20001
|
latestAuthor = link.author;
|
|
19889
20002
|
}
|
|
19890
20003
|
}
|
|
19891
|
-
// Find matching property (skip those with
|
|
20004
|
+
// Find matching property (skip those with getter)
|
|
19892
20005
|
let foundProperty = false;
|
|
19893
20006
|
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
19894
|
-
if (propMeta.
|
|
19895
|
-
continue; // Handle via
|
|
20007
|
+
if (propMeta.getter)
|
|
20008
|
+
continue; // Handle via getter evaluation
|
|
19896
20009
|
if (propMeta.predicate === predicate) {
|
|
19897
20010
|
// For properties, take the first value (or we could use timestamp to get latest)
|
|
19898
20011
|
// Note: Empty objects {} are truthy, so we need to check for them explicitly
|
|
@@ -19962,11 +20075,11 @@ WHERE ${whereConditions.join(' AND ')}
|
|
|
19962
20075
|
break;
|
|
19963
20076
|
}
|
|
19964
20077
|
}
|
|
19965
|
-
// If not a property, check if it's a collection (skip those with
|
|
20078
|
+
// If not a property, check if it's a collection (skip those with getter)
|
|
19966
20079
|
if (!foundProperty) {
|
|
19967
20080
|
for (const [collName, collMeta] of Object.entries(metadata.collections)) {
|
|
19968
|
-
if (collMeta.
|
|
19969
|
-
continue; // Handle via
|
|
20081
|
+
if (collMeta.getter)
|
|
20082
|
+
continue; // Handle via getter evaluation
|
|
19970
20083
|
if (collMeta.predicate === predicate) {
|
|
19971
20084
|
// For collections, accumulate all values with their timestamps and indices for sorting
|
|
19972
20085
|
if (!instance[collName]) {
|
|
@@ -20046,7 +20159,7 @@ WHERE ${whereConditions.join(' AND ')}
|
|
|
20046
20159
|
// Replace collection with sorted values, filtering out empty strings and None
|
|
20047
20160
|
instance[collName] = pairs
|
|
20048
20161
|
.map(p => p.value)
|
|
20049
|
-
.filter((v) => v && v !== '' && v !== 'None');
|
|
20162
|
+
.filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None');
|
|
20050
20163
|
// Clean up temporary arrays
|
|
20051
20164
|
delete instance[timestampsKey];
|
|
20052
20165
|
delete instance[indicesKey];
|
|
@@ -20056,8 +20169,9 @@ WHERE ${whereConditions.join(' AND ')}
|
|
|
20056
20169
|
if (requestedProperties.length > 0 || requestedCollections.length > 0) {
|
|
20057
20170
|
const requestedAttributes = [...requestedProperties, ...requestedCollections];
|
|
20058
20171
|
Object.keys(instance).forEach((key) => {
|
|
20059
|
-
// Keep only requested attributes, plus always keep
|
|
20060
|
-
|
|
20172
|
+
// Keep only requested attributes, plus always keep createdAt, updatedAt, author, and baseExpression
|
|
20173
|
+
// Note: timestamp is a getter alias for createdAt, so we preserve createdAt instead
|
|
20174
|
+
if (!requestedAttributes.includes(key) && key !== 'createdAt' && key !== 'updatedAt' && key !== 'author' && key !== 'baseExpression') {
|
|
20061
20175
|
delete instance[key];
|
|
20062
20176
|
}
|
|
20063
20177
|
});
|
|
@@ -20068,12 +20182,13 @@ WHERE ${whereConditions.join(' AND ')}
|
|
|
20068
20182
|
console.error(`Failed to process SurrealDB instance ${base}:`, error);
|
|
20069
20183
|
}
|
|
20070
20184
|
}
|
|
20071
|
-
// Evaluate
|
|
20185
|
+
// Evaluate custom getters for all instances (single pass)
|
|
20186
|
+
// This populates collection values needed for where.isInstance filtering
|
|
20072
20187
|
for (const instance of instances) {
|
|
20073
|
-
await this.
|
|
20188
|
+
await this.evaluateCustomGettersForInstance(instance, perspective, metadata);
|
|
20074
20189
|
}
|
|
20075
20190
|
// Filter collections by where.isInstance if specified
|
|
20076
|
-
// Do this
|
|
20191
|
+
// Do this after initial evaluation so collection values exist for filtering
|
|
20077
20192
|
for (const instance of instances) {
|
|
20078
20193
|
for (const [collName, collMeta] of Object.entries(metadata.collections)) {
|
|
20079
20194
|
if (collMeta.where?.isInstance && instance[collName]?.length > 0) {
|
|
@@ -20090,6 +20205,7 @@ WHERE ${whereConditions.join(' AND ')}
|
|
|
20090
20205
|
}
|
|
20091
20206
|
// Check which subjects are instances of the target class
|
|
20092
20207
|
const validSubjects = await perspective.batchCheckSubjectInstances(subjects, classMetadata);
|
|
20208
|
+
// Update the collection with filtered instances
|
|
20093
20209
|
instance[collName] = validSubjects;
|
|
20094
20210
|
}
|
|
20095
20211
|
catch (error) {
|
|
@@ -20098,10 +20214,6 @@ WHERE ${whereConditions.join(' AND ')}
|
|
|
20098
20214
|
}
|
|
20099
20215
|
}
|
|
20100
20216
|
}
|
|
20101
|
-
// Evaluate SurrealQL getters for all instances
|
|
20102
|
-
for (const instance of instances) {
|
|
20103
|
-
await this.evaluateSurrealGettersForInstance(instance, perspective, metadata);
|
|
20104
|
-
}
|
|
20105
20217
|
// Filter by where conditions that couldn't be filtered in SQL
|
|
20106
20218
|
// This includes:
|
|
20107
20219
|
// - author/timestamp (computed from grouped links)
|
|
@@ -100,11 +100,11 @@ export interface PropertyMetadata {
|
|
|
100
100
|
/** Language for resolution (e.g., "literal") */
|
|
101
101
|
resolveLanguage?: string;
|
|
102
102
|
/** Custom Prolog getter code */
|
|
103
|
-
|
|
103
|
+
prologGetter?: string;
|
|
104
104
|
/** Custom Prolog setter code */
|
|
105
|
-
|
|
105
|
+
prologSetter?: string;
|
|
106
106
|
/** Custom SurrealQL getter code */
|
|
107
|
-
|
|
107
|
+
getter?: string;
|
|
108
108
|
/** Whether stored locally only */
|
|
109
109
|
local?: boolean;
|
|
110
110
|
/** Transform function */
|
|
@@ -123,10 +123,11 @@ export interface CollectionMetadata {
|
|
|
123
123
|
/** Filter conditions */
|
|
124
124
|
where?: {
|
|
125
125
|
isInstance?: any;
|
|
126
|
+
prologCondition?: string;
|
|
126
127
|
condition?: string;
|
|
127
128
|
};
|
|
128
129
|
/** Custom SurrealQL getter code */
|
|
129
|
-
|
|
130
|
+
getter?: string;
|
|
130
131
|
/** Whether stored locally only */
|
|
131
132
|
local?: boolean;
|
|
132
133
|
}
|
|
@@ -349,7 +350,7 @@ export declare class Ad4mModel {
|
|
|
349
350
|
* Evaluates custom SurrealQL getters for properties and collections on a specific instance.
|
|
350
351
|
* @private
|
|
351
352
|
*/
|
|
352
|
-
private static
|
|
353
|
+
private static evaluateCustomGettersForInstance;
|
|
353
354
|
/**
|
|
354
355
|
* Generates a SurrealQL query from a Query object.
|
|
355
356
|
*
|