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

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 (124) hide show
  1. package/jest.config.js +8 -1
  2. package/lib/index.cjs +13793 -12854
  3. package/lib/index.js +13782 -12851
  4. package/lib/src/Ad4mClient.test.d.ts +1 -0
  5. package/lib/src/Ad4mClient.test.js +1204 -0
  6. package/lib/src/Literal.test.d.ts +1 -0
  7. package/lib/src/Literal.test.js +41 -0
  8. package/lib/src/model/Ad4mModel.d.ts +528 -101
  9. package/lib/src/model/Ad4mModel.js +1670 -748
  10. package/lib/src/model/Ad4mModel.test.js +140 -156
  11. package/lib/src/model/Subject.d.ts +3 -3
  12. package/lib/src/model/Subject.js +25 -25
  13. package/lib/src/model/decorators.d.ts +259 -247
  14. package/lib/src/model/decorators.js +379 -422
  15. package/lib/src/model/mutation.d.ts +81 -0
  16. package/lib/src/model/mutation.js +317 -0
  17. package/lib/src/model/parentUtils.d.ts +32 -0
  18. package/lib/src/model/parentUtils.js +64 -0
  19. package/lib/src/model/prolog/generatePrologFacts.d.ts +36 -0
  20. package/lib/src/model/prolog/generatePrologFacts.js +139 -0
  21. package/lib/src/model/prolog/index.d.ts +1 -0
  22. package/lib/src/model/prolog/index.js +1 -0
  23. package/lib/src/model/query/ModelQueryBuilder.d.ts +82 -0
  24. package/lib/src/model/query/ModelQueryBuilder.js +115 -0
  25. package/lib/src/model/query/QueryBuilder.d.ts +101 -0
  26. package/lib/src/model/query/QueryBuilder.js +193 -0
  27. package/lib/src/model/query/SurrealQueryBuilder.d.ts +48 -0
  28. package/lib/src/model/query/SurrealQueryBuilder.js +371 -0
  29. package/lib/src/model/query/fetchInstance.d.ts +24 -0
  30. package/lib/src/model/query/fetchInstance.js +144 -0
  31. package/lib/src/model/query/hydration.d.ts +54 -0
  32. package/lib/src/model/query/hydration.js +214 -0
  33. package/lib/src/model/query/operations.d.ts +59 -0
  34. package/lib/src/model/query/operations.js +384 -0
  35. package/lib/src/model/query/snapshot.d.ts +59 -0
  36. package/lib/src/model/query/snapshot.js +106 -0
  37. package/lib/src/model/query/surrealCompiler.d.ts +42 -0
  38. package/lib/src/model/query/surrealCompiler.js +304 -0
  39. package/lib/src/model/schema/fromJSONSchema.d.ts +67 -0
  40. package/lib/src/model/schema/fromJSONSchema.js +264 -0
  41. package/lib/src/model/schema/metadata.d.ts +15 -0
  42. package/lib/src/model/schema/metadata.js +112 -0
  43. package/lib/src/model/subscription.d.ts +47 -0
  44. package/lib/src/model/subscription.js +231 -0
  45. package/lib/src/model/transaction.d.ts +27 -0
  46. package/lib/src/model/transaction.js +32 -0
  47. package/lib/src/model/types.d.ts +195 -0
  48. package/lib/src/model/types.js +8 -0
  49. package/lib/src/model/util.d.ts +6 -6
  50. package/lib/src/model/util.js +22 -22
  51. package/lib/src/neighbourhood/NeighbourhoodClient.js +31 -12
  52. package/lib/src/perspectives/PerspectiveProxy.d.ts +9 -9
  53. package/lib/src/perspectives/PerspectiveProxy.js +63 -51
  54. package/lib/src/shacl/SHACLShape.d.ts +9 -0
  55. package/lib/src/shacl/SHACLShape.js +28 -4
  56. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  57. package/lib/src/shims/type-graphql.d.ts +32 -0
  58. package/lib/src/src/Ad4mClient.d.ts +28 -0
  59. package/lib/src/src/Address.d.ts +1 -0
  60. package/lib/src/src/DID.d.ts +1 -0
  61. package/lib/src/src/Exception.d.ts +7 -0
  62. package/lib/src/src/Literal.d.ts +7 -0
  63. package/lib/src/src/PubSub.d.ts +17 -0
  64. package/lib/src/src/SmartLiteral.d.ts +12 -0
  65. package/lib/src/src/agent/Agent.d.ts +110 -0
  66. package/lib/src/src/agent/AgentClient.d.ts +62 -0
  67. package/lib/src/src/agent/AgentResolver.d.ts +30 -0
  68. package/lib/src/src/agent/AgentStatus.d.ts +8 -0
  69. package/lib/src/src/ai/AIClient.d.ts +32 -0
  70. package/lib/src/src/ai/AIResolver.d.ts +75 -0
  71. package/lib/src/src/ai/Tasks.d.ts +37 -0
  72. package/lib/src/src/buildSchema.d.ts +1 -0
  73. package/lib/src/src/expression/Expression.d.ts +28 -0
  74. package/lib/src/src/expression/ExpressionClient.d.ts +13 -0
  75. package/lib/src/src/expression/ExpressionRef.d.ts +9 -0
  76. package/lib/src/src/expression/ExpressionResolver.d.ts +10 -0
  77. package/lib/src/src/index.d.ts +35 -0
  78. package/lib/src/src/jestSetup.d.ts +1 -0
  79. package/lib/src/src/language/Icon.d.ts +4 -0
  80. package/lib/src/src/language/Language.d.ts +206 -0
  81. package/lib/src/src/language/LanguageClient.d.ts +17 -0
  82. package/lib/src/src/language/LanguageContext.d.ts +37 -0
  83. package/lib/src/src/language/LanguageHandle.d.ts +9 -0
  84. package/lib/src/src/language/LanguageMeta.d.ts +35 -0
  85. package/lib/src/src/language/LanguageRef.d.ts +6 -0
  86. package/lib/src/src/language/LanguageResolver.d.ts +19 -0
  87. package/lib/src/src/links/Links.d.ts +39 -0
  88. package/lib/src/src/links/Links.test.d.ts +1 -0
  89. package/lib/src/src/model/Ad4mModel.d.ts +1438 -0
  90. package/lib/src/src/model/Ad4mModel.test.d.ts +1 -0
  91. package/lib/src/src/model/Subject.d.ts +25 -0
  92. package/lib/src/src/model/decorators.d.ts +545 -0
  93. package/lib/src/src/model/util.d.ts +12 -0
  94. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +10 -0
  95. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +25 -0
  96. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +19 -0
  97. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +1 -0
  98. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +24 -0
  99. package/lib/src/src/perspectives/LinkQuery.d.ts +11 -0
  100. package/lib/src/src/perspectives/Perspective.d.ts +38 -0
  101. package/lib/src/src/perspectives/Perspective.test.d.ts +1 -0
  102. package/lib/src/src/perspectives/PerspectiveClient.d.ts +97 -0
  103. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +9 -0
  104. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +18 -0
  105. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +865 -0
  106. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +57 -0
  107. package/lib/src/src/runtime/RuntimeClient.d.ts +56 -0
  108. package/lib/src/src/runtime/RuntimeResolver.d.ts +132 -0
  109. package/lib/src/src/shacl/SHACLFlow.d.ts +171 -0
  110. package/lib/src/src/shacl/SHACLFlow.test.d.ts +1 -0
  111. package/lib/src/src/shacl/SHACLShape.d.ts +117 -0
  112. package/lib/src/src/shacl/SHACLShape.test.d.ts +1 -0
  113. package/lib/src/src/typeDefs.d.ts +1 -0
  114. package/lib/src/src/unwrapApolloResult.d.ts +2 -0
  115. package/lib/src/src/utils.d.ts +25 -0
  116. package/package.json +20 -24
  117. package/src/model/Ad4mModel.test.ts +132 -149
  118. package/src/model/Ad4mModel.ts +1930 -784
  119. package/src/model/Subject.ts +24 -24
  120. package/src/model/decorators.ts +626 -482
  121. package/src/model/util.ts +22 -22
  122. package/src/neighbourhood/NeighbourhoodClient.ts +32 -16
  123. package/src/perspectives/PerspectiveProxy.ts +69 -55
  124. package/src/shacl/SHACLShape.ts +33 -4
