@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.
@@ -40,7 +40,7 @@ interface JSONSchemaToModelOptions {
40
40
  propertyOptions?: Record<string, Partial<PropertyOptions>>;
41
41
  }
42
42
  type ValueTuple = [name: string, value: any, resolve?: boolean];
43
- type WhereOps = {
43
+ export type WhereOps = {
44
44
  not: string | number | boolean | string[] | number[];
45
45
  between: [number, number];
46
46
  lt: number;
@@ -49,10 +49,10 @@ type WhereOps = {
49
49
  gte: number;
50
50
  contains: string | number;
51
51
  };
52
- type WhereCondition = string | number | boolean | string[] | number[] | {
52
+ export type WhereCondition = string | number | boolean | string[] | number[] | {
53
53
  [K in keyof WhereOps]?: WhereOps[K];
54
54
  };
55
- type Where = {
55
+ export type Where = {
56
56
  [propertyName: string]: WhereCondition;
57
57
  };
58
58
  type Order = {
@@ -184,6 +184,15 @@ export interface RelationMetadata {
184
184
  local?: boolean;
185
185
  /** Link direction: 'forward' for HasMany/HasOne, 'reverse' for BelongsToMany/BelongsToOne */
186
186
  direction?: 'forward' | 'reverse';
187
+ /** Target model class thunk for hydration and type filtering */
188
+ target?: () => any;
189
+ /**
190
+ * Whether to auto-generate a conformance filter when `target` is set.
191
+ * Defaults to `true` — set to `false` to opt out of DB-level type filtering.
192
+ */
193
+ filter?: boolean;
194
+ /** Where clause for relation filtering (query DSL) */
195
+ where?: Where;
187
196
  }
188
197
  /**
189
198
  * Complete model metadata extracted from decorators.
@@ -514,8 +523,29 @@ export declare class Ad4mModel {
514
523
  changedFields(): string[];
515
524
  private getData;
516
525
  static queryToProlog(perspective: PerspectiveProxy, query: Query, modelClassName?: string | null): Promise<string>;
526
+ /**
527
+ * Builds a SurrealQL conformance getter for a relation whose `target` model
528
+ * is known but no explicit `getter` string was supplied.
529
+ *
530
+ * The generated getter traverses outgoing links matching the relation's
531
+ * predicate and then filters the target nodes to only those that conform to
532
+ * the target model's shape (required properties / flags).
533
+ *
534
+ * Delegates to the shared `buildConformanceFilter()` utility in decorators.ts
535
+ * so the same logic is used at shape-definition time and at query time.
536
+ *
537
+ * @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
538
+ * @param targetClass - The target model class (result of calling the `target()` thunk)
539
+ * @returns A SurrealQL expression string, or `undefined` if no conformance
540
+ * conditions could be derived from the target model.
541
+ * @private
542
+ */
543
+ private static buildConformanceGetter;
517
544
  /**
518
545
  * Evaluates custom SurrealQL getters for properties and relations on a specific instance.
546
+ *
547
+ * For relations that declare a `target` but no explicit `getter`, a conformance
548
+ * getter is auto-generated from the target model's metadata (unless `filter: false`).
519
549
  * @private
520
550
  */
521
551
  private static evaluateCustomGettersForInstance;
@@ -1,9 +1,10 @@
1
1
  import { Literal } from "../Literal";
2
2
  import { Link } from "../links/Links";
3
3
  import { LinkQuery } from "../perspectives/LinkQuery";
4
- import { makeRandomId, Model, getPropertiesMetadata, getRelationsMetadata, setPropertyRegistryEntry, setRelationRegistryEntry } from "./decorators";
4
+ import { makeRandomId, Model, getPropertiesMetadata, getRelationsMetadata, setPropertyRegistryEntry, setRelationRegistryEntry, buildConformanceFilter } from "./decorators";
5
5
  import { propertyNameToSetterName } from "./util";
6
6
  import { escapeSurrealString } from "../utils";
7
+ import { formatSurrealValue as _formatSurrealValue, compileWhereClause } from "./surreal-utils";
7
8
  function capitalize(word) {
8
9
  return word.charAt(0).toUpperCase() + word.slice(1);
9
10
  }
@@ -429,6 +430,9 @@ export class Ad4mModel {
429
430
  ...(options.local !== undefined && { local: options.local }),
430
431
  ...(options.getter !== undefined && { getter: options.getter }),
431
432
  direction: (options.kind === 'belongsToMany' || options.kind === 'belongsToOne') ? 'reverse' : 'forward',
433
+ ...(options.target !== undefined && { target: options.target }),
434
+ ...(options.filter !== undefined && { filter: options.filter }),
435
+ ...(options.where !== undefined && { where: options.where }),
432
436
  };
433
437
  }
434
438
  // Fallback: If both structures are empty but a JSON schema is attached, derive from it
@@ -693,11 +697,29 @@ export class Ad4mModel {
693
697
  predToProperty.set(propMeta.predicate, [propName, propMeta]);
694
698
  }
695
699
  const predToRelation = new Map();
700
+ // Two-pass approach: first add all non-getter, non-target-filtered relations,
701
+ // then try to add target+filter relations only if their predicate isn't
702
+ // already claimed. This prevents predicate collisions (e.g. entries +
703
+ // messages sharing the same predicate) while still populating unique-
704
+ // predicate relations normally via link hydration.
705
+ const deferredTargetRelations = [];
696
706
  for (const [relName, relMeta] of Object.entries(metadata.relations)) {
697
707
  if (relMeta.getter)
708
+ continue; // Handled via explicit custom getter evaluation
709
+ if (relMeta.target && relMeta.filter !== false) {
710
+ deferredTargetRelations.push([relName, relMeta]);
698
711
  continue;
712
+ }
699
713
  predToRelation.set(relMeta.predicate, [relName, relMeta]);
700
714
  }
715
+ // Second pass: add deferred target+filter relations only if their predicate
716
+ // is not already claimed by a base relation. When a collision exists, the
717
+ // conformance getter will handle the filtered view instead.
718
+ for (const [relName, relMeta] of deferredTargetRelations) {
719
+ if (!predToRelation.has(relMeta.predicate)) {
720
+ predToRelation.set(relMeta.predicate, [relName, relMeta]);
721
+ }
722
+ }
701
723
  // Per-property accumulator: track all matching targets so we can pick the last (latest-wins)
702
724
  const propertyLatest = new Map();
703
725
  // Per-relation accumulator: ordered targets with metadata for sorting
@@ -1016,7 +1038,10 @@ export class Ad4mModel {
1016
1038
  }
1017
1039
  }
1018
1040
  // Evaluate SurrealQL getters
1019
- await ctor.evaluateCustomGettersForInstance(this, this._perspective, metadata);
1041
+ const getterOpts = opts?.properties || opts?.include
1042
+ ? { requestedProperties: opts?.properties, include: opts?.include }
1043
+ : undefined;
1044
+ await ctor.evaluateCustomGettersForInstance(this, this._perspective, metadata, getterOpts);
1020
1045
  // Eager-load relations if requested
1021
1046
  if (opts?.include) {
1022
1047
  await ctor.hydrateRelations([this], this._perspective, opts.include);
@@ -1053,14 +1078,49 @@ export class Ad4mModel {
1053
1078
  `;
1054
1079
  return fullQuery;
1055
1080
  }
1081
+ /**
1082
+ * Builds a SurrealQL conformance getter for a relation whose `target` model
1083
+ * is known but no explicit `getter` string was supplied.
1084
+ *
1085
+ * The generated getter traverses outgoing links matching the relation's
1086
+ * predicate and then filters the target nodes to only those that conform to
1087
+ * the target model's shape (required properties / flags).
1088
+ *
1089
+ * Delegates to the shared `buildConformanceFilter()` utility in decorators.ts
1090
+ * so the same logic is used at shape-definition time and at query time.
1091
+ *
1092
+ * @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
1093
+ * @param targetClass - The target model class (result of calling the `target()` thunk)
1094
+ * @returns A SurrealQL expression string, or `undefined` if no conformance
1095
+ * conditions could be derived from the target model.
1096
+ * @private
1097
+ */
1098
+ static buildConformanceGetter(relationPredicate, targetClass) {
1099
+ const filter = buildConformanceFilter(relationPredicate, targetClass);
1100
+ if (!filter) {
1101
+ const targetName = targetClass?.prototype?.className || targetClass?.name || 'unknown';
1102
+ console.warn(`[Ad4mModel] buildConformanceGetter: no conditions found for target "${targetName}".`);
1103
+ return undefined;
1104
+ }
1105
+ return filter.getter;
1106
+ }
1056
1107
  /**
1057
1108
  * Evaluates custom SurrealQL getters for properties and relations on a specific instance.
1109
+ *
1110
+ * For relations that declare a `target` but no explicit `getter`, a conformance
1111
+ * getter is auto-generated from the target model's metadata (unless `filter: false`).
1058
1112
  * @private
1059
1113
  */
1060
- static async evaluateCustomGettersForInstance(instance, perspective, metadata) {
1114
+ static async evaluateCustomGettersForInstance(instance, perspective, metadata, options) {
1061
1115
  const safeBaseExpression = this.formatSurrealValue(instance.id);
1116
+ // Build projection filter — when requestedProperties is active, only
1117
+ // evaluate getters for fields that are requested (or included).
1118
+ const projectionActive = options?.requestedProperties && options.requestedProperties.length > 0;
1119
+ const projectionSet = projectionActive ? new Set(options.requestedProperties) : null;
1062
1120
  // Evaluate property getters
1063
1121
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
1122
+ if (projectionSet && !projectionSet.has(propName))
1123
+ continue;
1064
1124
  if (propMeta.getter) {
1065
1125
  try {
1066
1126
  // Replace 'Base' placeholder with actual base expression
@@ -1076,14 +1136,56 @@ export class Ad4mModel {
1076
1136
  }
1077
1137
  }
1078
1138
  }
1079
- // Evaluate relation getters
1139
+ // Evaluate relation getters (explicit or auto-generated from target)
1080
1140
  for (const [relName, relMeta] of Object.entries(metadata.relations)) {
1081
- if (relMeta.getter) {
1141
+ // Skip relations excluded by property projection (unless in include map)
1142
+ if (projectionSet && !projectionSet.has(relName) && !(options?.include && relName in options.include))
1143
+ continue;
1144
+ const meta = relMeta;
1145
+ // Determine the getter to execute:
1146
+ // 1. Explicit `getter` always wins
1147
+ // 2. `where` clause → compile DSL to SurrealQL getter
1148
+ // 3. If `target` is set and `filter !== false`, auto-generate from target metadata
1149
+ // BUT skip auto-generation for reverse relations (belongsToMany / belongsToOne)
1150
+ // because buildConformanceGetter traverses outgoing links (->link) which is
1151
+ // wrong for reverse relations. Their values are already populated by the
1152
+ // reverse link lookup in instancesFromSurrealResult / getData.
1153
+ let getter = meta.getter;
1154
+ if (!getter && meta.where && meta.direction !== 'reverse') {
1155
+ try {
1156
+ const TargetClass = meta.target?.();
1157
+ const targetMetadata = TargetClass
1158
+ ? TargetClass.getModelMetadata?.() ?? null
1159
+ : null;
1160
+ const conditions = compileWhereClause(meta.where, targetMetadata);
1161
+ if (conditions.length > 0) {
1162
+ const escapedPred = escapeSurrealString(meta.predicate);
1163
+ getter = `(->link[WHERE predicate = '${escapedPred}'].out[WHERE ${conditions.join(' AND ')}].uri)`;
1164
+ }
1165
+ }
1166
+ catch (e) {
1167
+ // Target metadata may not be available yet
1168
+ }
1169
+ }
1170
+ if (!getter && meta.target && meta.filter !== false && meta.direction !== 'reverse') {
1171
+ try {
1172
+ const TargetClass = meta.target();
1173
+ getter = this.buildConformanceGetter(meta.predicate, TargetClass);
1174
+ if (!getter) {
1175
+ console.warn(`[Ad4mModel] buildConformanceGetter returned undefined for relation "${relName}" (predicate: "${meta.predicate}")`);
1176
+ }
1177
+ }
1178
+ catch (e) {
1179
+ console.warn(`[Ad4mModel] auto-generation failed for relation "${relName}":`, e);
1180
+ }
1181
+ }
1182
+ if (getter) {
1082
1183
  try {
1083
1184
  // Replace 'Base' placeholder with actual base expression
1084
- const query = relMeta.getter.replace(/Base/g, safeBaseExpression);
1185
+ const query = getter.replace(/Base/g, safeBaseExpression);
1186
+ const fullQuery = `SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`;
1085
1187
  // Query from node table to have graph traversal context
1086
- const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
1188
+ const result = await perspective.querySurrealDB(fullQuery);
1087
1189
  if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null) {
1088
1190
  // Filter out 'None' from relation results
1089
1191
  const value = result[0].value;
@@ -1863,26 +1965,7 @@ FETCH links
1863
1965
  * @private
1864
1966
  */
1865
1967
  static formatSurrealValue(value) {
1866
- if (typeof value === 'string') {
1867
- // Escape backslashes first, then single quotes and other special characters
1868
- const escaped = value
1869
- .replace(/\\/g, '\\\\') // Backslash -> \\
1870
- .replace(/'/g, "\\'") // Single quote -> \'
1871
- .replace(/"/g, '\\"') // Double quote -> \"
1872
- .replace(/\n/g, '\\n') // Newline -> \n
1873
- .replace(/\r/g, '\\r') // Carriage return -> \r
1874
- .replace(/\t/g, '\\t'); // Tab -> \t
1875
- return `'${escaped}'`;
1876
- }
1877
- else if (typeof value === 'number' || typeof value === 'boolean') {
1878
- return String(value);
1879
- }
1880
- else if (Array.isArray(value)) {
1881
- return `[${value.map(v => this.formatSurrealValue(v)).join(', ')}]`;
1882
- }
1883
- else {
1884
- return String(value);
1885
- }
1968
+ return _formatSurrealValue(value);
1886
1969
  }
1887
1970
  static async instancesFromPrologResult(perspective, query, result) {
1888
1971
  if (!result?.[0]?.AllInstances)
@@ -2010,8 +2093,11 @@ FETCH links
2010
2093
  }));
2011
2094
  }
2012
2095
  // Evaluate custom getters for all instances (single pass)
2096
+ const getterOpts = requestedProperties.length > 0 || query.include
2097
+ ? { requestedProperties, include: query.include }
2098
+ : undefined;
2013
2099
  for (const instance of instances) {
2014
- await this.evaluateCustomGettersForInstance(instance, perspective, metadata);
2100
+ await this.evaluateCustomGettersForInstance(instance, perspective, metadata, getterOpts);
2015
2101
  }
2016
2102
  // Filter by where conditions that couldn't be filtered in SQL
2017
2103
  // This includes:
@@ -2515,11 +2601,25 @@ FETCH links
2515
2601
  // entirely and let innerUpdate write the links directly.
2516
2602
  const metadata = this.constructor.getModelMetadata();
2517
2603
  const hasConstructor = Object.values(metadata.properties).some((p) => p.required || p.flag || p.initial !== undefined);
2604
+ // Track properties that have resolveLanguage (non-literal) so they can be
2605
+ // set via setProperty after createSubject (which doesn't resolve languages).
2606
+ const deferredResolveLanguageProps = [];
2518
2607
  if (hasConstructor) {
2519
2608
  // First filter out the properties that are not relations (arrays)
2520
2609
  const initialValues = {};
2521
2610
  for (const [key, value] of Object.entries(this)) {
2522
2611
  if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {
2612
+ // Check if this property requires language resolution (e.g. file storage).
2613
+ // If so, resolve the expression *before* passing to createSubject so
2614
+ // the constructor receives a valid URI instead of raw data.
2615
+ const propMeta = metadata.properties[key];
2616
+ if (propMeta?.resolveLanguage && propMeta.resolveLanguage !== 'literal' && typeof value === 'object') {
2617
+ // Defer these properties — they need createExpression which may
2618
+ // fail inside a batch context on some languages. We'll set them
2619
+ // via setProperty after createSubject.
2620
+ deferredResolveLanguageProps.push(key);
2621
+ continue;
2622
+ }
2523
2623
  initialValues[key] = value;
2524
2624
  }
2525
2625
  }
@@ -2532,6 +2632,15 @@ FETCH links
2532
2632
  // When createSubject was skipped (no constructor actions), we must enable
2533
2633
  // property writing so that scalar values are persisted as links.
2534
2634
  await this.innerUpdate(!hasConstructor, batchId);
2635
+ // Now handle any deferred resolveLanguage properties that were excluded
2636
+ // from initialValues. setProperty will call createExpression to upload
2637
+ // the data to the appropriate language and store the resulting URI.
2638
+ for (const key of deferredResolveLanguageProps) {
2639
+ const value = this[key];
2640
+ if (value !== undefined && value !== null) {
2641
+ await this.setProperty(key, value, batchId);
2642
+ }
2643
+ }
2535
2644
  // If we got a batchId passed in, we let the caller decide when to commit.
2536
2645
  // We can't call getData() since the instance won't exist in the perspective
2537
2646
  // until the batch is committed.
@@ -2584,6 +2693,22 @@ FETCH links
2584
2693
  // Skip unchanged fields when a snapshot is available
2585
2694
  if (dirty && !dirty.has(key))
2586
2695
  continue;
2696
+ // Skip read-only computed relations — explicit getters never write links.
2697
+ // For target+filter relations, skip only when another relation on this
2698
+ // model claims the same predicate (i.e., this is a filtered *view* of a
2699
+ // base relation and writing would collide).
2700
+ const relMeta = metadata.relations[key];
2701
+ if (relMeta) {
2702
+ if (relMeta.getter)
2703
+ continue;
2704
+ if (relMeta.target && relMeta.filter !== false) {
2705
+ // Check for predicate collision with a sibling relation
2706
+ const hasCollision = Object.entries(metadata.relations).some(([otherName, otherMeta]) => otherName !== key &&
2707
+ otherMeta.predicate === relMeta.predicate);
2708
+ if (hasCollision)
2709
+ continue;
2710
+ }
2711
+ }
2587
2712
  if (value !== undefined && value !== null) {
2588
2713
  if (value?.action) {
2589
2714
  switch (value.action) {
@@ -2680,11 +2805,6 @@ FETCH links
2680
2805
  * ```
2681
2806
  */
2682
2807
  async delete(batchId) {
2683
- // Check if the model has a destructor (required properties, flags, or
2684
- // properties with initial values). Models whose properties are all
2685
- // optional, have no @Flag, and have no initial values produce an empty
2686
- // SHACL destructor, so calling removeSubject would fail. In that case
2687
- // we skip the destructor and just remove all outgoing links directly.
2688
2808
  const metadata = this.constructor.getModelMetadata();
2689
2809
  const hasDestructor = Object.values(metadata.properties).some((p) => p.required || p.flag || p.initial !== undefined);
2690
2810
  if (hasDestructor) {
@@ -2692,18 +2812,39 @@ FETCH links
2692
2812
  await this._perspective.removeSubject(this, this._baseExpression, batchId);
2693
2813
  }
2694
2814
  else {
2695
- // No destructor — manually remove all outgoing links from this node
2815
+ // No destructor (all-optional model).
2816
+ // SAFETY: We must NOT remove all outgoing links because another model
2817
+ // class may be instantiated on the same base expression. Removing
2818
+ // everything would silently destroy that other instance's data — and
2819
+ // if that instance has a destructor, it can no longer be called
2820
+ // cleanly, leaving link debris.
2821
+ //
2822
+ // Instead we only remove outgoing links whose predicate is declared
2823
+ // by THIS model's schema (properties + relations).
2696
2824
  try {
2825
+ const knownPredicates = new Set();
2826
+ for (const p of Object.values(metadata.properties)) {
2827
+ if (p.predicate)
2828
+ knownPredicates.add(p.predicate);
2829
+ }
2830
+ for (const r of Object.values(metadata.relations)) {
2831
+ if (r.predicate)
2832
+ knownPredicates.add(r.predicate);
2833
+ }
2697
2834
  const outgoingLinks = await this._perspective.get(new LinkQuery({ source: this._baseExpression }));
2698
- if (outgoingLinks.length > 0) {
2699
- await this._perspective.removeLinks(outgoingLinks, batchId);
2835
+ const ownLinks = outgoingLinks.filter((link) => link.data.predicate && knownPredicates.has(link.data.predicate));
2836
+ if (ownLinks.length > 0) {
2837
+ await this._perspective.removeLinks(ownLinks, batchId);
2700
2838
  }
2701
2839
  }
2702
2840
  catch (e) {
2703
2841
  console.warn(`delete(): failed to remove outgoing links for ${this._baseExpression}:`, e);
2704
2842
  }
2705
2843
  }
2706
- // Clean up incoming links — remove any links that point **to** this instance
2844
+ // Clean up incoming links — remove any links that point **to** this instance.
2845
+ // Unlike outgoing links (scoped above), incoming links originate from OTHER
2846
+ // nodes. Removing them doesn't damage sibling models on this node; it
2847
+ // prevents dangling references elsewhere (e.g. a parent's has_child link).
2707
2848
  try {
2708
2849
  const incomingLinks = await this._perspective.get(new LinkQuery({ target: this._baseExpression }));
2709
2850
  if (incomingLinks.length > 0) {
@@ -1,3 +1,5 @@
1
+ import { ConformanceCondition } from "../shacl/SHACLShape";
2
+ import type { Where } from "./Ad4mModel";
1
3
  /** Metadata stored for each property via @Property / @Optional / @ReadOnly / @Flag */
2
4
  export interface PropertyMetadataEntry extends PropertyOptions {
3
5
  /** Internal computed writable flag (inverse of readOnly) for SDNA/SHACL compatibility */
@@ -21,6 +23,18 @@ export interface RelationMetadataEntry {
21
23
  * The expression can reference 'Base' which will be replaced with the instance's base expression.
22
24
  */
23
25
  getter?: string;
26
+ /**
27
+ * Whether to auto-generate a conformance filter when `target` is set.
28
+ * Defaults to `true` — set to `false` to opt out of DB-level type filtering
29
+ * while keeping hydration capability via `include`.
30
+ */
31
+ filter?: boolean;
32
+ /**
33
+ * Filter constraints on linked target nodes using the query DSL.
34
+ * Property names reference the target model's properties.
35
+ * Overrides auto-derived conformance when set.
36
+ */
37
+ where?: Where;
24
38
  }
25
39
  /**
26
40
  * Retrieve property metadata for a given class constructor.
@@ -53,6 +67,22 @@ export interface Ad4mModelLike {
53
67
  generateSDNA?: () => any;
54
68
  generateSHACL?: () => any;
55
69
  }
70
+ /**
71
+ * Build a conformance filter for a relation whose target model is known.
72
+ *
73
+ * Inspects the target class's property metadata to derive:
74
+ * - `conformanceConditions`: Structured, DB-agnostic conditions (flag & required checks)
75
+ * - `getter`: Pre-computed SurrealQL expression that traverses outgoing links and filters
76
+ * target nodes to only those conforming to the target shape.
77
+ *
78
+ * @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
79
+ * @param targetClass - The target model class (resolved from the target() thunk)
80
+ * @returns `{ getter, conformanceConditions }` or `undefined` if no conditions could be derived
81
+ */
82
+ export declare function buildConformanceFilter(relationPredicate: string, targetClass: Ad4mModelLike): {
83
+ getter: string;
84
+ conformanceConditions: ConformanceCondition[];
85
+ } | undefined;
56
86
  /**
57
87
  * Convert a model instance to a plain serializable object.
58
88
  * Reads the property metadata and extracts values from the instance.
@@ -388,18 +418,54 @@ export declare function ReadOnly(opts: PropertyOptions): <T>(target: T, key: key
388
418
  * Options for relation decorators (@HasMany, @HasOne, @BelongsToOne, @BelongsToMany).
389
419
  */
390
420
  export interface RelationOptions {
391
- /** The predicate URI used to link the two models */
392
- through: string;
393
- /** The target model class (use a thunk to avoid circular-dependency issues). Optional for untyped string relations. */
421
+ /**
422
+ * The predicate URI used to link the two models.
423
+ * Defaults to `'ad4m://has_child'` when omitted.
424
+ * Cannot be combined with `getter`.
425
+ */
426
+ through?: string;
427
+ /** The target model class (use a thunk to avoid circular-dependency issues). Optional for untyped string relations.
428
+ * Cannot be combined with `getter`. */
394
429
  target?: () => Ad4mModelLike;
395
430
  /**
396
431
  * Custom SurrealQL getter to resolve the relation values. Use this for custom graph traversals.
397
432
  * The expression can reference 'Base' which will be replaced with the instance's base expression.
398
433
  * Example: "(<-link[WHERE predicate = 'flux://has_reply'].out.uri)"
434
+ *
435
+ * Mutually exclusive with `through` and `target`. When `getter` is provided the
436
+ * relation is read-only (no adder/remover actions are generated).
399
437
  */
400
438
  getter?: string;
401
439
  /** Whether the link is stored locally (not shared on the network) */
402
440
  local?: boolean;
441
+ /**
442
+ * Whether to auto-generate a DB-level conformance filter when `target` is set.
443
+ * Defaults to `true` when `target` is present — the query will only return linked
444
+ * nodes whose shape matches the target model (required properties, flags, etc.).
445
+ * Set to `false` to opt out of filtering while keeping hydration capability.
446
+ */
447
+ filter?: boolean;
448
+ /**
449
+ * Filter constraints on the linked target nodes, using the same query DSL
450
+ * as `Model.query().where(...)`. Property names reference the **target**
451
+ * model's properties (resolved via target metadata).
452
+ *
453
+ * When `target` is set and `where` is omitted, conformance conditions are
454
+ * auto-derived from the target shape (flags + required properties).
455
+ * Providing `where` overrides this auto-derivation.
456
+ *
457
+ * Mutually exclusive with `getter` and `filter: false`.
458
+ *
459
+ * @example
460
+ * ```typescript
461
+ * @HasMany(() => Message, {
462
+ * through: "flux://entry_type",
463
+ * where: { status: "active", priority: { gte: 3 } }
464
+ * })
465
+ * activeMessages: Message[] = []
466
+ * ```
467
+ */
468
+ where?: Where;
403
469
  }
404
470
  /**
405
471
  * Utility type that describes the auto-generated helper methods for a HasMany
@@ -453,7 +519,7 @@ export type HasManyMethods<Keys extends string> = {
453
519
  * ```
454
520
  */
455
521
  export declare function HasMany(opts: RelationOptions): PropertyDecorator;
456
- export declare function HasMany(target: () => Ad4mModelLike, opts: Omit<RelationOptions, 'target'>): PropertyDecorator;
522
+ export declare function HasMany(target: () => Ad4mModelLike, opts?: Omit<RelationOptions, 'target'>): PropertyDecorator;
457
523
  /**
458
524
  * Decorator for defining a one-to-one relation (owning side).
459
525
  *
@@ -479,7 +545,7 @@ export declare function HasMany(target: () => Ad4mModelLike, opts: Omit<Relation
479
545
  * ```
480
546
  */
481
547
  export declare function HasOne(opts: RelationOptions): PropertyDecorator;
482
- export declare function HasOne(target: () => Ad4mModelLike, opts: Omit<RelationOptions, 'target'>): PropertyDecorator;
548
+ export declare function HasOne(target: () => Ad4mModelLike, opts?: Omit<RelationOptions, 'target'>): PropertyDecorator;
483
549
  /**
484
550
  * Decorator for defining the inverse side of a one-to-one relation.
485
551
  *
@@ -505,7 +571,7 @@ export declare function HasOne(target: () => Ad4mModelLike, opts: Omit<RelationO
505
571
  * ```
506
572
  */
507
573
  export declare function BelongsToOne(opts: RelationOptions): PropertyDecorator;
508
- export declare function BelongsToOne(target: () => Ad4mModelLike, opts: Omit<RelationOptions, 'target'>): PropertyDecorator;
574
+ export declare function BelongsToOne(target: () => Ad4mModelLike, opts?: Omit<RelationOptions, 'target'>): PropertyDecorator;
509
575
  /**
510
576
  * Decorator for defining the inverse side of a many-to-many relation.
511
577
  *
@@ -531,4 +597,4 @@ export declare function BelongsToOne(target: () => Ad4mModelLike, opts: Omit<Rel
531
597
  * ```
532
598
  */
533
599
  export declare function BelongsToMany(opts: RelationOptions): PropertyDecorator;
534
- export declare function BelongsToMany(target: () => Ad4mModelLike, opts: Omit<RelationOptions, 'target'>): PropertyDecorator;
600
+ export declare function BelongsToMany(target: () => Ad4mModelLike, opts?: Omit<RelationOptions, 'target'>): PropertyDecorator;