@coasys/ad4m 0.12.0-rc1-dev.3 → 0.12.0-rc1-dev.5

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.
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Shared SurrealQL compilation utilities.
3
+ *
4
+ * These functions are used by both the runtime query builder (`Ad4mModel`) and
5
+ * the compile-time SHACL generator (`decorators.ts`).
6
+ */
7
+ import type { WhereCondition, Where, ModelMetadata } from "./Ad4mModel";
8
+ /**
9
+ * Format a JavaScript value for embedding in a SurrealQL expression.
10
+ *
11
+ * - Strings are single-quoted with backslash / quote / newline escaping
12
+ * - Numbers and booleans are passed through as-is
13
+ * - Arrays are recursed
14
+ */
15
+ export declare function formatSurrealValue(value: any): string;
16
+ /**
17
+ * Compile a single Where condition for a property into a SurrealQL
18
+ * graph-traversal sub-expression.
19
+ *
20
+ * Operates on the **target node** — generates `count(->link[WHERE ...]) > 0`
21
+ * style checks that can be used inside a `[WHERE ...]` filter on nodes.
22
+ *
23
+ * @param predicate - The predicate URI for the property
24
+ * @param condition - The Where condition value
25
+ * @param opts - Optional settings (e.g. `resolveLanguage`)
26
+ * @returns A single SurrealQL condition string
27
+ */
28
+ export declare function buildWhereCondition(predicate: string, condition: WhereCondition, opts?: {
29
+ resolveLanguage?: string;
30
+ }): string;
31
+ /**
32
+ * Compile a full `Where` clause to an array of SurrealQL condition strings.
33
+ *
34
+ * When `metadata` is provided, property names are resolved to predicates
35
+ * using the model's property metadata. When `metadata` is `null`, property
36
+ * names are treated as raw predicate URIs.
37
+ *
38
+ * Only handles **regular properties** — special fields (`id`, `author`,
39
+ * `timestamp`) and relation fields are skipped (they are only relevant at
40
+ * runtime query time, not for compile-time getter generation).
41
+ */
42
+ export declare function compileWhereClause(where: Where, metadata: ModelMetadata | null): string[];
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Shared SurrealQL compilation utilities.
3
+ *
4
+ * These functions are used by both the runtime query builder (`Ad4mModel`) and
5
+ * the compile-time SHACL generator (`decorators.ts`).
6
+ */
7
+ import { escapeSurrealString } from "../utils";
8
+ /**
9
+ * Format a JavaScript value for embedding in a SurrealQL expression.
10
+ *
11
+ * - Strings are single-quoted with backslash / quote / newline escaping
12
+ * - Numbers and booleans are passed through as-is
13
+ * - Arrays are recursed
14
+ */
15
+ export function formatSurrealValue(value) {
16
+ if (typeof value === 'string') {
17
+ // Escape backslashes first, then single quotes and other special characters
18
+ const escaped = value
19
+ .replace(/\\/g, '\\\\') // Backslash -> \\
20
+ .replace(/'/g, "\\'") // Single quote -> \'
21
+ .replace(/"/g, '\\"') // Double quote -> \"
22
+ .replace(/\n/g, '\\n') // Newline -> \n
23
+ .replace(/\r/g, '\\r') // Carriage return -> \r
24
+ .replace(/\t/g, '\\t'); // Tab -> \t
25
+ return `'${escaped}'`;
26
+ }
27
+ else if (typeof value === 'number' || typeof value === 'boolean') {
28
+ return String(value);
29
+ }
30
+ else if (Array.isArray(value)) {
31
+ return `[${value.map(v => formatSurrealValue(v)).join(', ')}]`;
32
+ }
33
+ else {
34
+ return String(value);
35
+ }
36
+ }
37
+ /**
38
+ * Compile a single Where condition for a property into a SurrealQL
39
+ * graph-traversal sub-expression.
40
+ *
41
+ * Operates on the **target node** — generates `count(->link[WHERE ...]) > 0`
42
+ * style checks that can be used inside a `[WHERE ...]` filter on nodes.
43
+ *
44
+ * @param predicate - The predicate URI for the property
45
+ * @param condition - The Where condition value
46
+ * @param opts - Optional settings (e.g. `resolveLanguage`)
47
+ * @returns A single SurrealQL condition string
48
+ */
49
+ export function buildWhereCondition(predicate, condition, opts) {
50
+ const escapedPredicate = escapeSurrealString(predicate);
51
+ const targetField = opts?.resolveLanguage === 'literal'
52
+ ? 'fn::parse_literal(out.uri)'
53
+ : 'out.uri';
54
+ if (Array.isArray(condition)) {
55
+ // Array values → IN clause
56
+ const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
57
+ return `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} IN [${formattedValues}]]) > 0`;
58
+ }
59
+ else if (typeof condition === 'object' && condition !== null) {
60
+ // Operator object
61
+ const ops = condition;
62
+ const parts = [];
63
+ if (ops.not !== undefined) {
64
+ if (Array.isArray(ops.not)) {
65
+ const formattedValues = ops.not.map((v) => formatSurrealValue(v)).join(', ');
66
+ parts.push(`count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
67
+ }
68
+ else {
69
+ parts.push(`count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`);
70
+ }
71
+ }
72
+ // Comparison operators — ensure property exists (actual comparison
73
+ // may be post-filtered in JS at runtime, but the SurrealQL condition
74
+ // is valid for compile-time getter generation too).
75
+ const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
76
+ ops.lt !== undefined || ops.lte !== undefined ||
77
+ ops.between !== undefined || ops.contains !== undefined;
78
+ if (hasComparisonOps) {
79
+ parts.push(`count(->link[WHERE predicate = '${escapedPredicate}']) > 0`);
80
+ }
81
+ return parts.join(' AND ');
82
+ }
83
+ else {
84
+ // Simple equality
85
+ return `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} = ${formatSurrealValue(condition)}]) > 0`;
86
+ }
87
+ }
88
+ /**
89
+ * Compile a full `Where` clause to an array of SurrealQL condition strings.
90
+ *
91
+ * When `metadata` is provided, property names are resolved to predicates
92
+ * using the model's property metadata. When `metadata` is `null`, property
93
+ * names are treated as raw predicate URIs.
94
+ *
95
+ * Only handles **regular properties** — special fields (`id`, `author`,
96
+ * `timestamp`) and relation fields are skipped (they are only relevant at
97
+ * runtime query time, not for compile-time getter generation).
98
+ */
99
+ export function compileWhereClause(where, metadata) {
100
+ const conditions = [];
101
+ for (const [propertyName, condition] of Object.entries(where)) {
102
+ // Skip special fields that don't apply at compile time
103
+ if (['id', 'author', 'timestamp'].includes(propertyName))
104
+ continue;
105
+ let predicate;
106
+ let resolveLanguage;
107
+ if (metadata) {
108
+ const propMeta = metadata.properties[propertyName];
109
+ if (propMeta) {
110
+ predicate = propMeta.predicate;
111
+ resolveLanguage = propMeta.resolveLanguage;
112
+ }
113
+ else {
114
+ // Property not found in metadata — treat name as raw predicate URI
115
+ predicate = propertyName;
116
+ }
117
+ }
118
+ else {
119
+ // No metadata — treat name as raw predicate URI
120
+ predicate = propertyName;
121
+ }
122
+ const cond = buildWhereCondition(predicate, condition, { resolveLanguage });
123
+ if (cond) {
124
+ conditions.push(cond);
125
+ }
126
+ }
127
+ return conditions;
128
+ }
@@ -9,6 +9,18 @@ export interface AD4MAction {
9
9
  target: string;
10
10
  local?: boolean;
11
11
  }
12
+ /**
13
+ * A single structured conformance condition for relation filtering.
14
+ * DB-agnostic representation that can be translated to any query language.
15
+ */
16
+ export interface ConformanceCondition {
17
+ /** Type of check: 'flag' (predicate + value) or 'required' (predicate exists) */
18
+ type: 'flag' | 'required';
19
+ /** The predicate URI to check on the target node */
20
+ predicate: string;
21
+ /** For 'flag' conditions: the expected value */
22
+ value?: string;
23
+ }
12
24
  /**
13
25
  * SHACL Property Shape
14
26
  * Represents constraints on a single property path
@@ -46,6 +58,17 @@ export interface SHACLPropertyShape {
46
58
  adder?: AD4MAction[];
47
59
  /** AD4M-specific: Remover action for collection properties */
48
60
  remover?: AD4MAction[];
61
+ /** AD4M-specific: Pre-computed SurrealQL getter expression for reading this relation/property.
62
+ * For relations with a target model, this encodes conformance filtering
63
+ * so that Rust/MCP can execute the exact same query as the JS runtime. */
64
+ getter?: string;
65
+ /** AD4M-specific: Structured conformance conditions (DB-agnostic).
66
+ * Each condition describes a check on the target node (flag match or required property). */
67
+ conformanceConditions?: ConformanceCondition[];
68
+ /** sh:class — the target SHACL node shape URI that linked nodes must conform to.
69
+ * Set automatically when a relation has a `target` model. Enables typed construction
70
+ * on the Rust/MCP side by referencing the full target shape. */
71
+ class?: string;
49
72
  }
50
73
  /**
51
74
  * SHACL Node Shape
@@ -357,6 +357,27 @@ export class SHACLShape {
357
357
  target: `literal://string:${JSON.stringify(prop.remover)}`
358
358
  });
359
359
  }
360
+ if (prop.getter) {
361
+ links.push({
362
+ source: propShapeId,
363
+ predicate: "ad4m://getter",
364
+ target: `literal://string:${prop.getter}`
365
+ });
366
+ }
367
+ if (prop.conformanceConditions && prop.conformanceConditions.length > 0) {
368
+ links.push({
369
+ source: propShapeId,
370
+ predicate: "ad4m://conformanceConditions",
371
+ target: `literal://string:${JSON.stringify(prop.conformanceConditions)}`
372
+ });
373
+ }
374
+ if (prop.class) {
375
+ links.push({
376
+ source: propShapeId,
377
+ predicate: "sh://class",
378
+ target: prop.class
379
+ });
380
+ }
360
381
  }