@@ -1,6 +1,91 @@
1
- import { Subject } from "./Subject";
2
1
  import { capitalize, propertyNameToSetterName, stringifyObjectLiteral } from "./util";
3
2
  import { SHACLShape } from "../shacl/SHACLShape";
3
+ /** Registry of property metadata keyed by constructor → { propName → metadata } */
4
+ const propertyRegistry = new WeakMap();
5
+ /** Registry of relation metadata keyed by constructor → { propName → metadata } */
6
+ const relationRegistry = new WeakMap();
7
+ /**
8
+ * Retrieve property metadata for a given class constructor.
9
+ * Walks the prototype chain so subclass decorators compose with parent decorators.
10
+ */
11
+ export function getPropertiesMetadata(ctor) {
12
+ const result = {};
13
+ const chain = [];
14
+ let current = ctor;
15
+ while (current && current !== Object) {
16
+ chain.unshift(current); // parent-first order
17
+ current = Object.getPrototypeOf(current);
18
+ }
19
+ for (const c of chain) {
20
+ const meta = propertyRegistry.get(c);
21
+ if (meta)
22
+ Object.assign(result, meta);
23
+ }
24
+ return result;
25
+ }
26
+ /**
27
+ * Retrieve relation metadata for a given class constructor.
28
+ * Walks the prototype chain so subclass decorators compose with parent decorators.
29
+ */
30
+ export function getRelationsMetadata(ctor) {
31
+ const result = {};
32
+ const chain = [];
33
+ let current = ctor;
34
+ while (current && current !== Object) {
35
+ chain.unshift(current);
36
+ current = Object.getPrototypeOf(current);
37
+ }
38
+ for (const c of chain) {
39
+ const meta = relationRegistry.get(c);
40
+ if (meta)
41
+ Object.assign(result, meta);
42
+ }
43
+ return result;
44
+ }
45
+ /**
46
+ * Programmatically register property metadata for a given constructor.
47
+ * Used by `fromJSONSchema()` and other dynamic model builders.
48
+ */
49
+ export function setPropertyRegistryEntry(ctor, propName, meta) {
50
+ if (!propertyRegistry.has(ctor))
51
+ propertyRegistry.set(ctor, {});
52
+ propertyRegistry.get(ctor)[propName] = meta;
53
+ }
54
+ /**
55
+ * Programmatically register relation metadata for a given constructor.
56
+ * Used by `fromJSONSchema()` and other dynamic model builders.
57
+ */
58
+ export function setRelationRegistryEntry(ctor, relName, meta) {
59
+ if (!relationRegistry.has(ctor))
60
+ relationRegistry.set(ctor, {});
61
+ relationRegistry.get(ctor)[relName] = meta;
62
+ }
63
+ /**
64
+ * Convert a model instance to a plain serializable object.
65
+ * Reads the property metadata and extracts values from the instance.
66
+ */
67
+ export function instanceToSerializable(instance) {
68
+ const ctor = instance.constructor;
69
+ const props = getPropertiesMetadata(ctor);
70
+ const result = {};
71
+ for (const [key, _meta] of Object.entries(props)) {
72
+ result[key] = instance[key];
73
+ }
74
+ return result;
75
+ }
76
+ /**
77
+ * Generate a random identifier string (lowercase alpha).
78
+ * Generate a random identifier string of the given length (lowercase alpha).
79
+ */
80
+ export function makeRandomId(length) {
81
+ let result = '';
82
+ const characters = 'abcdefghijklmnopqrstuvwxyz';
83
+ const charactersLength = characters.length;
84
+ for (let i = 0; i < length; i++) {
85
+ result += characters.charAt(Math.floor(Math.random() * charactersLength));
86
+ }
87
+ return result;
88
+ }
4
89
  export class PerspectiveAction {
5
90
  }
