@coasys/ad4m 0.12.0-rc1-dev.4 → 0.12.0-rc2

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.
Files changed (166) hide show
  1. package/lib/index.cjs +5052 -4446
  2. package/lib/index.js +5019 -4442
  3. package/lib/src/agent/AgentClient.d.ts +4 -0
  4. package/lib/src/agent/AgentClient.js +34 -0
  5. package/lib/src/index.d.ts +2 -3
  6. package/lib/src/index.js +2 -3
  7. package/lib/src/model/Ad4mModel.d.ts +8 -782
  8. package/lib/src/model/Ad4mModel.js +160 -2354
  9. package/lib/src/model/ModelQueryBuilder.d.ts +370 -0
  10. package/lib/src/model/ModelQueryBuilder.js +556 -0
  11. package/lib/src/model/decorators.d.ts +71 -23
  12. package/lib/src/model/decorators.js +133 -384
  13. package/lib/src/model/hydration.d.ts +102 -0
  14. package/lib/src/model/hydration.js +709 -0
  15. package/lib/src/model/index.d.ts +20 -0
  16. package/lib/src/model/index.js +20 -0
  17. package/lib/src/model/{schema/fromJSONSchema.d.ts → json-schema.d.ts} +45 -12
  18. package/lib/src/model/json-schema.js +326 -0
  19. package/lib/src/model/prolog-facts.d.ts +37 -0
  20. package/lib/src/model/{prolog/generatePrologFacts.js → prolog-facts.js} +47 -52
  21. package/lib/src/model/query-common.d.ts +14 -0
  22. package/lib/src/model/query-common.js +36 -0
  23. package/lib/src/model/query-prolog.d.ts +15 -0
  24. package/lib/src/model/query-prolog.js +140 -0
  25. package/lib/src/model/query-surreal.d.ts +44 -0
  26. package/lib/src/model/query-surreal.js +249 -0
  27. package/lib/src/model/relation-filtering.test.js +838 -0
  28. package/lib/src/model/sdna.d.ts +14 -0
  29. package/lib/src/model/sdna.js +141 -0
  30. package/lib/src/model/shacl-gen.d.ts +31 -0
  31. package/lib/src/model/shacl-gen.js +246 -0
  32. package/lib/src/model/surreal-utils.d.ts +42 -0
  33. package/lib/src/model/surreal-utils.js +128 -0
  34. package/lib/src/model/types.d.ts +75 -96
  35. package/lib/src/model/types.js +4 -4
  36. package/lib/src/model/util.d.ts +4 -5
  37. package/lib/src/model/util.js +12 -32
  38. package/lib/src/perspectives/PerspectiveClient.d.ts +1 -1
  39. package/lib/src/perspectives/PerspectiveProxy.d.ts +1 -1
  40. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +79 -0
  41. package/lib/src/perspectives/WakerSubscriptionManager.js +196 -0
  42. package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
  43. package/lib/src/runtime/RuntimeResolver.js +73 -0
  44. package/lib/src/schema.gql +14 -0
  45. package/lib/src/shacl/SHACLShape.d.ts +23 -0
  46. package/lib/src/shacl/SHACLShape.js +45 -0
  47. package/lib/src/typeDefs.js +14 -0
  48. package/package.json +13 -8
  49. package/src/agent/AgentClient.ts +45 -0
  50. package/src/index.ts +2 -3
  51. package/src/model/Ad4mModel.ts +1089 -3686
  52. package/src/model/ModelQueryBuilder.ts +617 -0
  53. package/src/model/Subject.ts +1 -1
  54. package/src/model/decorators.ts +218 -453
  55. package/src/model/hydration.ts +796 -0
  56. package/src/model/index.ts +21 -0
  57. package/src/model/json-schema.ts +424 -0
  58. package/src/model/prolog-facts.ts +145 -0
  59. package/src/model/query-common.ts +48 -0
  60. package/src/model/query-prolog.ts +148 -0
  61. package/src/model/query-surreal.ts +280 -0
  62. package/src/model/relation-filtering.test.ts +803 -0
  63. package/src/model/sdna.ts +170 -0
  64. package/src/model/shacl-gen.ts +292 -0
  65. package/src/model/surreal-utils.ts +147 -0
  66. package/src/model/types.ts +182 -0
  67. package/src/model/util.ts +13 -36
  68. package/src/perspectives/PerspectiveClient.ts +1 -1
  69. package/src/perspectives/PerspectiveProxy.ts +1 -1
  70. package/src/perspectives/WakerSubscriptionManager.ts +292 -0
  71. package/src/runtime/RuntimeResolver.ts +53 -0
  72. package/src/shacl/SHACLShape.ts +83 -0
  73. package/lib/src/Ad4mClient.test.js +0 -1204
  74. package/lib/src/Literal.test.d.ts +0 -1
  75. package/lib/src/Literal.test.js +0 -41
  76. package/lib/src/model/mutation.d.ts +0 -81
  77. package/lib/src/model/mutation.js +0 -317
  78. package/lib/src/model/parentUtils.d.ts +0 -32
  79. package/lib/src/model/parentUtils.js +0 -64
  80. package/lib/src/model/prolog/generatePrologFacts.d.ts +0 -36
  81. package/lib/src/model/prolog/index.d.ts +0 -1
  82. package/lib/src/model/prolog/index.js +0 -1
  83. package/lib/src/model/query/ModelQueryBuilder.d.ts +0 -82
  84. package/lib/src/model/query/ModelQueryBuilder.js +0 -115
  85. package/lib/src/model/query/QueryBuilder.d.ts +0 -101
  86. package/lib/src/model/query/QueryBuilder.js +0 -193
  87. package/lib/src/model/query/SurrealQueryBuilder.d.ts +0 -48
  88. package/lib/src/model/query/SurrealQueryBuilder.js +0 -371
  89. package/lib/src/model/query/fetchInstance.d.ts +0 -24
  90. package/lib/src/model/query/fetchInstance.js +0 -144
  91. package/lib/src/model/query/hydration.d.ts +0 -54
  92. package/lib/src/model/query/hydration.js +0 -214
  93. package/lib/src/model/query/operations.d.ts +0 -59
  94. package/lib/src/model/query/operations.js +0 -384
  95. package/lib/src/model/query/snapshot.d.ts +0 -59
  96. package/lib/src/model/query/snapshot.js +0 -106
  97. package/lib/src/model/query/surrealCompiler.d.ts +0 -42
  98. package/lib/src/model/query/surrealCompiler.js +0 -304
  99. package/lib/src/model/schema/fromJSONSchema.js +0 -264
  100. package/lib/src/model/schema/metadata.d.ts +0 -15
  101. package/lib/src/model/schema/metadata.js +0 -112
  102. package/lib/src/model/subscription.d.ts +0 -47
  103. package/lib/src/model/subscription.js +0 -231
  104. package/lib/src/model/transaction.d.ts +0 -27
  105. package/lib/src/model/transaction.js +0 -32
  106. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  107. package/lib/src/shims/type-graphql.d.ts +0 -32
  108. package/lib/src/src/Ad4mClient.d.ts +0 -28
  109. package/lib/src/src/Address.d.ts +0 -1
  110. package/lib/src/src/DID.d.ts +0 -1
  111. package/lib/src/src/Exception.d.ts +0 -7
  112. package/lib/src/src/Literal.d.ts +0 -7
  113. package/lib/src/src/PubSub.d.ts +0 -17
  114. package/lib/src/src/SmartLiteral.d.ts +0 -12
  115. package/lib/src/src/agent/Agent.d.ts +0 -110
  116. package/lib/src/src/agent/AgentClient.d.ts +0 -62
  117. package/lib/src/src/agent/AgentResolver.d.ts +0 -30
  118. package/lib/src/src/agent/AgentStatus.d.ts +0 -8
  119. package/lib/src/src/ai/AIClient.d.ts +0 -32
  120. package/lib/src/src/ai/AIResolver.d.ts +0 -75
  121. package/lib/src/src/ai/Tasks.d.ts +0 -37
  122. package/lib/src/src/buildSchema.d.ts +0 -1
  123. package/lib/src/src/expression/Expression.d.ts +0 -28
  124. package/lib/src/src/expression/ExpressionClient.d.ts +0 -13
  125. package/lib/src/src/expression/ExpressionRef.d.ts +0 -9
  126. package/lib/src/src/expression/ExpressionResolver.d.ts +0 -10
  127. package/lib/src/src/index.d.ts +0 -35
  128. package/lib/src/src/jestSetup.d.ts +0 -1
  129. package/lib/src/src/language/Icon.d.ts +0 -4
  130. package/lib/src/src/language/Language.d.ts +0 -206
  131. package/lib/src/src/language/LanguageClient.d.ts +0 -17
  132. package/lib/src/src/language/LanguageContext.d.ts +0 -37
  133. package/lib/src/src/language/LanguageHandle.d.ts +0 -9
  134. package/lib/src/src/language/LanguageMeta.d.ts +0 -35
  135. package/lib/src/src/language/LanguageRef.d.ts +0 -6
  136. package/lib/src/src/language/LanguageResolver.d.ts +0 -19
  137. package/lib/src/src/links/Links.d.ts +0 -39
  138. package/lib/src/src/links/Links.test.d.ts +0 -1
  139. package/lib/src/src/model/Ad4mModel.d.ts +0 -1438
  140. package/lib/src/src/model/Ad4mModel.test.d.ts +0 -1
  141. package/lib/src/src/model/Subject.d.ts +0 -25
  142. package/lib/src/src/model/decorators.d.ts +0 -545
  143. package/lib/src/src/model/util.d.ts +0 -12
  144. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +0 -10
  145. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +0 -25
  146. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +0 -19
  147. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +0 -1
  148. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +0 -24
  149. package/lib/src/src/perspectives/LinkQuery.d.ts +0 -11
  150. package/lib/src/src/perspectives/Perspective.d.ts +0 -38
  151. package/lib/src/src/perspectives/Perspective.test.d.ts +0 -1
  152. package/lib/src/src/perspectives/PerspectiveClient.d.ts +0 -97
  153. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +0 -9
  154. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +0 -18
  155. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +0 -865
  156. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +0 -57
  157. package/lib/src/src/runtime/RuntimeClient.d.ts +0 -56
  158. package/lib/src/src/runtime/RuntimeResolver.d.ts +0 -132
  159. package/lib/src/src/shacl/SHACLFlow.d.ts +0 -171
  160. package/lib/src/src/shacl/SHACLFlow.test.d.ts +0 -1
  161. package/lib/src/src/shacl/SHACLShape.d.ts +0 -117
  162. package/lib/src/src/shacl/SHACLShape.test.d.ts +0 -1
  163. package/lib/src/src/typeDefs.d.ts +0 -1
  164. package/lib/src/src/unwrapApolloResult.d.ts +0 -2
  165. package/lib/src/src/utils.d.ts +0 -25
  166. /package/lib/src/{Ad4mClient.test.d.ts → model/relation-filtering.test.d.ts} +0 -0