361
382
  return links;
362
383
  }
@@ -510,6 +531,24 @@ export class SHACLShape {
510
531
  // Ignore parse errors
511
532
  }
512
533
  }
534
+ const getterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://getter");
535
+ if (getterLink) {
536
+ prop.getter = getterLink.target.replace('literal://string:', '');
537
+ }
538
+ const conditionsLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://conformanceConditions");
539
+ if (conditionsLink) {
540
+ try {
541
+ const jsonStr = conditionsLink.target.replace('literal://string:', '');
542
+ prop.conformanceConditions = JSON.parse(jsonStr);
543
+ }
544
+ catch (e) {
545
+ // Ignore parse errors
546
+ }
547
+ }
548
+ const classLink = links.find(l => l.source === propShapeId && l.predicate === "sh://class");
549
+ if (classLink) {
550
+ prop.class = classLink.target;
551
+ }
513
552
  shape.addProperty(prop);
514
553
  }
515
554
  return shape;
@@ -542,6 +581,9 @@ export class SHACLShape {
542
581
  setter: p.setter,
543
582
  adder: p.adder,
544
583
  remover: p.remover,
584
+ getter: p.getter,
585
+ conformance_conditions: p.conformanceConditions,
586
+ class: p.class,
545
587
  })),
546
588
  constructor_actions: this.constructor_actions,
