@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.
@@ -44,14 +44,14 @@ export function hasLink(predicate) {
44
44
  * static async findByName(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
45
45
  *
46
46
  * // Get highly rated recipes using a custom condition
47
- * @InstanceQuery({ condition: "triple(Instance, 'recipe://rating', Rating), Rating > 4" })
47
+ * @InstanceQuery({ prologCondition: "triple(Instance, 'recipe://rating', Rating), Rating > 4" })
48
48
  * static async topRated(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
49
49
  * }
50
50
  * ```
51
51
  *
52
52
  * @param {Object} [options] - Query options
53
53
  * @param {object} [options.where] - Object with property-value pairs to match
54
- * @param {string} [options.condition] - Custom Prolog condition for more complex queries
54
+ * @param {string} [options.prologCondition] - Custom Prolog condition for more complex queries
55
55
  */
56
56
  export function InstanceQuery(options) {
57
57
  return function (target, key, descriptor) {
@@ -70,8 +70,8 @@ export function InstanceQuery(options) {
70
70
  query += `, property_getter(C, Instance, "${prop}", "${value}")`;
71
71
  }
72
72
  }
73
- if (options && options.condition) {
74
- query += ', ' + options.condition;
73
+ if (options && options.prologCondition) {
74
+ query += ', ' + options.prologCondition;
75
75
  }
76
76
  // Try Prolog first
77
77
  try {
@@ -191,8 +191,8 @@ export function InstanceQuery(options) {
191
191
  * @param {boolean} [opts.required] - Whether the property must have a value
192
192
  * @param {boolean} [opts.writable=true] - Whether the property can be modified
193
193
  * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
194
- * @param {string} [opts.getter] - Custom Prolog code for getting the property value
195
- * @param {string} [opts.setter] - Custom Prolog code for setting the property value
194
+ * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
195
+ * @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
196
196
  * @param {boolean} [opts.local] - Whether the property should only be stored locally
197
197
  */
198
198
  export function Optional(opts) {
@@ -203,8 +203,8 @@ export function Optional(opts) {
203
203
  if (opts.required && !opts.initial) {
204
204
  throw new Error("SubjectProperty requires an 'initial' option if 'required' is true");
205
205
  }
206
- if (!opts.through && !opts.getter) {
207
- throw new Error("SubjectProperty requires either 'through' or 'getter' option");
206
+ if (!opts.through && !opts.prologGetter) {
207
+ throw new Error("SubjectProperty requires either 'through' or 'prologGetter' option");
208
208
  }
209
209
  target["__properties"] = target["__properties"] || {};
210
210
  target["__properties"][key] = target["__properties"][key] || {};
@@ -330,13 +330,20 @@ export function Flag(opts) {
330
330
  * })
331
331
  * comments: string[] = [];
332
332
  *
333
- * // Collection with custom filter condition
333
+ * // Collection with custom Prolog filter condition
334
334
  * @Collection({
335
335
  * through: "recipe://step",
336
- * where: { condition: `triple(Target, "step://order", Order), Order < 3` }
336
+ * where: { prologCondition: `triple(Target, "step://order", Order), Order < 3` }
337
337
  * })
338
338
  * firstSteps: string[] = [];
339
339
  *
340
+ * // Collection with custom SurrealDB filter condition
341
+ * @Collection({
342
+ * through: "recipe://entries",
343
+ * where: { condition: `WHERE in.uri = Target AND predicate = 'recipe://has_ingredient' AND out.uri = 'recipe://test')`
344
+ * })
345
+ * ingredients: string[] = [];
346
+ *
340
347
  * // Local-only collection not shared with network
341
348
  * @Collection({
342
349
  * through: "recipe://note",
@@ -356,7 +363,7 @@ export function Flag(opts) {
356
363
  * @param {string} opts.through - The predicate URI for collection links
357
364
  * @param {WhereOptions} [opts.where] - Filter conditions for collection values
358
365
  * @param {any} [opts.where.isInstance] - Model class to filter instances by
359
- * @param {string} [opts.where.condition] - Custom Prolog condition for filtering
366
+ * @param {string} [opts.where.prologCondition] - Custom Prolog condition for filtering
360
367
  * @param {boolean} [opts.local] - Whether collection links are stored locally only
361
368
  */
362
369
  export function Collection(opts) {
@@ -456,13 +463,13 @@ export function ModelOptions(opts) {
456
463
  let properties = obj.__properties || {};
457
464
  for (let property in properties) {
458
465
  let propertyCode = `property(${uuid}, "${property}").\n`;
459
- let { through, initial, required, resolveLanguage, writable, flag, getter, setter, local } = properties[property];
466
+ let { through, initial, required, resolveLanguage, writable, flag, prologGetter, prologSetter, local } = properties[property];
460
467
  if (resolveLanguage) {
461
468
  propertyCode += `property_resolve(${uuid}, "${property}").\n`;
462
469
  propertyCode += `property_resolve_language(${uuid}, "${property}", "${resolveLanguage}").\n`;
463
470
  }
464
- if (getter) {
465
- propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- ${getter}.\n`;
471
+ if (prologGetter) {
472
+ propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- ${prologGetter}.\n`;
466
473
  }
467
474
  else if (through) {
468
475
  propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- triple(Base, "${through}", Value).\n`;
@@ -475,8 +482,8 @@ export function ModelOptions(opts) {
475
482
  }
476
483
  }
477
484
  }