@@ -1,5 +1,9 @@
1
- import { capitalize, propertyNameToSetterName, singularToPlural, stringifyObjectLiteral } from "./util";
2
- import { SHACLShape, SHACLPropertyShape } from "../shacl/SHACLShape";
1
+ import { capitalize } from "./util";
2
+ import type { Where } from "./types";
3
+ import { buildSDNA } from "./sdna";
4
+ import { buildSHACL } from "./shacl-gen";
5
+ import { escapeSurrealString } from "../utils";
6
+ import type { ConformanceCondition } from "../shacl/SHACLShape";
3
7
 
4
8
  // ============================================================================
5
9
  // WeakMap-based metadata registry
@@ -32,6 +36,18 @@ export interface RelationMetadataEntry {
32
36
  * The expression can reference 'Base' which will be replaced with the instance's base expression.
33
37
  */
34
38
  getter?: string;
39
+ /**
40
+ * Whether to auto-generate a conformance filter when `target` is set.
41
+ * Defaults to `true` — set to `false` to opt out of DB-level type filtering
42
+ * while keeping hydration capability via `include`.
43
+ */
44
+ filter?: boolean;
45
+ /**
46
+ * Filter constraints on linked target nodes using the query DSL.
47
+ * Property names reference the target model's properties.
48
+ * Overrides auto-derived conformance when set.
49
+ */
50
+ where?: Where;
35
51
  }