547
589
  destructor_actions: this.destructor_actions,
@@ -572,6 +614,9 @@ export class SHACLShape {
572
614
  setter: p.setter,
573
615
  adder: p.adder,
574
616
  remover: p.remover,
617
+ getter: p.getter,
618
+ conformanceConditions: p.conformance_conditions,
619
+ class: p.class,
575
620
  });
576
621
  }
577
622
  if (json.constructor_actions) {
package/package.json CHANGED
@@ -58,7 +58,7 @@
58
58
  "ws": "8.13.0"
59
59
  },
60
60
  "patchedDependencies": {},
61
- "version": "0.12.0-rc1-dev.3",
61
+ "version": "0.12.0-rc1-dev.5",
62
62
  "scripts": {
63
63
  "build": "patch-package && tsc && pnpm run buildSchema && pnpm run bundle",
64
64
  "buildSchema": "tsx lib/src/buildSchema.js",
@@ -2,9 +2,10 @@ import { Literal } from "../Literal";
2
2
  import { Link } from "../links/Links";
3
3
  import { LinkQuery } from "../perspectives/LinkQuery";
4
4
  import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
5
- import { makeRandomId, PropertyOptions, Model, getPropertiesMetadata, getRelationsMetadata, setPropertyRegistryEntry, setRelationRegistryEntry, PropertyMetadataEntry, RelationMetadataEntry } from "./decorators";
5
+ import { makeRandomId, PropertyOptions, Model, getPropertiesMetadata, getRelationsMetadata, setPropertyRegistryEntry, setRelationRegistryEntry, PropertyMetadataEntry, RelationMetadataEntry, buildConformanceFilter } from "./decorators";
6
6
  import { singularToPlural, pluralToSingular, propertyNameToSetterName, relationToAdderName, relationToRemoverName, relationToSetterName } from "./util";
7
7
  import { escapeSurrealString } from "../utils";
8
+ import { formatSurrealValue as _formatSurrealValue, compileWhereClause } from "./surreal-utils";
8
9
 
9
10
  // JSON Schema type definitions
10
11
  interface JSONSchemaProperty {
@@ -46,7 +47,7 @@ interface JSONSchemaToModelOptions {
46
47
  }
47
48
 
48
49
  type ValueTuple = [name: string, value: any, resolve?: boolean];
49
- type WhereOps = {
50
+ export type WhereOps = {
50
51
  not: string | number | boolean | string[] | number[];
51
52
  between: [number, number];
52
53
  lt: number; // less than
@@ -55,8 +56,8 @@ type WhereOps = {
55
56
  gte: number; // greater than or equal to
56
57
  contains: string | number; // substring/element check
57
58
  };
58
- type WhereCondition = string | number | boolean | string[] | number[] | { [K in keyof WhereOps]?: WhereOps[K] };
59
- type Where = { [propertyName: string]: WhereCondition };
59
+ export type WhereCondition = string | number | boolean | string[] | number[] | { [K in keyof WhereOps]?: WhereOps[K] };
60
+ export type Where = { [propertyName: string]: WhereCondition };
60
61
  type Order = { [propertyName: string]: "ASC" | "DESC" };
61
62
 
62
63
  /**
@@ -175,6 +176,15 @@ export interface RelationMetadata {
175
176
  local?: boolean;
176
177
  /** Link direction: 'forward' for HasMany/HasOne, 'reverse' for BelongsToMany/BelongsToOne */
177
178
  direction?: 'forward' | 'reverse';
179
+ /** Target model class thunk for hydration and type filtering */
180
+ target?: () => any;
181
+ /**
182
+ * Whether to auto-generate a conformance filter when `target` is set.
183
+ * Defaults to `true` — set to `false` to opt out of DB-level type filtering.
184
+ */
185
+ filter?: boolean;
186
+ /** Where clause for relation filtering (query DSL) */
187
+ where?: Where;
178
188
  }
179
189
 
180
190
 
@@ -660,6 +670,9 @@ export class Ad4mModel {
660
670
  ...(options.local !== undefined && { local: options.local }),
661
671
  ...(options.getter !== undefined && { getter: options.getter }),
662
672
  direction: (options.kind === 'belongsToMany' || options.kind === 'belongsToOne') ? 'reverse' : 'forward',
673
+ ...(options.target !== undefined && { target: options.target }),
674
+ ...(options.filter !== undefined && { filter: options.filter }),
675
+ ...(options.where !== undefined && { where: options.where }),
663
676
  };
664
677
  }
665
678
 
@@ -971,10 +984,29 @@ export class Ad4mModel {
971
984
  }
972
985
 
973
986
  const predToRelation = new Map<string, [string, RelationMetadata]>();
987
+
988
+ // Two-pass approach: first add all non-getter, non-target-filtered relations,
989
+ // then try to add target+filter relations only if their predicate isn't
990
+ // already claimed. This prevents predicate collisions (e.g. entries +
991
+ // messages sharing the same predicate) while still populating unique-
992
+ // predicate relations normally via link hydration.
993
+ const deferredTargetRelations: [string, RelationMetadata][] = [];
974
994
  for (const [relName, relMeta] of Object.entries(metadata.relations)) {
975
- if (relMeta.getter) continue;
995
+ if (relMeta.getter) continue; // Handled via explicit custom getter evaluation
996
+ if (relMeta.target && relMeta.filter !== false) {
997
+ deferredTargetRelations.push([relName, relMeta]);
998
+ continue;
999
+ }
976
1000
  predToRelation.set(relMeta.predicate, [relName, relMeta]);
977
1001
  }
1002
+ // Second pass: add deferred target+filter relations only if their predicate
1003
+ // is not already claimed by a base relation. When a collision exists, the
1004
+ // conformance getter will handle the filtered view instead.
1005
+ for (const [relName, relMeta] of deferredTargetRelations) {
1006
+ if (!predToRelation.has(relMeta.predicate)) {
1007
+ predToRelation.set(relMeta.predicate, [relName, relMeta]);
1008
+ }
1009
+ }
978
1010
 
979
1011
  // Per-property accumulator: track all matching targets so we can pick the last (latest-wins)
980
1012
  const propertyLatest = new Map<string, { target: string; timestamp?: string | number }>();
@@ -1333,7 +1365,10 @@ export class Ad4mModel {
1333
1365
  }
1334
1366
 
1335
1367
  // Evaluate SurrealQL getters
1336
- await ctor.evaluateCustomGettersForInstance(this, this._perspective, metadata);
1368
+ const getterOpts = opts?.properties || opts?.include
1369
+ ? { requestedProperties: opts?.properties, include: opts?.include }
1370
+ : undefined;
1371
+ await ctor.evaluateCustomGettersForInstance(this, this._perspective, metadata, getterOpts);
1337
1372
 
1338
1373
  // Eager-load relations if requested
1339
1374
  if (opts?.include) {
@@ -1378,19 +1413,59 @@ export class Ad4mModel {
1378
1413
  return fullQuery;
1379
1414
  }
1380
1415
 
1416
+ /**
1417
+ * Builds a SurrealQL conformance getter for a relation whose `target` model
1418
+ * is known but no explicit `getter` string was supplied.
1419
+ *
1420
+ * The generated getter traverses outgoing links matching the relation's
1421
+ * predicate and then filters the target nodes to only those that conform to
1422
+ * the target model's shape (required properties / flags).
1423
+ *
1424
+ * Delegates to the shared `buildConformanceFilter()` utility in decorators.ts
1425
+ * so the same logic is used at shape-definition time and at query time.
1426
+ *
1427
+ * @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
1428
+ * @param targetClass - The target model class (result of calling the `target()` thunk)
1429
+ * @returns A SurrealQL expression string, or `undefined` if no conformance
1430
+ * conditions could be derived from the target model.
1431
+ * @private
1432
+ */
1433
+ private static buildConformanceGetter(
1434
+ relationPredicate: string,
1435
+ targetClass: any
1436
+ ): string | undefined {
1437
+ const filter = buildConformanceFilter(relationPredicate, targetClass);
1438
+ if (!filter) {
1439
+ const targetName = targetClass?.prototype?.className || targetClass?.name || 'unknown';
1440
+ console.warn(`[Ad4mModel] buildConformanceGetter: no conditions found for target "${targetName}".`);
1441
+ return undefined;
1442
+ }
1443
+ return filter.getter;
1444
+ }
1445
+
1381
1446
  /**
1382
1447
  * Evaluates custom SurrealQL getters for properties and relations on a specific instance.
1448
+ *
1449
+ * For relations that declare a `target` but no explicit `getter`, a conformance
1450
+ * getter is auto-generated from the target model's metadata (unless `filter: false`).
1383
1451
  * @private
1384
1452
  */
1385
1453
  private static async evaluateCustomGettersForInstance(
1386
1454
  instance: any,
1387
1455
  perspective: PerspectiveProxy,
1388
- metadata: any
1456
+ metadata: any,
1457
+ options?: { requestedProperties?: string[]; include?: Record<string, any> }
1389
1458
  ) {
1390
1459
  const safeBaseExpression = this.formatSurrealValue(instance.id);
1391
1460
 
1461
+ // Build projection filter — when requestedProperties is active, only
1462
+ // evaluate getters for fields that are requested (or included).
1463
+ const projectionActive = options?.requestedProperties && options.requestedProperties.length > 0;
1464
+ const projectionSet = projectionActive ? new Set(options!.requestedProperties) : null;
1465
+
1392
1466
  // Evaluate property getters
1393
1467
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
1468
+ if (projectionSet && !projectionSet.has(propName)) continue;
1394
1469
  if ((propMeta as any).getter) {
1395
1470
  try {
1396
1471
  // Replace 'Base' placeholder with actual base expression
@@ -1408,16 +1483,56 @@ export class Ad4mModel {
1408
1483
  }
1409
1484
  }
1410
1485
 
1411
- // Evaluate relation getters
1486
+ // Evaluate relation getters (explicit or auto-generated from target)
1412
1487
  for (const [relName, relMeta] of Object.entries(metadata.relations)) {
1413
- if ((relMeta as any).getter) {
1488
+ // Skip relations excluded by property projection (unless in include map)
1489
+ if (projectionSet && !projectionSet.has(relName) && !(options?.include && relName in options.include)) continue;
1490
+ const meta = relMeta as RelationMetadata;
1491
+
1492
+ // Determine the getter to execute:
1493
+ // 1. Explicit `getter` always wins
1494
+ // 2. `where` clause → compile DSL to SurrealQL getter
1495
+ // 3. If `target` is set and `filter !== false`, auto-generate from target metadata
1496
+ // BUT skip auto-generation for reverse relations (belongsToMany / belongsToOne)
1497
+ // because buildConformanceGetter traverses outgoing links (->link) which is
1498
+ // wrong for reverse relations. Their values are already populated by the
1499
+ // reverse link lookup in instancesFromSurrealResult / getData.
1500
+ let getter = meta.getter;
1501
+ if (!getter && meta.where && meta.direction !== 'reverse') {
1502
+ try {
1503
+ const TargetClass = meta.target?.();
1504
+ const targetMetadata = TargetClass
1505
+ ? (TargetClass as any).getModelMetadata?.() ?? null
1506
+ : null;
1507
+ const conditions = compileWhereClause(meta.where, targetMetadata);
1508
+ if (conditions.length > 0) {
1509
+ const escapedPred = escapeSurrealString(meta.predicate);
1510
+ getter = `(->link[WHERE predicate = '${escapedPred}'].out[WHERE ${conditions.join(' AND ')}].uri)`;
1511
+ }
1512
+ } catch (e) {
1513
+ // Target metadata may not be available yet
1514
+ }
1515
+ }
1516
+ if (!getter && meta.target && meta.filter !== false && meta.direction !== 'reverse') {
1517
+ try {
1518
+ const TargetClass = meta.target();
1519
+ getter = this.buildConformanceGetter(meta.predicate, TargetClass);
1520
+ if (!getter) {
1521
+ console.warn(`[Ad4mModel] buildConformanceGetter returned undefined for relation "${relName}" (predicate: "${meta.predicate}")`);
1522
+ }
1523
+ } catch (e) {
1524
+ console.warn(`[Ad4mModel] auto-generation failed for relation "${relName}":`, e);
1525
+ }
1526
+ }
1527
+
1528
+ if (getter) {
1414
1529
  try {
1415
1530
  // Replace 'Base' placeholder with actual base expression
1416
- const query = (relMeta as any).getter.replace(/Base/g, safeBaseExpression);
1531
+ const query = getter.replace(/Base/g, safeBaseExpression);
1532
+ const fullQuery = `SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`;
1417
1533
  // Query from node table to have graph traversal context
1418
- const result = await perspective.querySurrealDB(
1419
- `SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`
1420
- );
1534
+ const result = await perspective.querySurrealDB(fullQuery);
1535
+
1421
1536
  if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null) {
1422
1537
  // Filter out 'None' from relation results
1423
1538
  const value = result[0].value;
@@ -2243,23 +2358,7 @@ FETCH links
2243
2358
  * @private
2244
2359
  */
2245
2360
  private static formatSurrealValue(value: any): string {
2246
- if (typeof value === 'string') {
2247
- // Escape backslashes first, then single quotes and other special characters
2248
- const escaped = value
2249
- .replace(/\\/g, '\\\\') // Backslash -> \\
2250
- .replace(/'/g, "\\'") // Single quote -> \'
2251
- .replace(/"/g, '\\"') // Double quote -> \"
2252
- .replace(/\n/g, '\\n') // Newline -> \n
2253
- .replace(/\r/g, '\\r') // Carriage return -> \r
2254
- .replace(/\t/g, '\\t'); // Tab -> \t
2255
- return `'${escaped}'`;
2256
- } else if (typeof value === 'number' || typeof value === 'boolean') {
2257
- return String(value);
2258
- } else if (Array.isArray(value)) {
2259
- return `[${value.map(v => this.formatSurrealValue(v)).join(', ')}]`;
2260
- } else {
2261
- return String(value);
2262
- }
2361
+ return _formatSurrealValue(value);
2263
2362
  }
2264
2363
 
2265
2364
  public static async instancesFromPrologResult<T extends Ad4mModel>(
@@ -2417,8 +2516,11 @@ FETCH links
2417
2516
  }
2418
2517
 
2419
2518
  // Evaluate custom getters for all instances (single pass)
2519
+ const getterOpts = requestedProperties.length > 0 || query.include
2520
+ ? { requestedProperties, include: query.include }
2521
+ : undefined;
2420
2522
  for (const instance of instances) {
2421
- await this.evaluateCustomGettersForInstance(instance, perspective, metadata);
2523
+ await this.evaluateCustomGettersForInstance(instance, perspective, metadata, getterOpts);
2422
2524
  }
2423
2525
 
2424
2526
  // Filter by where conditions that couldn't be filtered in SQL
@@ -2996,11 +3098,26 @@ FETCH links
2996
3098
  (p) => p.required || p.flag || p.initial !== undefined
2997
3099
  );
2998
3100
 
3101
+ // Track properties that have resolveLanguage (non-literal) so they can be
3102
+ // set via setProperty after createSubject (which doesn't resolve languages).
3103
+ const deferredResolveLanguageProps: string[] = [];
3104
+
2999
3105
  if (hasConstructor) {
3000
3106
  // First filter out the properties that are not relations (arrays)
3001
3107
  const initialValues = {};
3002
3108
  for (const [key, value] of Object.entries(this)) {
3003
3109
  if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {
3110
+ // Check if this property requires language resolution (e.g. file storage).
3111
+ // If so, resolve the expression *before* passing to createSubject so
3112
+ // the constructor receives a valid URI instead of raw data.
3113
+ const propMeta = metadata.properties[key];
3114
+ if (propMeta?.resolveLanguage && propMeta.resolveLanguage !== 'literal' && typeof value === 'object') {
3115
+ // Defer these properties — they need createExpression which may
3116
+ // fail inside a batch context on some languages. We'll set them
3117
+ // via setProperty after createSubject.
3118
+ deferredResolveLanguageProps.push(key);
3119
+ continue;
3120
+ }
3004
3121
  initialValues[key] = value;
3005
3122
  }
3006
3123
  }
@@ -3022,6 +3139,16 @@ FETCH links
3022
3139
  // property writing so that scalar values are persisted as links.
3023
3140
  await this.innerUpdate(!hasConstructor, batchId)
3024
3141
 
3142
+ // Now handle any deferred resolveLanguage properties that were excluded
3143
+ // from initialValues. setProperty will call createExpression to upload
3144
+ // the data to the appropriate language and store the resulting URI.
3145
+ for (const key of deferredResolveLanguageProps) {
3146
+ const value = (this as any)[key];
3147
+ if (value !== undefined && value !== null) {
3148
+ await this.setProperty(key, value, batchId);
3149
+ }
3150
+ }
3151
+
3025
3152
  // If we got a batchId passed in, we let the caller decide when to commit.
3026
3153
  // We can't call getData() since the instance won't exist in the perspective
3027
3154
  // until the batch is committed.
@@ -3079,6 +3206,24 @@ FETCH links
3079
3206
  // Skip unchanged fields when a snapshot is available
3080
3207
  if (dirty && !dirty.has(key)) continue;
3081
3208
 
3209
+ // Skip read-only computed relations — explicit getters never write links.
3210
+ // For target+filter relations, skip only when another relation on this
3211
+ // model claims the same predicate (i.e., this is a filtered *view* of a
3212
+ // base relation and writing would collide).
3213
+ const relMeta = metadata.relations[key];
3214
+ if (relMeta) {
3215
+ if (relMeta.getter) continue;
3216
+ if (relMeta.target && relMeta.filter !== false) {
3217
+ // Check for predicate collision with a sibling relation
3218
+ const hasCollision = Object.entries(metadata.relations).some(
3219
+ ([otherName, otherMeta]) =>
3220
+ otherName !== key &&
3221
+ (otherMeta as RelationMetadata).predicate === relMeta.predicate
3222
+ );
3223
+ if (hasCollision) continue;
3224
+ }
3225
+ }
3226
+
3082
3227
  if (value !== undefined && value !== null) {
3083
3228
  if (value?.action) {
3084
3229
  switch (value.action) {
@@ -3177,11 +3322,6 @@ FETCH links
3177
3322
  * ```
3178
3323
  */
3179
3324
  async delete(batchId?: string) {
3180
- // Check if the model has a destructor (required properties, flags, or
3181
- // properties with initial values). Models whose properties are all
3182
- // optional, have no @Flag, and have no initial values produce an empty
3183
- // SHACL destructor, so calling removeSubject would fail. In that case
3184
- // we skip the destructor and just remove all outgoing links directly.
3185
3325
  const metadata = (this.constructor as typeof Ad4mModel).getModelMetadata();
3186
3326
  const hasDestructor = Object.values(metadata.properties).some(
3187
3327
  (p) => p.required || p.flag || p.initial !== undefined
@@ -3191,18 +3331,40 @@ FETCH links
3191
3331
  // Remove the subject itself (destructor actions)
3192
3332
  await this._perspective.removeSubject(this, this._baseExpression, batchId);
3193
3333
  } else {
3194
- // No destructor — manually remove all outgoing links from this node
3334
+ // No destructor (all-optional model).
3335
+ // SAFETY: We must NOT remove all outgoing links because another model
3336
+ // class may be instantiated on the same base expression. Removing
3337
+ // everything would silently destroy that other instance's data — and
3338
+ // if that instance has a destructor, it can no longer be called
3339
+ // cleanly, leaving link debris.
3340
+ //
3341
+ // Instead we only remove outgoing links whose predicate is declared
3342
+ // by THIS model's schema (properties + relations).
3195
3343
  try {
3344
+ const knownPredicates = new Set<string>();
3345
+ for (const p of Object.values(metadata.properties)) {
3346
+ if (p.predicate) knownPredicates.add(p.predicate);
3347
+ }
3348
+ for (const r of Object.values(metadata.relations)) {
3349
+ if (r.predicate) knownPredicates.add(r.predicate);
3350
+ }
3351
+
3196
3352
  const outgoingLinks = await this._perspective.get(new LinkQuery({ source: this._baseExpression }));
3197
- if (outgoingLinks.length > 0) {
3198
- await this._perspective.removeLinks(outgoingLinks, batchId);
3353
+ const ownLinks = outgoingLinks.filter(
3354
+ (link) => link.data.predicate && knownPredicates.has(link.data.predicate)
3355
+ );
3356
+ if (ownLinks.length > 0) {
3357
+ await this._perspective.removeLinks(ownLinks, batchId);
3199
3358
  }
3200
3359
  } catch (e) {
3201
3360
  console.warn(`delete(): failed to remove outgoing links for ${this._baseExpression}:`, e);
3202
3361
  }
3203
3362
  }
3204
3363
 
3205
- // Clean up incoming links — remove any links that point **to** this instance
3364
+ // Clean up incoming links — remove any links that point **to** this instance.
3365
+ // Unlike outgoing links (scoped above), incoming links originate from OTHER
3366
+ // nodes. Removing them doesn't damage sibling models on this node; it
3367
+ // prevents dangling references elsewhere (e.g. a parent's has_child link).
3206
3368
  try {
3207
3369
  const incomingLinks = await this._perspective.get(new LinkQuery({ target: this._baseExpression }));
3208
3370
  if (incomingLinks.length > 0) {