478
- if (setter) {
479
- propertyCode += `property_setter(${uuid}, "${property}", Actions) :- ${setter}.\n`;
485
+ if (prologSetter) {
486
+ propertyCode += `property_setter(${uuid}, "${property}", Actions) :- ${prologSetter}.\n`;
480
487
  }
481
488
  else if (writable && through) {
482
489
  let setter = obj[propertyNameToSetterName(property)];
@@ -514,8 +521,8 @@ export function ModelOptions(opts) {
514
521
  let { through, where, local } = collections[collection];
515
522
  if (through) {
516
523
  if (where) {
517
- if (!where.isInstance && !where.condition) {
518
- throw "'where' needs one of 'isInstance' or 'condition'";
524
+ if (!where.isInstance && !where.prologCondition && !where.condition) {
525
+ throw "'where' needs one of 'isInstance', 'prologCondition', or 'condition'";
519
526
  }
520
527
  let conditions = [];
521
528
  if (where.isInstance) {
@@ -528,11 +535,19 @@ export function ModelOptions(opts) {
528
535
  }
529
536
  conditions.push(`instance(OtherClass, Target), subject_class("${otherClass}", OtherClass)`);
530
537
  }
531
- if (where.condition) {
532
- conditions.push(where.condition);
538
+ if (where.prologCondition) {
539
+ conditions.push(where.prologCondition);
540
+ }
541
+ // If there are Prolog conditions (isInstance or prologCondition), use setof with conditions
542
+ // If only condition is present, use simple findall (SurrealDB will filter later)
543
+ if (conditions.length > 0) {
544
+ const conditionString = conditions.join(", ");
545
+ collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- setof(Target, (triple(Base, "${through}", Target), ${conditionString}), List).\n`;
546
+ }
547
+ else {
548
+ // Only SurrealDB condition present (no Prolog filtering)
549
+ collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- findall(C, triple(Base, "${through}", C), List).\n`;
533
550
  }
534
- const conditionString = conditions.join(", ");
535
- collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- setof(Target, (triple(Base, "${through}", Target), ${conditionString}), List).\n`;
536
551
  }
537
552
  else {
538
553
  collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- findall(C, triple(Base, "${through}", C), List).\n`;
@@ -634,8 +649,8 @@ export function ModelOptions(opts) {
634
649
  * @param {string} opts.through - The predicate URI for the property
635
650
  * @param {string} [opts.initial] - Initial value (defaults to "literal://string:uninitialized")
636
651
  * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
637
- * @param {string} [opts.getter] - Custom Prolog code for getting the property value
638
- * @param {string} [opts.setter] - Custom Prolog code for setting the property value
652
+ * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
653
+ * @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
639
654
  * @param {boolean} [opts.local] - Whether the property should only be stored locally
640
655
  */
641
656
  export function Property(opts) {
@@ -698,7 +713,7 @@ export function Property(opts) {
698
713
  * @param {string} opts.through - The predicate URI for the property
699
714
  * @param {string} [opts.initial] - Initial value (if property should have one)
700
715
  * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
701
- * @param {string} [opts.getter] - Custom Prolog code for getting the property value
716
+ * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
702
717
  * @param {boolean} [opts.local] - Whether the property should only be stored locally
703
718
  */
704
719
  export function ReadOnly(opts) {
@@ -595,6 +595,7 @@ export declare class PerspectiveProxy {
595
595
  collections: Map<string, {
596
596
  predicate: string;
597
597
  instanceFilter?: string;
598
+ condition?: string;
598
599
  }>;
599
600
  } | null>;
600
601
  /**
@@ -609,6 +610,7 @@ export declare class PerspectiveProxy {
609
610
  /**
610
611
  * Gets collection values using SurrealDB when Prolog fails.
611
612
  * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
613
+ * Note: This is used by Subject.ts (legacy pattern). Ad4mModel.ts uses getModelMetadata() instead.
612
614
  */
613
615
  getCollectionValuesViaSurreal(baseExpression: string, className: string, collectionName: string): Promise<any[]>;
614
616
  /**
@@ -628,6 +630,7 @@ export declare class PerspectiveProxy {
628
630
  collections: Map<string, {
629
631
  predicate: string;
630
632
  instanceFilter?: string;
633
+ condition?: string;
631
634
  }>;
632
635
  }): Promise<string[]>;
633
636
  /**
@@ -1140,6 +1140,7 @@ export class PerspectiveProxy {
1140
1140
  const collName = result.Coll;
1141
1141
  let predicate = null;
1142
1142
  let instanceFilter = undefined;
1143
+ let condition = undefined;
1143
1144
  // Try to extract predicate from collection_adder first
1144
1145
  const adderResults = await this.infer(`subject_class("${className}", C), collection_adder(C, "${collName}", Adder)`);
1145
1146
  if (adderResults && adderResults.length > 0) {
@@ -1149,6 +1150,8 @@ export class PerspectiveProxy {
1149
1150
  predicate = predicateMatch[1] || predicateMatch[2];
1150
1151
  }
1151
1152
  }
1153
+ // Note: condition is not stored in SDNA, it's read from class metadata
1154
+ // It will be populated by augmentMetadataWithCollectionOptions() when needed
1152
1155
  // Parse collection_getter from SDNA to extract predicate and instanceFilter
1153
1156
  // Format 1 (findall): collection_getter(c, Base, "comments", List) :- findall(C, triple(Base, "todo://comment", C), List).
1154
1157
  // Format 2 (setof): collection_getter(c, Base, "messages", List) :- setof(Target, (triple(Base, "flux://entry_type", Target), ...), List).
@@ -1184,7 +1187,7 @@ export class PerspectiveProxy {
1184
1187
  }
1185
1188
  }
1186
1189
  if (predicate) {
1187
- collections.set(collName, { predicate, instanceFilter });
1190
+ collections.set(collName, { predicate, instanceFilter, condition });
1188
1191
  }
1189
1192
  }
1190
1193
  }
@@ -1260,6 +1263,7 @@ export class PerspectiveProxy {
1260
1263
  /**
1261
1264
  * Gets collection values using SurrealDB when Prolog fails.
1262
1265
  * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
1266
+ * Note: This is used by Subject.ts (legacy pattern). Ad4mModel.ts uses getModelMetadata() instead.
1263
1267
  */
1264
1268
  async getCollectionValuesViaSurreal(baseExpression, className, collectionName) {
1265
1269
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
@@ -1278,6 +1282,31 @@ export class PerspectiveProxy {
1278
1282
  return [];
1279
1283
  }
1280
1284
  let values = result.map(r => r.value).filter(v => v !== "" && v !== '');
1285
+ // Apply condition filtering if present
1286
+ if (collMeta.condition && values.length > 0) {
1287
+ try {
1288
+ const filteredValues = [];
1289
+ for (const value of values) {
1290
+ let condition = collMeta.condition
1291
+ .replace(/\$perspective/g, `'${this.uuid}'`)
1292
+ .replace(/\$base/g, `'${baseExpression}'`)
1293
+ .replace(/Target/g, `'${value.replace(/'/g, "\\'")}'`);
1294
+ // If condition starts with WHERE, wrap in array length check
1295
+ if (condition.trim().startsWith('WHERE')) {
1296
+ condition = `array::len(SELECT * FROM link ${condition}) > 0`;
1297
+ }
1298
+ const filterResult = await this.querySurrealDB(`RETURN ${condition}`);
1299
+ const isTrue = filterResult === true || (Array.isArray(filterResult) && filterResult.length > 0 && filterResult[0] === true);
1300
+ if (isTrue) {
1301
+ filteredValues.push(value);
1302
+ }
1303
+ }
1304
+ values = filteredValues;
1305
+ }
1306
+ catch (error) {
1307
+ console.warn(`Failed to apply condition filter for ${collectionName}:`, error);
1308
+ }
1309
+ }
1281
1310
  // Apply instance filter if present - batch-check all values at once
1282
1311
  if (collMeta.instanceFilter) {
1283
1312
  try {
@@ -1319,11 +1348,13 @@ export class PerspectiveProxy {
1319
1348
  if (triple.target) {
1320
1349
  // Flag: must match both predicate AND exact target value
1321
1350
  const escapedTarget = escapeSurrealString(triple.target);
1322
- checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}' GROUP BY in.uri`;
1351
+ // Note: Removed GROUP BY because it was causing SurrealDB to only return one result
1352
+ checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}'`;
1323
1353
  }
1324
1354
  else {
1325
1355
  // Property: just check predicate exists
1326
- checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}' GROUP BY in.uri`;
1356
+ // Note: Removed GROUP BY because it was causing SurrealDB to only return one result
1357
+ checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}'`;
1327
1358
  }
1328
1359
  const result = await this.querySurrealDB(checkQuery);
1329
1360
  validExpressionSets.push(new Set(result.map(r => r.uri)));
package/package.json CHANGED
@@ -57,7 +57,7 @@
57
57
  "react-dom": "*"
58
58
  },
59
59
  "patchedDependencies": {},
60
- "version": "0.11.2-dev.4",
60
+ "version": "0.11.2-dev.6",
61
61
  "scripts": {
62
62
  "build": "patch-package && tsc && pnpm run buildSchema && pnpm run bundle",
63
63
  "buildSchema": "node --es-module-specifier-resolution=node lib/src/buildSchema.js",
@@ -22,7 +22,7 @@ describe("Ad4mModel.getModelMetadata()", () => {
22
22
  @Optional({ through: "test://optional", writable: true })
23
23
  optional: string = "";
24
24
 
25
- @ReadOnly({ through: "test://readonly", getter: "custom_getter" })
25
+ @ReadOnly({ through: "test://readonly", prologGetter: "custom_getter" })
26
26
  readonly: string = "";
27
27
 
28
28
  @Flag({ through: "test://type", value: "test://flag" })
@@ -47,7 +47,7 @@ describe("Ad4mModel.getModelMetadata()", () => {
47
47
  // Verify "readonly" property
48
48
  expect(metadata.properties.readonly.predicate).toBe("test://readonly");
49
49
  expect(metadata.properties.readonly.writable).toBe(false);
50
- expect(metadata.properties.readonly.getter).toBe("custom_getter");
50
+ expect(metadata.properties.readonly.prologGetter).toBe("custom_getter");
51
51
 
52
52
  // Verify "type" property (flag)
53
53
  expect(metadata.properties.type.predicate).toBe("test://type");
@@ -114,18 +114,18 @@ describe("Ad4mModel.getModelMetadata()", () => {
114
114
  class CustomModel extends Ad4mModel {
115
115
  @Optional({
116
116
  through: "test://computed",
117
- getter: "triple(Base, 'test://value', V), Value is V * 2",
118
- setter: "Value is V / 2, Actions = [{action: 'setSingleTarget', source: 'this', predicate: 'test://value', target: Value}]"
117
+ prologGetter: "triple(Base, 'test://value', V), Value is V * 2",
118
+ prologSetter: "Value is V / 2, Actions = [{action: 'setSingleTarget', source: 'this', predicate: 'test://value', target: Value}]"
119
119
  })
120
120
  computed: number = 0;
121
121
  }
122
122
 
123
123
  const metadata = CustomModel.getModelMetadata();
124
124
 
125
- // Assert getter and setter contain the custom code
126
- expect(metadata.properties.computed.getter).toContain("triple(Base, 'test://value', V), Value is V * 2");
127
- expect(metadata.properties.computed.setter).toContain("Value is V / 2");
128
- expect(metadata.properties.computed.setter).toContain("setSingleTarget");
125
+ // Assert prologGetter and prologSetter contain the custom code
126
+ expect(metadata.properties.computed.prologGetter).toContain("triple(Base, 'test://value', V), Value is V * 2");
127
+ expect(metadata.properties.computed.prologSetter).toContain("Value is V / 2");
128
+ expect(metadata.properties.computed.prologSetter).toContain("setSingleTarget");
129
129
  });
130
130
 
131
131
  it("should handle collection with isInstance where clause", () => {
@@ -163,7 +163,7 @@ describe("Ad4mModel.getModelMetadata()", () => {
163
163
  @Optional({ through: "recipe://description" })
164
164
  description: string = "";
165
165
 
166
- @ReadOnly({ through: "recipe://rating", getter: "avg_rating(Base, Value)" })
166
+ @ReadOnly({ through: "recipe://rating", prologGetter: "avg_rating(Base, Value)" })
167
167
  rating: number = 0;
168
168
 
169
169
  @Collection({ through: "recipe://ingredient" })
@@ -194,7 +194,7 @@ describe("Ad4mModel.getModelMetadata()", () => {
194
194
  expect(metadata.properties.name.resolveLanguage).toBe("literal");
195
195
  expect(metadata.properties.description.predicate).toBe("recipe://description");
196
196
  expect(metadata.properties.rating.predicate).toBe("recipe://rating");
197
- expect(metadata.properties.rating.getter).toBe("avg_rating(Base, Value)");
197
+ expect(metadata.properties.rating.prologGetter).toBe("avg_rating(Base, Value)");
198
198
  expect(metadata.collections.ingredients.predicate).toBe("recipe://ingredient");
199
199
  expect(metadata.collections.steps.predicate).toBe("recipe://step");
200
200
  expect(metadata.collections.steps.local).toBe(true);