36
52
 
37
53
  /** Registry of property metadata keyed by constructor → { propName → metadata } */
@@ -117,54 +133,68 @@ export interface Ad4mModelLike {
117
133
  }
118
134
 
119
135
  /**
120
- * Convert a model instance to a plain serializable object.
121
- * Reads the property metadata and extracts values from the instance.
136
+ * Build a conformance filter for a relation whose target model is known.
137
+ *
138
+ * Inspects the target class's property metadata to derive:
139
+ * - `conformanceConditions`: Structured, DB-agnostic conditions (flag & required checks)
140
+ * - `getter`: Pre-computed SurrealQL expression that traverses outgoing links and filters
141
+ * target nodes to only those conforming to the target shape.
142
+ *
143
+ * @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
144
+ * @param targetClass - The target model class (resolved from the target() thunk)
145
+ * @returns `{ getter, conformanceConditions }` or `undefined` if no conditions could be derived
122
146
  */
123
- export function instanceToSerializable(instance: any): Record<string, any> {
124
- const ctor = instance.constructor;
125
- const props = getPropertiesMetadata(ctor);
126
- const result: Record<string, any> = {};
127
- for (const [key, _meta] of Object.entries(props)) {
128
- result[key] = instance[key];
129
- }
130
- return result;
131
- }
147
+ export function buildConformanceFilter(
148
+ relationPredicate: string,
149
+ targetClass: Ad4mModelLike
150
+ ): { getter: string; conformanceConditions: ConformanceCondition[] } | undefined {
151
+ try {
152
+ const targetProps = getPropertiesMetadata(targetClass);
153
+ const conditions: ConformanceCondition[] = [];
154
+ const surrealConditions: string[] = [];
155
+
156
+ // 1. Flags — check predicate + value
157
+ for (const [_propName, propMeta] of Object.entries(targetProps)) {
158
+ if (propMeta.flag && propMeta.initial && propMeta.through) {
159
+ conditions.push({
160
+ type: 'flag',
161
+ predicate: propMeta.through,
162
+ value: propMeta.initial,
163
+ });
164
+ surrealConditions.push(
165
+ `count(->link[WHERE predicate = '${escapeSurrealString(propMeta.through)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`
166
+ );
167
+ }
168
+ }
132
169
 
133
- /**
134
- * Generate a random identifier string (lowercase alpha).
135
- * Generate a random identifier string of the given length (lowercase alpha).
136
- */
137
- export function makeRandomId(length: number): string {
138
- let result = '';
139
- const characters = 'abcdefghijklmnopqrstuvwxyz';
140
- const charactersLength = characters.length;
141
- for (let i = 0; i < length; i++) {
142
- result += characters.charAt(Math.floor(Math.random() * charactersLength));
143
- }
144
- return result;
145
- }
170
+ // 2. Required (non-flag) properties — check predicate exists
171
+ // Skip properties with custom getters (they don't follow the standard link pattern)
172
+ for (const [_propName, propMeta] of Object.entries(targetProps)) {
173
+ if (propMeta.required && !propMeta.flag && !propMeta.getter && propMeta.through) {
174
+ conditions.push({
175
+ type: 'required',
176
+ predicate: propMeta.through,
177
+ });
178
+ surrealConditions.push(
179
+ `count(->link[WHERE predicate = '${escapeSurrealString(propMeta.through)}']) > 0`
180
+ );
181
+ }
182
+ }
146
183
 
147
- export class PerspectiveAction {
148
- action: string
149
- source: string
150
- predicate: string
151
- target: string
152
- }
184
+ if (conditions.length === 0) {
185
+ return undefined;
186
+ }
153
187
 
154
- export function addLink(source: string, predicate: string, target: string): PerspectiveAction {
155
- return {
156
- action: "addLink",
157
- source,
158
- predicate,
159
- target,
160
- };
161
- }
188
+ const escapedPredicate = escapeSurrealString(relationPredicate);
189
+ const getter = `(->link[WHERE predicate = '${escapedPredicate}'].out[WHERE ${surrealConditions.join(' AND ')}].uri)`;
162
190
 
163
- export function hasLink(predicate: string): string {
164
- return `triple(this, "${predicate}", _)`
191
+ return { getter, conformanceConditions: conditions };
192
+ } catch (e) {
193
+ // Target class may not have property metadata
194
+ return undefined;
195
+ }
165
196
  }
166
197
 
167
-
168
198
  export interface PropertyOptions {
169
199
  /**
170
200
  * The predicate of the property. All properties must have this option.
@@ -453,376 +483,22 @@ export function Model(opts: ModelConfig) {
453
483
  target.className = opts.name;
454
484
 
455
485
  target.generateSDNA = function() {
456
- let sdna = ""
457
- let subjectName = opts.name
458
- let obj = target.prototype;
459
-
460
- let uuid = makeRandomId(8)
461
-
462
- sdna += `subject_class("${subjectName}", ${uuid}).\n`
463
-
464
-
465
- let classRemoverActions = []
466
-
467
- let constructorActions = []
468
- if(obj.subjectConstructor && obj.subjectConstructor.length) {
469
- constructorActions = constructorActions.concat(obj.subjectConstructor)
470
- }
471
-
472
- let instanceConditions = []
473
- if(obj.isSubjectInstance && obj.isSubjectInstance.length) {
474
- instanceConditions = instanceConditions.concat(obj.isSubjectInstance)
475
- }
476
-
477
- let propertiesCode = []
478
- let properties = getPropertiesMetadata(target)
479
- for(let property in properties) {
480
- let propertyCode = `property(${uuid}, "${property}").\n`
481
-
482
- let { through, initial, required, resolveLanguage, writable, flag, prologGetter, prologSetter, local } = properties[property]
483
-
484
- if(resolveLanguage) {
485
- propertyCode += `property_resolve(${uuid}, "${property}").\n`
486
- propertyCode += `property_resolve_language(${uuid}, "${property}", "${resolveLanguage}").\n`
487
- }
488
-
489
- if(prologGetter) {
490
- propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- ${prologGetter}.\n`
491
- } else if(through) {
492
- propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- triple(Base, "${through}", Value).\n`
493
-
494
- if(required) {
495
- if(flag) {
496
- instanceConditions.push(`triple(Base, "${through}", "${initial}")`)
497
- } else {
498
- instanceConditions.push(`triple(Base, "${through}", _)`)
499
- }
500
- }
501
- }
502
-
503
- if(prologSetter) {
504
- propertyCode += `property_setter(${uuid}, "${property}", Actions) :- ${prologSetter}.\n`
505
- } else if (writable && through) {
506
- let setter = obj[propertyNameToSetterName(property)]
507
- if(typeof setter === "function") {
508
- let action = [{
509
- action: "setSingleTarget",
510
- source: "this",
511
- predicate: through,
512
- target: "value",
513
- ...(local && { local: true })
514
- }]
515
- propertyCode += `property_setter(${uuid}, "${property}", '${stringifyObjectLiteral(action)}').\n`
516
- }
517
- }
518
-
519
- propertiesCode.push(propertyCode)
520
-
521
- // Auto-derive effectiveInitial for required, writable, non-flag properties
522
- // so constructor/destructor always handle the property link.
523
- // Optional properties (required: false) are excluded — they should
524
- // remain unset (undefined) until explicitly assigned.
525
- const effectiveInitial = initial
526
- ?? (required && writable && !flag && through ? "literal://string:" : undefined);
527
-
528
- if(effectiveInitial) {
529
- constructorActions.push({
530
- action: "addLink",
531
- source: "this",
532
- predicate: through,
533
- target: effectiveInitial,
534
- })
535
-
536
- classRemoverActions.push({
537
- action: "removeLink",
538
- source: "this",
539
- predicate: through,
540
- target: "*",
541
- })
542
- }
543
- }
544
-
545
- let relationsCode = []
546
- const allRelationsMeta = getRelationsMetadata(target)
547
- const relations = Object.fromEntries(
548
- Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany')
549
- )
550
- for(let relation in relations) {
551
- let relationCode = `collection(${uuid}, "${relation}").\n`
552
-
553
- let { predicate: through, local} = relations[relation]
554
-
555
- if(through) {
556
- relationCode += `collection_getter(${uuid}, Base, "${relation}", List) :- findall(C, triple(Base, "${through}", C), List).\n`
557
-
558
- let relationAdderAction = [{
559
- action: "addLink",
560
- source: "this",
561
- predicate: through,
562
- target: "value",
563
- ...(local && { local: true })
564
- }]
565
-
566
- let relationRemoverAction = [{
567
- action: "removeLink",
568
- source: "this",
569
- predicate: through,
570
- target: "value",
571
- }]
572
-
573
- let relationSetterAction = [{
574
- action: "collectionSetter",
575
- source: "this",
576
- predicate: through,
577
- target: "value",
578
- ...(local && { local: true })
579
- }]
580
- relationCode += `collection_adder(${uuid}, "${relation}", '${stringifyObjectLiteral(relationAdderAction)}').\n`
581
- relationCode += `collection_remover(${uuid}, "${relation}", '${stringifyObjectLiteral(relationRemoverAction)}').\n`
582
- relationCode += `collection_setter(${uuid}, "${relation}", '${stringifyObjectLiteral(relationSetterAction)}').\n`
583
- }
584
-
585
- relationsCode.push(relationCode)
586
- }
587
-
588
- let subjectContructorJSONString = stringifyObjectLiteral(constructorActions)
589
- sdna += `constructor(${uuid}, '${subjectContructorJSONString}').\n`
590
- if(instanceConditions.length > 0) {
591
- let instanceConditionProlog = instanceConditions.join(", ")
592
- sdna += `instance(${uuid}, Base) :- ${instanceConditionProlog}.\n`
593
- sdna += "\n"
594
- }
595
- sdna += `destructor(${uuid}, '${stringifyObjectLiteral(classRemoverActions)}').\n`
596
- sdna += "\n"
597
- sdna += propertiesCode.join("\n")
598
- sdna += "\n"
599
- sdna += relationsCode.join("\n")
600
-
601
- return {
602
- sdna,
603
- name: subjectName
604
- }
486
+ return buildSDNA(
487
+ opts.name,
488
+ target.prototype,
489
+ getPropertiesMetadata(target),
490
+ getRelationsMetadata(target),
491
+ );
605
492
  }
606
493
 
607
- // Generate SHACL shape (W3C standard + AD4M action definitions)
608
494
  target.generateSHACL = function() {
609
- const subjectName = opts.name;
610
- const obj = target.prototype;
611
-
612
- // Determine namespace from first property or relation, or use default
613
- let namespace = "ad4m://";
614
- const properties = getPropertiesMetadata(target);
615
- const allRelationsMeta2 = getRelationsMetadata(target);
616
- const relations = Object.fromEntries(
617
- Object.entries(allRelationsMeta2).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany')
495
+ return buildSHACL(
496
+ opts.name,
497
+ target,
498
+ getPropertiesMetadata(target),
499
+ getRelationsMetadata(target),
500
+ buildConformanceFilter,
618
501
  );
619
-
620
- // Try properties first
621
- if (Object.keys(properties).length > 0) {
622
- const firstProp = properties[Object.keys(properties)[0]];
623
- if (firstProp.through) {
624
- // Extract namespace from through predicate (e.g., "recipe://name" -> "recipe://")
625
- const match = firstProp.through.match(/^([^:]+:\/\/)/);
626
- if (match) {
627
- namespace = match[1];
628
- }
629
- }
630
- }
631
- // Fall back to relations if no properties
632
- else if (Object.keys(relations).length > 0) {
633
- const firstRel = relations[Object.keys(relations)[0]];
634
- if (firstRel.predicate) {
635
- const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
636
- if (match) {
637
- namespace = match[1];
638
- }
639
- }
640
- }
641
-
642
- // Create SHACL shape
643
- const shapeUri = `${namespace}${subjectName}Shape`;
644
- const targetClass = `${namespace}${subjectName}`;
645
- const shape = new SHACLShape(shapeUri, targetClass);
646
-
647
- // Detect @Model inheritance — if the parent class also has
648
- // generateSHACL it is itself a @Model and we reference its shape
649
- // via sh:node so SHACL validators can walk the hierarchy.
650
- const parentCtor = Object.getPrototypeOf(target);
651
- if (parentCtor && typeof parentCtor.generateSHACL === 'function') {
652
- const parentSHACL = parentCtor.generateSHACL();
653
- if (parentSHACL?.shape?.nodeShapeUri) {
654
- shape.addParentShape(parentSHACL.shape.nodeShapeUri);
655
- }
656
- }
657
-
658
- // === Extract Constructor Actions (same logic as generateSDNA) ===
659
- let constructorActions = [];
660
- if(obj.subjectConstructor && obj.subjectConstructor.length) {
661
- constructorActions = constructorActions.concat(obj.subjectConstructor);
662
- }
663
-
664
- // === Extract Destructor Actions ===
665
- let destructorActions = [];
666
-
667
- // Convert properties to SHACL property shapes
668
- for (const propName in properties) {
669
- const propMeta = properties[propName];
670
-
671
- if (!propMeta.through) continue; // Skip properties without predicates
672
-
673
- const propShape: SHACLPropertyShape = {
674
- name: propName, // Property name for generating named URIs
675
- path: propMeta.through,
676
- };
677
-
678
- // Determine datatype from initial value or resolveLanguage
679
- if (propMeta.resolveLanguage === "literal") {
680
- // If it resolves via literal language, it's likely a string
681
- propShape.datatype = "xsd://string";
682
- } else if (propMeta.initial) {
683
- // Try to infer from initial value type
684
- const initialType = typeof obj[propName];
685
- if (initialType === "number") {
686
- propShape.datatype = "xsd://integer";
687
- } else if (initialType === "boolean") {
688
- propShape.datatype = "xsd://boolean";
689
- } else if (initialType === "string") {
690
- propShape.datatype = "xsd://string";
691
- }
692
- }
693
-
694
- // Cardinality constraints
695
- if (propMeta.required) {
696
- propShape.minCount = 1;
697
- }
698
-
699
- // Single-valued properties get maxCount 1
700
- // (relations are handled separately below)
701
- propShape.maxCount = 1;
702
-
703
- // Flag properties have fixed value
704
- if (propMeta.flag && propMeta.initial) {
705
- propShape.hasValue = propMeta.initial;
706
- }
707
-
708
- // AD4M-specific metadata
709
- if (propMeta.local !== undefined) {
710
- propShape.local = propMeta.local;
711
- }
712
-
713
- if (propMeta.writable !== undefined) {
714
- propShape.writable = propMeta.writable;
715
- }
716
-
717
- if (propMeta.resolveLanguage) {
718
- propShape.resolveLanguage = propMeta.resolveLanguage;
719
- }
720
-
721
- // === Extract Setter Actions (same logic as generateSDNA) ===
722
- if (propMeta.prologSetter) {
723
- // Custom Prolog setter defined - not yet supported in SHACL
724
- console.warn(
725
- `[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
726
- `The property will be created without setter actions. Consider using standard writable properties or provide explicit SHACL JSON.`
727
- );
728
- // TODO: Parse custom Prolog setter to extract actions
729
- } else if (propMeta.writable && propMeta.through) {
730
- let setter = obj[propertyNameToSetterName(propName)];
731
- if (typeof setter === "function") {
732
- propShape.setter = [{
733
- action: "setSingleTarget",
734
- source: "this",
735
- predicate: propMeta.through,
736
- target: "value",
737
- ...(propMeta.local && { local: true })
738
- }];
739
- }
740
- }
741
-
742
- // Add to constructor actions if property has initial value
743
- // Auto-derive effectiveInitial for required, writable, non-flag properties.
744
- // Optional properties (required: false) are excluded — they should
745
- // remain unset (undefined) until explicitly assigned.
746
- const effectiveInitial = propMeta.initial
747
- ?? (propMeta.required && propMeta.writable && !propMeta.flag && propMeta.through
748
- ? "literal://string:" : undefined);
749
-
750
- if (effectiveInitial) {
751
- constructorActions.push({
752
- action: "addLink",
753
- source: "this",
754
- predicate: propMeta.through,
755
- target: effectiveInitial,
756
- });
757
-
758
- // Add to destructor actions
759
- destructorActions.push({
760
- action: "removeLink",
761
- source: "this",
762
- predicate: propMeta.through,
763
- target: "*",
764
- });
765
- }
766
-
767
- shape.addProperty(propShape);
768
- }
769
-
770
- // Convert relations to SHACL property shapes
771
- // (relations variable already declared above for namespace inference)
772
- for (const relName in relations) {
773
- const relMeta = relations[relName];
774
-
775
- if (!relMeta.predicate) continue;
776
-
777
- const relShape: SHACLPropertyShape = {
778
- name: relName, // Relation name for generating named URIs
779
- path: relMeta.predicate,
780
- // Relations have no maxCount (unlimited)
781
- // minCount defaults to 0 (optional)
782
- };
783
-
784
- // Determine node kind — relations typically contain IRIs
785
- relShape.nodeKind = 'IRI';
786
-
787
- // AD4M-specific metadata
788
- if (relMeta.local !== undefined) {
789
- relShape.local = relMeta.local;
790
- }
791
-
792
- // === Extract Relation Actions (adder/remover) ===
793
- // Adder action - adds a link to the relation
794
- relShape.adder = [{
795
- action: "addLink",
796
- source: "this",
797
- predicate: relMeta.predicate,
798
- target: "value",
799
- ...(relMeta.local && { local: true })
800
- }];
801
-
802
- // Remover action - removes a link from the relation
803
- relShape.remover = [{
804
- action: "removeLink",
805
- source: "this",
806
- predicate: relMeta.predicate,
807
- target: "value",
808
- ...(relMeta.local && { local: true })
809
- }];
810
-
811
- shape.addProperty(relShape);
812
- }
813
-
814
- // Always set constructor and destructor actions on the shape, even
815
- // when empty. An empty array serialises to `literal://string:[]`
816
- // which the Rust executor parses as a valid (no-op) command list,
817
- // avoiding "No SHACL constructor found" errors for models whose
818
- // properties are all optional and have no @Flag.
819
- shape.setConstructorActions(constructorActions);
820
- shape.setDestructorActions(destructorActions);
821
-
822
- return {
823
- shape,
824
- name: subjectName
825
- };
826
502
  }
827
503
 
828
504
  Object.defineProperty(target, 'type', {configurable: true});
@@ -973,18 +649,54 @@ export function ReadOnly(opts: PropertyOptions) {
973
649
  * Options for relation decorators (@HasMany, @HasOne, @BelongsToOne, @BelongsToMany).
974
650
  */
975
651
  export interface RelationOptions {
976
- /** The predicate URI used to link the two models */
977
- through: string;
978
- /** The target model class (use a thunk to avoid circular-dependency issues). Optional for untyped string relations. */
652
+ /**
653
+ * The predicate URI used to link the two models.
654
+ * Defaults to `'ad4m://has_child'` when omitted.
655
+ * Cannot be combined with `getter`.
656
+ */
657
+ through?: string;
658
+ /** The target model class (use a thunk to avoid circular-dependency issues). Optional for untyped string relations.
659
+ * Cannot be combined with `getter`. */
979
660
  target?: () => Ad4mModelLike;
980
661
  /**
981
662
  * Custom SurrealQL getter to resolve the relation values. Use this for custom graph traversals.
982
663
  * The expression can reference 'Base' which will be replaced with the instance's base expression.
983
664
  * Example: "(<-link[WHERE predicate = 'flux://has_reply'].out.uri)"
665
+ *
666
+ * Mutually exclusive with `through` and `target`. When `getter` is provided the
667
+ * relation is read-only (no adder/remover actions are generated).
984
668
  */
985
669
  getter?: string;
986
670
  /** Whether the link is stored locally (not shared on the network) */
987
671
  local?: boolean;
672
+ /**
673
+ * Whether to auto-generate a DB-level conformance filter when `target` is set.
674
+ * Defaults to `true` when `target` is present — the query will only return linked
675
+ * nodes whose shape matches the target model (required properties, flags, etc.).
676
+ * Set to `false` to opt out of filtering while keeping hydration capability.
677
+ */
678
+ filter?: boolean;
679
+ /**
680
+ * Filter constraints on the linked target nodes, using the same query DSL
681
+ * as `Model.query().where(...)`. Property names reference the **target**
682
+ * model's properties (resolved via target metadata).
683
+ *
684
+ * When `target` is set and `where` is omitted, conformance conditions are
685
+ * auto-derived from the target shape (flags + required properties).
686
+ * Providing `where` overrides this auto-derivation.
687
+ *
688
+ * Mutually exclusive with `getter` and `filter: false`.
689
+ *
690
+ * @example
691
+ * ```typescript
692
+ * @HasMany(() => Message, {
693
+ * through: "flux://entry_type",
694
+ * where: { status: "active", priority: { gte: 3 } }
695
+ * })
696
+ * activeMessages: Message[] = []
697
+ * ```
698
+ */
699
+ where?: Where;
988
700
  }
989
701
 
990
702
  /**
@@ -1016,13 +728,47 @@ function resolveRelationArgs(
1016
728
  second?: Omit<RelationOptions, 'target'>,
1017
729
  ): RelationOptions {
1018
730
  const opts = typeof first === 'function'
1019
- ? { ...second!, target: first }
731
+ ? { ...(second || {}), target: first }
1020
732
  : first;
1021
733
 
734
+ // getter is mutually exclusive with through, target, and where
735
+ if (opts.getter) {
736
+ if (opts.through) {
737
+ throw new Error(
738
+ 'Relation decorator: `getter` and `through` are mutually exclusive. ' +
739
+ 'Use `getter` alone for custom read-only relations, or `through` ' +
740
+ '(with optional `target`) for standard link-based relations.'
741
+ );
742
+ }
743
+ if (opts.target) {
744
+ throw new Error(
745
+ 'Relation decorator: `getter` and `target` are mutually exclusive. ' +
746
+ '`target` auto-generates a conformance getter from the model shape; ' +
747
+ 'providing both is contradictory.'
748
+ );
749
+ }
750
+ if (opts.where) {
751
+ throw new Error(
752
+ 'Relation decorator: `where` and `getter` are mutually exclusive. ' +
753
+ 'Use `where` for DSL-based filtering, or `getter` for raw SurrealQL.'
754
+ );
755
+ }
756
+ return opts;
757
+ }
758
+
759
+ // Default predicate when not provided
1022
760
  if (!opts.through) {
1023
- throw new Error(
1024
- `Relation decorator requires a { through: '...' } option specifying the predicate URI.`
1025
- );
761
+ opts.through = 'ad4m://has_child';
762
+ }
763
+
764
+ // where validation
765
+ if (opts.where) {
766
+ if (opts.filter === false) {
767
+ throw new Error(
768
+ 'Relation decorator: `where` and `filter: false` are contradictory. ' +
769
+ '`where` adds filtering constraints; `filter: false` disables filtering.'
770
+ );
771
+ }
1026
772
  }
1027
773
 
1028
774
  return opts;
@@ -1058,7 +804,7 @@ function resolveRelationArgs(
1058
804
  * ```
1059
805
  */
1060
806
  export function HasMany(opts: RelationOptions): PropertyDecorator;
1061
- export function HasMany(target: () => Ad4mModelLike, opts: Omit<RelationOptions, 'target'>): PropertyDecorator;
807
+ export function HasMany(target: () => Ad4mModelLike, opts?: Omit<RelationOptions, 'target'>): PropertyDecorator;
1062
808
  export function HasMany(
1063
809
  first: (() => Ad4mModelLike) | RelationOptions,
1064
810
  second?: Omit<RelationOptions, 'target'>,
@@ -1075,19 +821,24 @@ export function HasMany(
1075
821
  kind: 'hasMany',
1076
822
  local: opts.local,
1077
823
  ...(opts.getter && { getter: opts.getter }),
824
+ ...(opts.filter !== undefined && { filter: opts.filter }),
825
+ ...(opts.where && { where: opts.where }),
1078
826
  };
1079
827
 
1080
- // Add prototype methods for add/remove/set
1081
828
  const relKey = key as string;
1082
- (target as any)[`add${capitalize(relKey)}`] = async function(this: any, arg: any, batchId?: string) {
1083
- return (this as any).addRelationValue(relKey, arg, batchId);
1084
- };
1085
- (target as any)[`remove${capitalize(relKey)}`] = async function(this: any, arg: any, batchId?: string) {
1086
- return (this as any).removeRelationValue(relKey, arg, batchId);
1087
- };
1088
- (target as any)[`set${capitalize(relKey)}`] = async function(this: any, arg: any, batchId?: string) {
1089
- return (this as any).setRelationValues(relKey, arg, batchId);
1090
- };
829
+ // Only add mutation methods when a predicate is available
830
+ // (getter-only relations are read-only)
831
+ if (opts.through) {
832
+ (target as any)[`add${capitalize(relKey)}`] = async function(this: any, arg: any, batchId?: string) {
833
+ return (this as any).addRelationValue(relKey, arg, batchId);
834
+ };
835
+ (target as any)[`remove${capitalize(relKey)}`] = async function(this: any, arg: any, batchId?: string) {
836
+ return (this as any).removeRelationValue(relKey, arg, batchId);
837
+ };
838
+ (target as any)[`set${capitalize(relKey)}`] = async function(this: any, arg: any, batchId?: string) {
839
+ return (this as any).setRelationValues(relKey, arg, batchId);
840
+ };
841
+ }
1091
842
  Object.defineProperty(target, relKey, { configurable: true, writable: true });
1092
843
  };
1093
844
  }
@@ -1117,7 +868,7 @@ export function HasMany(
1117
868
  * ```
1118
869
  */
1119
870
  export function HasOne(opts: RelationOptions): PropertyDecorator;
1120
- export function HasOne(target: () => Ad4mModelLike, opts: Omit<RelationOptions, 'target'>): PropertyDecorator;
871
+ export function HasOne(target: () => Ad4mModelLike, opts?: Omit<RelationOptions, 'target'>): PropertyDecorator;
1121
872
  export function HasOne(
1122
873
  first: (() => Ad4mModelLike) | RelationOptions,
1123
874
  second?: Omit<RelationOptions, 'target'>,
@@ -1133,26 +884,32 @@ export function HasOne(
1133
884
  kind: 'hasOne',
1134
885
  maxCount: 1,
1135
886
  local: opts.local,
887
+ ...(opts.filter !== undefined && { filter: opts.filter }),
888
+ ...(opts.where && { where: opts.where }),
1136
889
  };
1137
890
 
1138
- // Register as a writable property
1139
- applyPropertyMetadata({
1140
- through: opts.through,
1141
- readOnly: false,
1142
- local: opts.local,
1143
- })(target, key);
1144
-
1145
- // Add prototype methods for add/remove/set (mirroring @HasMany)
1146
891
  const relKey = key as string;
1147
- (target as any)[`add${capitalize(relKey)}`] = async function(this: any, arg: any) {
1148
- return (this as any).addRelationValue(relKey, arg);
1149
- };
1150
- (target as any)[`remove${capitalize(relKey)}`] = async function(this: any, arg: any) {
1151
- return (this as any).removeRelationValue(relKey, arg);
1152
- };
1153
- (target as any)[`set${capitalize(relKey)}`] = async function(this: any, arg: any) {
1154
- return (this as any).setRelationValues(relKey, arg);
1155
- };
892
+ if (opts.through) {
893
+ // Register as a writable property
894
+ applyPropertyMetadata({
895
+ through: opts.through,
896
+ readOnly: false,
897
+ local: opts.local,
898
+ })(target, key);
899
+
900
+ // Add prototype methods for add/remove/set (mirroring @HasMany)
901
+ (target as any)[`add${capitalize(relKey)}`] = async function(this: any, arg: any) {
902
+ return (this as any).addRelationValue(relKey, arg);
903
+ };
904
+ (target as any)[`remove${capitalize(relKey)}`] = async function(this: any, arg: any) {
905
+ return (this as any).removeRelationValue(relKey, arg);
906
+ };
907
+ (target as any)[`set${capitalize(relKey)}`] = async function(this: any, arg: any) {
908
+ return (this as any).setRelationValues(relKey, arg);
909
+ };
910
+ } else {
911
+ Object.defineProperty(target, relKey, { configurable: true, writable: true });
912
+ }
1156
913
  };
1157
914
  }
1158
915
 
@@ -1181,7 +938,7 @@ export function HasOne(
1181
938
  * ```
1182
939
  */
1183
940
  export function BelongsToOne(opts: RelationOptions): PropertyDecorator;
1184
- export function BelongsToOne(target: () => Ad4mModelLike, opts: Omit<RelationOptions, 'target'>): PropertyDecorator;
941
+ export function BelongsToOne(target: () => Ad4mModelLike, opts?: Omit<RelationOptions, 'target'>): PropertyDecorator;
1185
942
  export function BelongsToOne(
1186
943
  first: (() => Ad4mModelLike) | RelationOptions,
1187
944
  second?: Omit<RelationOptions, 'target'>,
@@ -1197,14 +954,20 @@ export function BelongsToOne(
1197
954
  kind: 'belongsToOne',
1198
955
  maxCount: 1,
1199
956
  local: opts.local,
957
+ ...(opts.filter !== undefined && { filter: opts.filter }),
958
+ ...(opts.where && { where: opts.where }),
1200
959
  };
1201
960
 
1202
- // Read-only property (the owning side manages the link)
1203
- applyPropertyMetadata({
1204
- through: opts.through,
1205
- readOnly: true,
1206
- local: opts.local,
1207
- })(target, key);
961
+ if (opts.through) {
962
+ // Read-only property (the owning side manages the link)
963
+ applyPropertyMetadata({
964
+ through: opts.through,
965
+ readOnly: true,
966
+ local: opts.local,
967
+ })(target, key);
968
+ } else {
969
+ Object.defineProperty(target, key, { configurable: true, writable: true });
970
+ }
1208
971
  };
1209
972
  }
1210
973
 
@@ -1233,7 +996,7 @@ export function BelongsToOne(
1233
996
  * ```
1234
997
  */
1235
998
  export function BelongsToMany(opts: RelationOptions): PropertyDecorator;
1236
- export function BelongsToMany(target: () => Ad4mModelLike, opts: Omit<RelationOptions, 'target'>): PropertyDecorator;
999
+ export function BelongsToMany(target: () => Ad4mModelLike, opts?: Omit<RelationOptions, 'target'>): PropertyDecorator;
1237
1000
  export function BelongsToMany(
1238
1001
  first: (() => Ad4mModelLike) | RelationOptions,
1239
1002
  second?: Omit<RelationOptions, 'target'>,
@@ -1249,6 +1012,8 @@ export function BelongsToMany(
1249
1012
  kind: 'belongsToMany',
1250
1013
  local: opts.local,
1251
1014
  ...(opts.getter && { getter: opts.getter }),
1015
+ ...(opts.filter !== undefined && { filter: opts.filter }),
1016
+ ...(opts.where && { where: opts.where }),
1252
1017
  };
1253
1018
 
1254
1019
  // @BelongsToMany is the inverse/read-only side — do NOT generate add*/remove*/set*