6
91
  export function addLink(source, predicate, target) {
@@ -15,207 +100,59 @@ export function hasLink(predicate) {
15
100
  return `triple(this, "${predicate}", _)`;
16
101
  }
17
102
  /**
18
- * Decorator for querying instances of a model class.
19
- *
20
- * @category Decorators
21
- *
22
- * @description
23
- * Allows you to define static query methods on your model class to retrieve instances based on custom conditions.
24
- * This decorator can only be applied to static async methods that return a Promise of an array of model instances.
25
- *
26
- * The query can be constrained using either:
27
- * - A `where` clause that matches property values
28
- * - A custom Prolog `condition` for more complex queries
29
- *
30
- * @example
31
- * ```typescript
32
- * class Recipe extends Ad4mModel {
33
- * @Property({ through: "recipe://name" })
34
- * name: string = "";
35
- *
36
- * @Property({ through: "recipe://rating" })
37
- * rating: number = 0;
38
- *
39
- * // Get all recipes
40
- * @InstanceQuery()
41
- * static async all(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
42
- *
43
- * // Get recipes by name
44
- * @InstanceQuery({ where: { name: "Chocolate Cake" }})
45
- * static async findByName(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
46
- *
47
- * // Get highly rated recipes using a custom condition
48
- * @InstanceQuery({ prologCondition: "triple(Instance, 'recipe://rating', Rating), Rating > 4" })
49
- * static async topRated(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
50
- * }
51
- * ```
52
- *
53
- * @param {Object} [options] - Query options
54
- * @param {object} [options.where] - Object with property-value pairs to match
55
- * @param {string} [options.prologCondition] - Custom Prolog condition for more complex queries
103
+ * Internal core implementation for registering property metadata on the prototype.
104
+ * All property decorators (@Property, @Optional, @ReadOnly) and relation decorators
105
+ * that create properties delegate to this function.
106
+ * @internal
56
107
  */
57
- export function InstanceQuery(options) {
58
- return function (target, key, descriptor) {
59
- const originalMethod = descriptor.value;
60
- if (typeof originalMethod !== "function") {
61
- throw new Error("InstanceQuery decorator can only be applied to methods");
108
+ function applyPropertyMetadata(opts) {
109
+ return function (target, key) {
110
+ // Map readOnly → internal writable for SDNA/SHACL compatibility
111
+ const writable = opts.readOnly ? false : (opts.through ? true : false);
112
+ if (opts.required && !opts.initial) {
113
+ throw new Error("SubjectProperty requires an 'initial' option if 'required' is true");
62
114
  }
63
- descriptor.value = async function (perspective) {
64
- let instances = [];
65
- //@ts-ignore
66
- let subjectClassName = target.name;
67
- let query = `subject_class("${subjectClassName}", C), instance(C, Instance)`;
68
- if (options && options.where) {
69
- for (let prop in options.where) {
70
- let value = options.where[prop];
71
- query += `, property_getter(C, Instance, "${prop}", "${value}")`;
72
- }
73
- }
74
- if (options && options.prologCondition) {
75
- query += ', ' + options.prologCondition;
76
- }
77
- // Try Prolog first
78
- try {
79
- let results = await perspective.infer(query);
80
- if (results && results !== false && typeof results !== "string" && results.length > 0) {
81
- for (let result of results) {
82
- let instance = result.Instance;
83
- let subject = new Subject(perspective, instance, subjectClassName);
84
- await subject.init();
85
- instances.push(subject);
86
- }
87
- return instances;
88
- }
89
- }
90
- catch (e) {
91
- // Prolog failed, fall through to SurrealDB
92
- }
93
- // Fallback to SurrealDB (SdnaOnly mode)
94
- // Get all instances first - pass the class constructor, not just the name
95
- let allInstances = await perspective.getAllSubjectInstances(target);
96
- // Filter by where clause if provided
97
- if (options && options.where) {
98
- let filtered = [];
99
- for (let instance of allInstances) {
100
- let matches = true;
101
- for (let prop in options.where) {
102
- let expectedValue = options.where[prop];
103
- //@ts-ignore
104
- let actualValue = await instance[prop];
105
- if (actualValue !== expectedValue) {
106
- matches = false;
107
- break;
108
- }
109
- }
110
- if (matches) {
111
- filtered.push(instance);
112
- }
113
- }
114
- return filtered;
115
- }
116
- return allInstances;
117
- };
115
+ if (!opts.through && !opts.prologGetter) {
116
+ throw new Error("SubjectProperty requires either 'through' or 'prologGetter' option");
117
+ }
118
+ // Write to WeakMap registry (keyed by constructor)
119
+ const ctor = target.constructor;
120
+ if (!propertyRegistry.has(ctor))
121
+ propertyRegistry.set(ctor, {});
122
+ propertyRegistry.get(ctor)[key] = { ...opts, writable };
123
+ if (writable) {
124
+ const value = key;
125
+ target[`set${capitalize(value)}`] = () => { };
126
+ }
127
+ Object.defineProperty(target, key, { configurable: true, writable: true });
118
128
  };
119
129
  }
120
130
  /**
121
- * Decorator for defining optional properties on model classes.
131
+ * Convenience decorator for defining optional (not required) properties.
122
132
  *
123
133
  * @category Decorators
124
134
  *
125
135
  * @description
126
- * The most flexible property decorator that allows you to define properties with full control over:
127
- * - Whether the property is required
128
- * - Whether the property is writable
129
- * - How values are stored and retrieved
130
- * - Custom getter/setter logic
131
- * - Local vs network storage
132
- *
133
- * Both @Property and @ReadOnly are specialized versions of @Optional with preset configurations.
136
+ * Equivalent to `@Property` but defaults `required` to `false` and does not
137
+ * apply `resolveLanguage` or `initial` defaults. Use this when a property
138
+ * may or may not have a value, and you want full control over its configuration.
134
139
  *
135
140
  * @example
136
141
  * ```typescript
137
142
  * class Recipe extends Ad4mModel {
138
- * // Basic optional property
139
- * @Optional({
140
- * through: "recipe://description"
141
- * })
143
+ * @Optional({ through: "recipe://description" })
142
144
  * description?: string;
143
- *
144
- * // Optional property with custom initial value
145
- * @Optional({
146
- * through: "recipe://status",
147
- * initial: "recipe://draft",
148
- * required: true
149
- * })
150
- * status: string = "";
151
- *
152
- * // Read-only property with custom getter
153
- * @Optional({
154
- * through: "recipe://rating",
155
- * writable: false,
156
- * getter: `
157
- * findall(Rating, triple(Base, "recipe://user_rating", Rating), Ratings),
158
- * sum_list(Ratings, Sum),
159
- * length(Ratings, Count),
160
- * Value is Sum / Count
161
- * `
162
- * })
163
- * averageRating: number = 0;
164
- *
165
- * // Property that resolves to a Literal and is stored locally
166
- * @Optional({
167
- * through: "recipe://notes",
168
- * resolveLanguage: "literal",
169
- * local: true
170
- * })
171
- * notes?: string;
172
- *
173
- * // Property with custom getter and setter logic
174
- * @Optional({
175
- * through: "recipe://ingredients",
176
- * getter: `
177
- * triple(Base, "recipe://ingredients", RawValue),
178
- * atom_json_term(RawValue, Value)
179
- * `,
180
- * setter: `
181
- * atom_json_term(Value, JsonValue),
182
- * Actions = [{"action": "setSingleTarget", "source": "this", "predicate": "recipe://ingredients", "target": JsonValue}]
183
- * `
184
- * })
185
- * ingredients: string[] = [];
186
145
  * }
187
146
  * ```
188
147
  *
189
- * @param {PropertyOptions} opts - Property configuration options
190
- * @param {string} opts.through - The predicate URI for the property
191
- * @param {string} [opts.initial] - Initial value (required if property is required)
192
- * @param {boolean} [opts.required] - Whether the property must have a value
193
- * @param {boolean} [opts.writable=true] - Whether the property can be modified
194
- * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
195
- * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
196
- * @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
197
- * @param {boolean} [opts.local] - Whether the property should only be stored locally
148
+ * @param {PropertyOptions} opts - Property configuration (same options as @Property)
198
149
  */
199
150
  export function Optional(opts) {
200
- return function (target, key) {
201
- if (typeof opts.writable === "undefined" && opts.through) {
202
- opts.writable = true;
203
- }
204
- if (opts.required && !opts.initial) {
205
- throw new Error("SubjectProperty requires an 'initial' option if 'required' is true");
206
- }
207
- if (!opts.through && !opts.prologGetter) {
208
- throw new Error("SubjectProperty requires either 'through' or 'prologGetter' option");
209
- }
210
- target["__properties"] = target["__properties"] || {};
211
- target["__properties"][key] = target["__properties"][key] || {};
212
- target["__properties"][key] = { ...target["__properties"][key], ...opts };
213
- if (opts.writable) {
214
- const value = key;
215
- target[`set${capitalize(value)}`] = () => { };
216
- }
217
- Object.defineProperty(target, key, { configurable: true, writable: true });
218
- };
151
+ return applyPropertyMetadata({
152
+ ...opts,
153
+ required: opts.required ?? false,
154
+ readOnly: opts.readOnly ?? false,
155
+ });
219
156
  }
220
157
  /**
221
158
  * Decorator for defining flags on model classes.
@@ -281,112 +218,24 @@ export function Flag(opts) {
281
218
  if (!opts.value) {
282
219
  throw new Error("SubjectFlag requires a 'value' option");
283
220
  }
284
- target["__properties"] = target["__properties"] || {};
285
- target["__properties"][key] = target["__properties"][key] || {};
286
- target["__properties"][key] = {
287
- ...target["__properties"][key],
221
+ const entry = {
288
222
  through: opts.through,
289
223
  required: true,
290
224
  initial: opts.value,
291
- flag: true
225
+ flag: true,
226
+ readOnly: true,
227
+ writable: false,
292
228
  };
229
+ // Write to WeakMap registry
230
+ const ctor = target.constructor;
231
+ if (!propertyRegistry.has(ctor))
232
+ propertyRegistry.set(ctor, {});
233
+ propertyRegistry.get(ctor)[key] = entry;
293
234
  // @ts-ignore
294
235
  target[key] = opts.value;
295
236
  Object.defineProperty(target, key, { configurable: true, writable: true });
296
237
  };
297
238
  }
298
- /**
299
- * Decorator for defining collections on model classes.
300
- *
301
- * @category Decorators
302
- *
303
- * @description
304
- * Defines a property that represents a collection of values linked to the model instance.
305
- * Collections are always arrays and support operations for adding, removing, and setting values.
306
- *
307
- * For each collection property, the following methods are automatically generated:
308
- * - `addX(value)` - Add a value to the collection
309
- * - `removeX(value)` - Remove a value from the collection
310
- * - `setCollectionX(values)` - Replace all values in the collection
311
- *
312
- * Where X is the capitalized property name.
313
- *
314
- * Collections can be filtered using the `where` option to only include values that:
315
- * - Are instances of a specific model class
316
- * - Match a custom Prolog condition
317
- *
318
- * @example
319
- * ```typescript
320
- * class Recipe extends Ad4mModel {
321
- * // Basic collection of ingredients
322
- * @Collection({
323
- * through: "recipe://ingredient"
324
- * })
325
- * ingredients: string[] = [];
326
- *
327
- * // Collection that only includes instances of another model
328
- * @Collection({
329
- * through: "recipe://comment",
330
- * where: { isInstance: Comment }
331
- * })
332
- * comments: string[] = [];
333
- *
334
- * // Collection with custom Prolog filter condition
335
- * @Collection({
336
- * through: "recipe://step",
337
- * where: { prologCondition: `triple(Target, "step://order", Order), Order < 3` }
338
- * })
339
- * firstSteps: string[] = [];
340
- *
341
- * // Collection with custom SurrealDB filter condition
342
- * @Collection({
343
- * through: "recipe://entries",
344
- * where: { condition: `WHERE in.uri = Target AND predicate = 'recipe://has_ingredient' AND out.uri = 'recipe://test')`
345
- * })
346
- * ingredients: string[] = [];
347
- *
348
- * // Local-only collection not shared with network
349
- * @Collection({
350
- * through: "recipe://note",
351
- * local: true
352
- * })
353
- * privateNotes: string[] = [];
354
- * }
355
- *
356
- * // Using the generated methods:
357
- * const recipe = new Recipe(perspective);
358
- * await recipe.addIngredients("ingredient://flour");
359
- * await recipe.removeIngredients("ingredient://sugar");
360
- * await recipe.setCollectionIngredients(["ingredient://butter", "ingredient://eggs"]);
361
- * ```
362
- *
363
- * @param {CollectionOptions} opts - Collection configuration
364
- * @param {string} opts.through - The predicate URI for collection links
365
- * @param {WhereOptions} [opts.where] - Filter conditions for collection values
366
- * @param {any} [opts.where.isInstance] - Model class to filter instances by
367
- * @param {string} [opts.where.prologCondition] - Custom Prolog condition for filtering
368
- * @param {boolean} [opts.local] - Whether collection links are stored locally only
369
- */
370
- export function Collection(opts) {
371
- return function (target, key) {
372
- target["__collections"] = target["__collections"] || {};
373
- target["__collections"][key] = opts;
374
- const value = key;
375
- target[`add${capitalize(value)}`] = () => { };
376
- target[`remove${capitalize(value)}`] = () => { };
377
- target[`setCollection${capitalize(value)}`] = () => { };
378
- Object.defineProperty(target, key, { configurable: true, writable: true });
379
- };
380
- }
381
- export function makeRandomPrologAtom(length) {
382
- let result = '';
383
- let characters = 'abcdefghijklmnopqrstuvwxyz';
384
- let charactersLength = characters.length;
385
- for (let i = 0; i < length; i++) {
386
- result += characters.charAt(Math.floor(Math.random() * charactersLength));
387
- }
388
- return result;
389
- }
390
239
  /**
391
240
  * Decorator for defining model classes in AD4M.
392
241
  *
@@ -399,13 +248,13 @@ export function makeRandomPrologAtom(length) {
399
248
  *
400
249
  * This decorator:
401
250
  * - Registers the class with a unique name in the AD4M system
402
- * - Generates the necessary SDNA code for the model's properties and collections
403
- * - Enables the use of other model decorators (@Property, @Collection, etc.)
251
+ * - Generates the necessary SDNA code for the model's properties and relations
252
+ * - Enables the use of other model decorators (@Property, @HasMany, etc.)
404
253
  * - Provides static query methods through the Ad4mModel base class
405
254
  *
406
255
  * @example
407
256
  * ```typescript
408
- * @ModelOptions({ name: "Recipe" })
257
+ * @Model({ name: "Recipe" })
409
258
  * class Recipe extends Ad4mModel {
410
259
  * @Property({
411
260
  * through: "recipe://name",
@@ -413,7 +262,7 @@ export function makeRandomPrologAtom(length) {
413
262
  * })
414
263
  * name: string = "";
415
264
  *
416
- * @Collection({ through: "recipe://ingredient" })
265
+ * @HasMany({ through: "recipe://ingredient" })
417
266
  * ingredients: string[] = [];
418
267
  *
419
268
  * // Static query methods from Ad4mModel:
@@ -438,10 +287,10 @@ export function makeRandomPrologAtom(length) {
438
287
  * await perspective.ensureSDNASubjectClass(Recipe);
439
288
  * ```
440
289
  *
441
- * @param {ModelOptionsOptions} opts - Model configuration
290
+ * @param {ModelConfig} opts - Model configuration
442
291
  * @param {string} opts.name - Unique name for the model class in AD4M
443
292
  */
444
- export function ModelOptions(opts) {
293
+ export function Model(opts) {
445
294
  return function (target) {
446
295
  target.prototype.className = opts.name;
447
296
  target.className = opts.name;
@@ -449,7 +298,7 @@ export function ModelOptions(opts) {
449
298
  let sdna = "";
450
299
  let subjectName = opts.name;
451
300
  let obj = target.prototype;
452
- let uuid = makeRandomPrologAtom(8);
301
+ let uuid = makeRandomId(8);
453
302
  sdna += `subject_class("${subjectName}", ${uuid}).\n`;
454
303
  let classRemoverActions = [];
455
304
  let constructorActions = [];
@@ -461,7 +310,7 @@ export function ModelOptions(opts) {
461
310
  instanceConditions = instanceConditions.concat(obj.isSubjectInstance);
462
311
  }
463
312
  let propertiesCode = [];
464
- let properties = obj.__properties || {};
313
+ let properties = getPropertiesMetadata(target);
465
314
  for (let property in properties) {
466
315
  let propertyCode = `property(${uuid}, "${property}").\n`;
467
316
  let { through, initial, required, resolveLanguage, writable, flag, prologGetter, prologSetter, local } = properties[property];
@@ -500,12 +349,18 @@ export function ModelOptions(opts) {
500
349
  }
501
350
  }
502
351
  propertiesCode.push(propertyCode);
503
- if (initial) {
352
+ // Auto-derive effectiveInitial for required, writable, non-flag properties
353
+ // so constructor/destructor always handle the property link.
354
+ // Optional properties (required: false) are excluded — they should
355
+ // remain unset (undefined) until explicitly assigned.
356
+ const effectiveInitial = initial
357
+ ?? (required && writable && !flag && through ? "literal://string:" : undefined);
358
+ if (effectiveInitial) {
504
359
  constructorActions.push({
505
360
  action: "addLink",
506
361
  source: "this",
507
362
  predicate: through,
508
- target: initial,
363
+ target: effectiveInitial,
509
364
  });
510
365
  classRemoverActions.push({
511
366
  action: "removeLink",
@@ -515,69 +370,39 @@ export function ModelOptions(opts) {
515
370
  });
516
371
  }
517
372
  }
518
- let collectionsCode = [];
519
- let collections = obj.__collections || {};
520
- for (let collection in collections) {
521
- let collectionCode = `collection(${uuid}, "${collection}").\n`;
522
- let { through, where, local } = collections[collection];
373
+ let relationsCode = [];
374
+ const allRelationsMeta = getRelationsMetadata(target);
375
+ const relations = Object.fromEntries(Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));
376
+ for (let relation in relations) {
377
+ let relationCode = `collection(${uuid}, "${relation}").\n`;
378
+ let { predicate: through, local } = relations[relation];
523
379
  if (through) {
524
- if (where) {
525
- if (!where.isInstance && !where.prologCondition && !where.condition) {
526
- throw "'where' needs one of 'isInstance', 'prologCondition', or 'condition'";
527
- }
528
- let conditions = [];
529
- if (where.isInstance) {
530
- let otherClass;
531
- if (where.isInstance.name) {
532
- otherClass = where.isInstance.name;
533
- }
534
- else {
535
- otherClass = where.isInstance;
536
- }
537
- conditions.push(`instance(OtherClass, Target), subject_class("${otherClass}", OtherClass)`);
538
- }
539
- if (where.prologCondition) {
540
- conditions.push(where.prologCondition);
541
- }
542
- // If there are Prolog conditions (isInstance or prologCondition), use setof with conditions
543
- // If only condition is present, use simple findall (SurrealDB will filter later)
544
- if (conditions.length > 0) {
545
- const conditionString = conditions.join(", ");
546
- collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- setof(Target, (triple(Base, "${through}", Target), ${conditionString}), List).\n`;
547
- }
548
- else {
549
- // Only SurrealDB condition present (no Prolog filtering)
550
- collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- findall(C, triple(Base, "${through}", C), List).\n`;
551
- }
552
- }
553
- else {
554
- collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- findall(C, triple(Base, "${through}", C), List).\n`;
555
- }
556
- let collectionAdderAction = [{
380
+ relationCode += `collection_getter(${uuid}, Base, "${relation}", List) :- findall(C, triple(Base, "${through}", C), List).\n`;
381
+ let relationAdderAction = [{
557
382
  action: "addLink",
558
383
  source: "this",
559
384
  predicate: through,
560
385
  target: "value",
561
386
  ...(local && { local: true })
562
387
  }];
563
- let collectionRemoverAction = [{
388
+ let relationRemoverAction = [{
564
389
  action: "removeLink",
565
390
  source: "this",
566
391
  predicate: through,
567
392
  target: "value",
568
393
  }];
569
- let collectionSetterAction = [{
394
+ let relationSetterAction = [{
570
395
  action: "collectionSetter",
571
396
  source: "this",
572
397
  predicate: through,
573
398
  target: "value",
574
399
  ...(local && { local: true })
575
400
  }];
576
- collectionCode += `collection_adder(${uuid}, "${collection}", '${stringifyObjectLiteral(collectionAdderAction)}').\n`;
577
- collectionCode += `collection_remover(${uuid}, "${collection}", '${stringifyObjectLiteral(collectionRemoverAction)}').\n`;
578
- collectionCode += `collection_setter(${uuid}, "${collection}", '${stringifyObjectLiteral(collectionSetterAction)}').\n`;
401
+ relationCode += `collection_adder(${uuid}, "${relation}", '${stringifyObjectLiteral(relationAdderAction)}').\n`;
402
+ relationCode += `collection_remover(${uuid}, "${relation}", '${stringifyObjectLiteral(relationRemoverAction)}').\n`;
403
+ relationCode += `collection_setter(${uuid}, "${relation}", '${stringifyObjectLiteral(relationSetterAction)}').\n`;
579
404
  }
580
- collectionsCode.push(collectionCode);
405
+ relationsCode.push(relationCode);
581
406
  }
582
407
  let subjectContructorJSONString = stringifyObjectLiteral(constructorActions);
583
408
  sdna += `constructor(${uuid}, '${subjectContructorJSONString}').\n`;
@@ -590,7 +415,7 @@ export function ModelOptions(opts) {
590
415
  sdna += "\n";
591
416
  sdna += propertiesCode.join("\n");
592
417
  sdna += "\n";
593
- sdna += collectionsCode.join("\n");
418
+ sdna += relationsCode.join("\n");
594
419
  return {
595
420
  sdna,
596
421
  name: subjectName
@@ -600,10 +425,11 @@ export function ModelOptions(opts) {
600
425
  target.generateSHACL = function () {
601
426
  const subjectName = opts.name;
602
427
  const obj = target.prototype;
603
- // Determine namespace from first property or collection, or use default
428
+ // Determine namespace from first property or relation, or use default
604
429
  let namespace = "ad4m://";
605
- const properties = obj.__properties || {};
606
- const collections = obj.__collections || {};
430
+ const properties = getPropertiesMetadata(target);
431
+ const allRelationsMeta2 = getRelationsMetadata(target);
432
+ const relations = Object.fromEntries(Object.entries(allRelationsMeta2).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));
607
433
  // Try properties first
608
434
  if (Object.keys(properties).length > 0) {
609
435
  const firstProp = properties[Object.keys(properties)[0]];
@@ -615,11 +441,11 @@ export function ModelOptions(opts) {
615
441
  }
616
442
  }
617
443
  }
618
- // Fall back to collections if no properties
619
- else if (Object.keys(collections).length > 0) {
620
- const firstColl = collections[Object.keys(collections)[0]];
621
- if (firstColl.through) {
622
- const match = firstColl.through.match(/^([^:]+:\/\/)/);
444
+ // Fall back to relations if no properties
445
+ else if (Object.keys(relations).length > 0) {
446
+ const firstRel = relations[Object.keys(relations)[0]];
447
+ if (firstRel.predicate) {
448
+ const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
623
449
  if (match) {
624
450
  namespace = match[1];
625
451
  }
@@ -629,6 +455,16 @@ export function ModelOptions(opts) {
629
455
  const shapeUri = `${namespace}${subjectName}Shape`;
630
456
  const targetClass = `${namespace}${subjectName}`;
631
457
  const shape = new SHACLShape(shapeUri, targetClass);
458
+ // Detect @Model inheritance — if the parent class also has
459
+ // generateSHACL it is itself a @Model and we reference its shape
460
+ // via sh:node so SHACL validators can walk the hierarchy.
461
+ const parentCtor = Object.getPrototypeOf(target);
462
+ if (parentCtor && typeof parentCtor.generateSHACL === 'function') {
463
+ const parentSHACL = parentCtor.generateSHACL();
464
+ if (parentSHACL?.shape?.nodeShapeUri) {
465
+ shape.addParentShape(parentSHACL.shape.nodeShapeUri);
466
+ }
467
+ }
632
468
  // === Extract Constructor Actions (same logic as generateSDNA) ===
633
469
  let constructorActions = [];
634
470
  if (obj.subjectConstructor && obj.subjectConstructor.length) {
@@ -668,10 +504,8 @@ export function ModelOptions(opts) {
668
504
  propShape.minCount = 1;
669
505
  }
670
506
  // Single-valued properties get maxCount 1
671
- // (collections are handled separately below)
672
- if (!propMeta.collection) {
673
- propShape.maxCount = 1;
674
- }
507
+ // (relations are handled separately below)
508
+ propShape.maxCount = 1;
675
509
  // Flag properties have fixed value
676
510
  if (propMeta.flag && propMeta.initial) {
677
511
  propShape.hasValue = propMeta.initial;
@@ -687,8 +521,8 @@ export function ModelOptions(opts) {
687
521
  propShape.resolveLanguage = propMeta.resolveLanguage;
688
522
  }
689
523
  // === Extract Setter Actions (same logic as generateSDNA) ===
690
- if (propMeta.setter) {
691
- // Custom setter defined - not yet supported in SHACL
524
+ if (propMeta.prologSetter) {
525
+ // Custom Prolog setter defined - not yet supported in SHACL
692
526
  console.warn(`[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
693
527
  `The property will be created without setter actions. Consider using standard writable properties or provide explicit SHACL JSON.`);
694
528
  // TODO: Parse custom Prolog setter to extract actions
@@ -706,12 +540,18 @@ export function ModelOptions(opts) {
706
540
  }
707
541
  }
708
542
  // Add to constructor actions if property has initial value
709
- if (propMeta.initial) {
543
+ // Auto-derive effectiveInitial for required, writable, non-flag properties.
544
+ // Optional properties (required: false) are excluded — they should
545
+ // remain unset (undefined) until explicitly assigned.
546
+ const effectiveInitial = propMeta.initial
547
+ ?? (propMeta.required && propMeta.writable && !propMeta.flag && propMeta.through
548
+ ? "literal://string:" : undefined);
549
+ if (effectiveInitial) {
710
550
  constructorActions.push({
711
551
  action: "addLink",
712
552
  source: "this",
713
553
  predicate: propMeta.through,
714
- target: propMeta.initial,
554
+ target: effectiveInitial,
715
555
  });
716
556
  // Add to destructor actions
717
557
  destructorActions.push({
@@ -723,63 +563,50 @@ export function ModelOptions(opts) {
723
563
  }
724
564
  shape.addProperty(propShape);
725
565
  }
726
- // Convert collections to SHACL property shapes
727
- // (collections variable already declared above for namespace inference)
728
- for (const collName in collections) {
729
- const collMeta = collections[collName];
730
- if (!collMeta.through)
566
+ // Convert relations to SHACL property shapes
567
+ // (relations variable already declared above for namespace inference)
568
+ for (const relName in relations) {
569
+ const relMeta = relations[relName];
570
+ if (!relMeta.predicate)
731
571
  continue;
732
- const collShape = {
733
- name: collName,
734
- path: collMeta.through,
735
- // Collections have no maxCount (unlimited)
572
+ const relShape = {
573
+ name: relName,
574
+ path: relMeta.predicate,
575
+ // Relations have no maxCount (unlimited)
736
576
  // minCount defaults to 0 (optional)
737
577
  };
738
- // Determine if it's a reference (IRI) or literal
739
- // Collections typically contain references (IRIs) to other entities
740
- // They're literals only if explicitly marked or contain primitive values
741
- if (collMeta.where?.isInstance) {
742
- // Collection of typed entities - definitely IRIs
743
- collShape.nodeKind = 'IRI';
744
- }
745
- else {
746
- // Default to IRI for collections (most common case)
747
- // Literal collections are rare and would need explicit marking
748
- collShape.nodeKind = 'IRI';
749
- }
578
+ // Determine node kind — relations typically contain IRIs
579
+ relShape.nodeKind = 'IRI';
750
580
  // AD4M-specific metadata
751
- if (collMeta.local !== undefined) {
752
- collShape.local = collMeta.local;
753
- }
754
- if (collMeta.writable !== undefined) {
755
- collShape.writable = collMeta.writable;
581
+ if (relMeta.local !== undefined) {
582
+ relShape.local = relMeta.local;
756
583
  }
757
- // === Extract Collection Actions (adder/remover) ===
758
- // Adder action - adds a link to the collection
759
- collShape.adder = [{
584
+ // === Extract Relation Actions (adder/remover) ===
585
+ // Adder action - adds a link to the relation
586
+ relShape.adder = [{
760
587
  action: "addLink",
761
588
  source: "this",
762
- predicate: collMeta.through,
589
+ predicate: relMeta.predicate,
763
590
  target: "value",
764
- ...(collMeta.local && { local: true })
591
+ ...(relMeta.local && { local: true })
765
592
  }];
766
- // Remover action - removes a link from the collection
767
- collShape.remover = [{
593
+ // Remover action - removes a link from the relation
594
+ relShape.remover = [{
768
595
  action: "removeLink",
769
596
  source: "this",
770
- predicate: collMeta.through,
597
+ predicate: relMeta.predicate,
771
598
  target: "value",
772
- ...(collMeta.local && { local: true })
599
+ ...(relMeta.local && { local: true })
773
600
  }];
774
- shape.addProperty(collShape);
775
- }
776
- // Set constructor and destructor actions on the shape
777
- if (constructorActions.length > 0) {
778
- shape.setConstructorActions(constructorActions);
779
- }
780
- if (destructorActions.length > 0) {
781
- shape.setDestructorActions(destructorActions);
601
+ shape.addProperty(relShape);
782
602
  }
603
+ // Always set constructor and destructor actions on the shape, even
604
+ // when empty. An empty array serialises to `literal://string:[]`
605
+ // which the Rust executor parses as a valid (no-op) command list,
606
+ // avoiding "No SHACL constructor found" errors for models whose
607
+ // properties are all optional and have no @Flag.
608
+ shape.setConstructorActions(constructorActions);
609
+ shape.setDestructorActions(destructorActions);
783
610
  return {
784
611
  shape,
785
612
  name: subjectName
@@ -789,66 +616,76 @@ export function ModelOptions(opts) {
789
616
  };
790
617
  }
791
618
  /**
792
- * Decorator for defining required and writable properties on model classes.
619
+ * The primary property decorator for AD4M model classes.
793
620
  *
794
621
  * @category Decorators
795
622
  *
796
623
  * @description
797
- * A convenience decorator that defines a required property that must have an initial value and is writable by default.
798
- * This is equivalent to using @Optional with `required: true` and `writable: true`.
624
+ * The core property decorator with smart defaults. All other property decorators
625
+ * (@Optional, @ReadOnly) are thin wrappers that adjust these defaults.
626
+ *
627
+ * Smart defaults (all overridable):
628
+ * - `required` → `false`
629
+ * - `readOnly` → `false`
630
+ * - `resolveLanguage` → `"literal"`
631
+ * - `initial` → `undefined` (no link created until a value is explicitly set)
799
632
  *
800
- * Properties defined with this decorator:
801
- * - Must have a value (required)
802
- * - Can be modified after creation (writable)
803
- * - Default to "literal://string:uninitialized" if no initial value is provided
633
+ * Properties are optional by default. When a model instance is created without
634
+ * providing a value for an optional property, no link is added to the graph.
635
+ * Set `required: true` explicitly when a property must always be present (this
636
+ * also adds a `"literal://string:uninitialized"` sentinel as the initial value
637
+ * so that the SDNA constructor creates a placeholder link).
804
638
  *
805
639
  * @example
806
640
  * ```typescript
807
641
  * class User extends Ad4mModel {
808
- * // Basic required property with default initial value
642
+ * // Optional property (default) — no link created until a value is set
809
643
  * @Property({
810
644
  * through: "user://name"
811
645
  * })
812
646
  * name: string = "";
813
647
  *
814
- * // Required property with custom initial value
648
+ * // Explicitly required property with sentinel initial value
815
649
  * @Property({
816
650
  * through: "user://status",
817
- * initial: "user://active"
651
+ * required: true
818
652
  * })
819
653
  * status: string = "";
820
654
  *
821
- * // Required property with literal resolution
655
+ * // Required property with custom initial value
822
656
  * @Property({
823
- * through: "user://bio",
824
- * resolveLanguage: "literal"
657
+ * through: "user://role",
658
+ * required: true,
659
+ * initial: "user://member"
825
660
  * })
826
- * bio: string = "";
661
+ * role: string = "";
827
662
  *
828
- * // Required property with custom getter/setter
663
+ * // Optional property with literal resolution
829
664
  * @Property({
830
- * through: "user://age",
831
- * getter: `triple(Base, "user://birthYear", Year), Value is 2024 - Year`,
832
- * setter: `Year is 2024 - Value, Actions = [{"action": "setSingleTarget", "source": "this", "predicate": "user://birthYear", "target": Year}]`
665
+ * through: "user://bio",
666
+ * resolveLanguage: "literal"
833
667
  * })
834
- * age: number = 0;
668
+ * bio: string = "";
835
669
  * }
836
670
  * ```
837
671
  *
838
672
  * @param {PropertyOptions} opts - Property configuration
839
673
  * @param {string} opts.through - The predicate URI for the property
840
- * @param {string} [opts.initial] - Initial value (defaults to "literal://string:uninitialized")
674
+ * @param {boolean} [opts.required=false] - Whether the property is required (adds query filters and sentinel initial value)
675
+ * @param {string} [opts.initial] - Initial value (defaults to "literal://string:uninitialized" when required)
841
676
  * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
842
677
  * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
843
678
  * @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
844
679
  * @param {boolean} [opts.local] - Whether the property should only be stored locally
845
680
  */
846
681
  export function Property(opts) {
847
- return Optional({
682
+ const required = opts.required ?? false;
683
+ return applyPropertyMetadata({
848
684
  ...opts,
849
- required: true,
850
- writable: true,
851
- initial: opts.initial || "literal://string:uninitialized"
685
+ required,
686
+ readOnly: opts.readOnly ?? false,
687
+ resolveLanguage: opts.resolveLanguage ?? "literal",
688
+ initial: opts.initial ?? (required ? "literal://string:uninitialized" : undefined),
852
689
  });
853
690
  }
854
691
  /**
@@ -857,8 +694,8 @@ export function Property(opts) {
857
694
  * @category Decorators
858
695
  *
859
696
  * @description
860
- * A convenience decorator that defines a property that can only be read and cannot be modified after initialization.
861
- * This is equivalent to using @Optional with `writable: false`.
697
+ * A convenience decorator that defines a read-only property.
698
+ * Equivalent to `@Property` with `readOnly: true`.
862
699
  *
863
700
  * Read-only properties are ideal for:
864
701
  * - Computed or derived values
@@ -907,8 +744,128 @@ export function Property(opts) {
907
744
  * @param {boolean} [opts.local] - Whether the property should only be stored locally
908
745
  */
909
746
  export function ReadOnly(opts) {
910
- return Optional({
747
+ return Property({
911
748
  ...opts,
912
- writable: false
749
+ readOnly: true,
913
750
  });
914
751
  }
752
+ /**
753
+ * Resolve overloaded relation decorator arguments.
754
+ * Supports two calling conventions:
755
+ * @HasMany({ through: "...", target: () => X }) — single options object
756
+ * @HasMany(() => X, { through: "..." }) — target thunk + options
757
+ * @internal
758
+ */
759
+ function resolveRelationArgs(first, second) {
760
+ const opts = typeof first === 'function'
761
+ ? { ...second, target: first }
762
+ : first;
763
+ if (!opts.through) {
764
+ throw new Error(`Relation decorator requires a { through: '...' } option specifying the predicate URI.`);
765
+ }
766
+ return opts;
767
+ }
768
+ export function HasMany(first, second) {
769
+ const opts = resolveRelationArgs(first, second);
770
+ return function (target, key) {
771
+ // --- relation registry ---
772
+ const ctor = target.constructor;
773
+ if (!relationRegistry.has(ctor))
774
+ relationRegistry.set(ctor, {});
775
+ const map = relationRegistry.get(ctor);
776
+ map[key] = {
777
+ predicate: opts.through,
778
+ target: opts.target,
779
+ kind: 'hasMany',
780
+ local: opts.local,
781
+ ...(opts.getter && { getter: opts.getter }),
782
+ };
783
+ // Add prototype methods for add/remove/set
784
+ const relKey = key;
785
+ target[`add${capitalize(relKey)}`] = async function (arg, batchId) {
786
+ return this.addRelationValue(relKey, arg, batchId);
787
+ };
788
+ target[`remove${capitalize(relKey)}`] = async function (arg, batchId) {
789
+ return this.removeRelationValue(relKey, arg, batchId);
790
+ };
791
+ target[`set${capitalize(relKey)}`] = async function (arg, batchId) {
792
+ return this.setRelationValues(relKey, arg, batchId);
793
+ };
794
+ Object.defineProperty(target, relKey, { configurable: true, writable: true });
795
+ };
796
+ }
797
+ export function HasOne(first, second) {
798
+ const opts = resolveRelationArgs(first, second);
799
+ return function (target, key) {
800
+ const ctor = target.constructor;
801
+ if (!relationRegistry.has(ctor))
802
+ relationRegistry.set(ctor, {});
803
+ const map = relationRegistry.get(ctor);
804
+ map[key] = {
805
+ predicate: opts.through,
806
+ target: opts.target,
807
+ kind: 'hasOne',
808
+ maxCount: 1,
809
+ local: opts.local,
810
+ };
811
+ // Register as a writable property
812
+ applyPropertyMetadata({
813
+ through: opts.through,
814
+ readOnly: false,
815
+ local: opts.local,
816
+ })(target, key);
817
+ // Add prototype methods for add/remove/set (mirroring @HasMany)
818
+ const relKey = key;
819
+ target[`add${capitalize(relKey)}`] = async function (arg) {
820
+ return this.addRelationValue(relKey, arg);
821
+ };
822
+ target[`remove${capitalize(relKey)}`] = async function (arg) {
823
+ return this.removeRelationValue(relKey, arg);
824
+ };
825
+ target[`set${capitalize(relKey)}`] = async function (arg) {
826
+ return this.setRelationValues(relKey, arg);
827
+ };
828
+ };
829
+ }
830
+ export function BelongsToOne(first, second) {
831
+ const opts = resolveRelationArgs(first, second);
832
+ return function (target, key) {
833
+ const ctor = target.constructor;
834
+ if (!relationRegistry.has(ctor))
835
+ relationRegistry.set(ctor, {});
836
+ const map = relationRegistry.get(ctor);
837
+ map[key] = {
838
+ predicate: opts.through,
839
+ target: opts.target,
840
+ kind: 'belongsToOne',
841
+ maxCount: 1,
842
+ local: opts.local,
843
+ };
844
+ // Read-only property (the owning side manages the link)
845
+ applyPropertyMetadata({
846
+ through: opts.through,
847
+ readOnly: true,
848
+ local: opts.local,
849
+ })(target, key);
850
+ };
851
+ }
852
+ export function BelongsToMany(first, second) {
853
+ const opts = resolveRelationArgs(first, second);
854
+ return function (target, key) {
855
+ const ctor = target.constructor;
856
+ if (!relationRegistry.has(ctor))
857
+ relationRegistry.set(ctor, {});
858
+ const map = relationRegistry.get(ctor);
859
+ map[key] = {
860
+ predicate: opts.through,
861
+ target: opts.target,
862
+ kind: 'belongsToMany',
863
+ local: opts.local,
864
+ ...(opts.getter && { getter: opts.getter }),
865
+ };
866
+ // @BelongsToMany is the inverse/read-only side — do NOT generate add*/remove*/set*
867
+ // prototype methods. Mutation must go through the owning side's @HasMany decorator.
868
+ const relKey = key;
869
+ Object.defineProperty(target, relKey, { configurable: true, writable: true });
870
+ };
871
+ }