@coasys/ad4m 0.10.0 → 0.10.1-multi-user-1

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 (72) hide show
  1. package/lib/index.cjs +3730 -906
  2. package/lib/index.js +3722 -902
  3. package/lib/src/Ad4mClient.js +2 -1
  4. package/lib/src/Literal.js +4 -1
  5. package/lib/src/agent/Agent.d.ts +12 -0
  6. package/lib/src/agent/Agent.js +48 -0
  7. package/lib/src/agent/AgentClient.d.ts +3 -1
  8. package/lib/src/agent/AgentClient.js +23 -0
  9. package/lib/src/ai/AIClient.d.ts +8 -2
  10. package/lib/src/ai/AIClient.js +25 -14
  11. package/lib/src/ai/AIResolver.d.ts +25 -6
  12. package/lib/src/ai/AIResolver.js +102 -18
  13. package/lib/src/index.d.ts +4 -3
  14. package/lib/src/index.js +4 -3
  15. package/lib/src/language/Language.d.ts +12 -1
  16. package/lib/src/model/Ad4mModel.d.ts +622 -0
  17. package/lib/src/model/Ad4mModel.js +1118 -0
  18. package/lib/src/{subject → model}/Subject.d.ts +2 -2
  19. package/lib/src/{subject → model}/Subject.js +18 -18
  20. package/lib/src/model/decorators.d.ts +502 -0
  21. package/lib/src/model/decorators.js +683 -0
  22. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +2 -2
  23. package/lib/src/neighbourhood/NeighbourhoodClient.js +13 -10
  24. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +2 -2
  25. package/lib/src/neighbourhood/NeighbourhoodProxy.js +4 -4
  26. package/lib/src/neighbourhood/NeighbourhoodProxy.test.d.ts +1 -0
  27. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +73 -0
  28. package/lib/src/neighbourhood/NeighbourhoodResolver.d.ts +2 -2
  29. package/lib/src/neighbourhood/NeighbourhoodResolver.js +6 -4
  30. package/lib/src/perspectives/PerspectiveClient.d.ts +23 -11
  31. package/lib/src/perspectives/PerspectiveClient.js +147 -51
  32. package/lib/src/perspectives/PerspectiveProxy.d.ts +494 -54
  33. package/lib/src/perspectives/PerspectiveProxy.js +684 -67
  34. package/lib/src/perspectives/PerspectiveResolver.d.ts +24 -9
  35. package/lib/src/perspectives/PerspectiveResolver.js +151 -46
  36. package/lib/src/runtime/RuntimeClient.d.ts +11 -2
  37. package/lib/src/runtime/RuntimeClient.js +94 -0
  38. package/lib/src/runtime/RuntimeResolver.d.ts +36 -1
  39. package/lib/src/runtime/RuntimeResolver.js +193 -0
  40. package/lib/src/schema.gql +65 -16
  41. package/lib/src/typeDefs.js +65 -16
  42. package/package.json +4 -3
  43. package/src/Ad4mClient.test.ts +51 -19
  44. package/src/Ad4mClient.ts +3 -1
  45. package/src/Literal.ts +4 -1
  46. package/src/agent/Agent.ts +36 -0
  47. package/src/agent/AgentClient.ts +30 -0
  48. package/src/ai/AIClient.ts +35 -14
  49. package/src/ai/AIResolver.ts +78 -16
  50. package/src/index.ts +4 -3
  51. package/src/language/Language.ts +16 -4
  52. package/src/model/Ad4mModel.ts +1279 -0
  53. package/src/{subject → model}/Subject.ts +16 -16
  54. package/src/{subject/SDNADecorators.ts → model/decorators.ts} +384 -50
  55. package/src/neighbourhood/NeighbourhoodClient.ts +13 -10
  56. package/src/neighbourhood/NeighbourhoodProxy.test.ts +100 -0
  57. package/src/neighbourhood/NeighbourhoodProxy.ts +4 -4
  58. package/src/neighbourhood/NeighbourhoodResolver.ts +2 -2
  59. package/src/perspectives/PerspectiveClient.ts +156 -51
  60. package/src/perspectives/PerspectiveProxy.ts +766 -82
  61. package/src/perspectives/PerspectiveResolver.ts +134 -23
  62. package/src/runtime/RuntimeClient.ts +104 -2
  63. package/src/runtime/RuntimeResolver.ts +126 -1
  64. package/lib/src/subject/SDNADecorators.d.ts +0 -188
  65. package/lib/src/subject/SDNADecorators.js +0 -360
  66. package/lib/src/subject/SubjectEntity.d.ts +0 -102
  67. package/lib/src/subject/SubjectEntity.js +0 -267
  68. package/src/subject/SubjectEntity.ts +0 -315
  69. package/yarn-error.log +0 -90
  70. /package/lib/src/{subject → model}/util.d.ts +0 -0
  71. /package/lib/src/{subject → model}/util.js +0 -0
  72. /package/src/{subject → model}/util.ts +0 -0
@@ -7,18 +7,18 @@ import { collectionSetterToName, collectionToAdderName, collectionToRemoverName,
7
7
  */
8
8
  export class Subject {
9
9
  #baseExpression: string;
10
- #subjectClass: string;
10
+ #subjectClassName: string;
11
11
  #perspective: PerspectiveProxy
12
12
 
13
13
  /**
14
14
  * Constructs a new subject.
15
15
  * @param perspective - The perspective that the subject belongs to.
16
16
  * @param baseExpression - The base expression of the subject.
17
- * @param subjectClass - The class of the subject.
17
+ * @param subjectClassName - The class name of the subject.
18
18
  */
19
- constructor(perspective: PerspectiveProxy, baseExpression: string, subjectClass: string) {
19
+ constructor(perspective: PerspectiveProxy, baseExpression: string, subjectClassName: string) {
20
20
  this.#baseExpression = baseExpression
21
- this.#subjectClass = subjectClass
21
+ this.#subjectClassName = subjectClassName
22
22
  this.#perspective = perspective
23
23
  }
24
24
 
@@ -36,21 +36,21 @@ export class Subject {
36
36
  */
37
37
  async init() {
38
38
  // Check if the subject is a valid instance of the subject class
39
- let isInstance = await this.#perspective.isSubjectInstance(this.#baseExpression, this.#subjectClass)
39
+ let isInstance = await this.#perspective.isSubjectInstance(this.#baseExpression, this.#subjectClassName)
40
40
  if(!isInstance) {
41
- throw `Not a valid subject instance of ${this.#subjectClass} for ${this.#baseExpression}`
41
+ throw `Not a valid subject instance of ${this.#subjectClassName} for ${this.#baseExpression}`
42
42
  }
43
43
 
44
44
  // Define properties and collections dynamically
45
- let results = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), property(C, Property)`)
45
+ let results = await this.#perspective.infer(`subject_class("${this.#subjectClassName}", C), property(C, Property)`)
46
46
  let properties = results.map(result => result.Property)
47
47
 
48
48
  for(let p of properties) {
49
- const resolveExpressionURI = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), property_resolve(C, "${p}")`)
49
+ const resolveExpressionURI = await this.#perspective.infer(`subject_class("${this.#subjectClassName}", C), property_resolve(C, "${p}")`)
50
50
  Object.defineProperty(this, p, {
51
51
  configurable: true,
52
52
  get: async () => {
53
- let results = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), property_getter(C, "${this.#baseExpression}", "${p}", Value)`)
53
+ let results = await this.#perspective.infer(`subject_class("${this.#subjectClassName}", C), property_getter(C, "${this.#baseExpression}", "${p}", Value)`)
54
54
  if(results && results.length > 0) {
55
55
  let expressionURI = results[0].Value
56
56
  if(resolveExpressionURI) {
@@ -81,13 +81,13 @@ export class Subject {
81
81
  }
82
82
 
83
83
  // Define setters
84
- const setters = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), property_setter(C, Property, Setter)`)
84
+ const setters = await this.#perspective.infer(`subject_class("${this.#subjectClassName}", C), property_setter(C, Property, Setter)`)
85
85
 
86
86
  for(let setter of (setters ? setters : [])) {
87
87
  if(setter) {
88
88
  const property = setter.Property
89
89
  const actions = eval(setter.Setter)
90
- const resolveLanguageResults = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), property_resolve_language(C, "${property}", Language)`)
90
+ const resolveLanguageResults = await this.#perspective.infer(`subject_class("${this.#subjectClassName}", C), property_resolve_language(C, "${property}", Language)`)
91
91
  let resolveLanguage
92
92
  if(resolveLanguageResults && resolveLanguageResults.length > 0) {
93
93
  resolveLanguage = resolveLanguageResults[0].Language
@@ -102,7 +102,7 @@ export class Subject {
102
102
  }
103
103
 
104
104
  // Define collections
105
- let results2 = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), collection(C, Collection)`)
105
+ let results2 = await this.#perspective.infer(`subject_class("${this.#subjectClassName}", C), collection(C, Collection)`)
106
106
  if(!results2) results2 = []
107
107
  let collections = results2.map(result => result.Collection)
108
108
 
@@ -110,7 +110,7 @@ export class Subject {
110
110
  Object.defineProperty(this, c, {
111
111
  configurable: true,
112
112
  get: async () => {
113
- let results = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), collection_getter(C, "${this.#baseExpression}", "${c}", Value)`)
113
+ let results = await this.#perspective.infer(`subject_class("${this.#subjectClassName}", C), collection_getter(C, "${this.#baseExpression}", "${c}", Value)`)
114
114
  if(results && results.length > 0 && results[0].Value) {
115
115
  let collectionContent = results[0].Value.filter((v: any) => v !== "" && v !== '')
116
116
  return collectionContent
@@ -122,7 +122,7 @@ export class Subject {
122
122
  }
123
123
 
124
124
  // Define collection adders
125
- let adders = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), collection_adder(C, Collection, Adder)`)
125
+ let adders = await this.#perspective.infer(`subject_class("${this.#subjectClassName}", C), collection_adder(C, Collection, Adder)`)
126
126
  if(!adders) adders = []
127
127
 
128
128
  for(let adder of adders) {
@@ -140,7 +140,7 @@ export class Subject {
140
140
  }
141
141
 
142
142
  // Define collection removers
143
- let removers = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), collection_remover(C, Collection, Remover)`)
143
+ let removers = await this.#perspective.infer(`subject_class("${this.#subjectClassName}", C), collection_remover(C, Collection, Remover)`)
144
144
  if(!removers) removers = []
145
145
 
146
146
  for(let remover of removers) {
@@ -158,7 +158,7 @@ export class Subject {
158
158
  }
159
159
 
160
160
  // Define collection setters
161
- let collectionSetters = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), collection_setter(C, Collection, Setter)`)
161
+ let collectionSetters = await this.#perspective.infer(`subject_class("${this.#subjectClassName}", C), collection_setter(C, Collection, Setter)`)
162
162
  if(!collectionSetters) collectionSetters = []
163
163
 
164
164
  for(let collectionSetter of collectionSetters) {
@@ -35,23 +35,44 @@ condition?: string;
35
35
  }
36
36
 
37
37
  /**
38
- * Decorator for querying instances of a subject class.
38
+ * Decorator for querying instances of a model class.
39
39
  *
40
40
  * @category Decorators
41
41
  *
42
42
  * @description
43
- * NOTE: Only works on methods that return a promise and will throw an error if not used on a method that returns a promise.
44
- * This will allow you to query for instances of a subject class with custom clauses within the instance clauses.
43
+ * Allows you to define static query methods on your model class to retrieve instances based on custom conditions.
44
+ * This decorator can only be applied to static async methods that return a Promise of an array of model instances.
45
45
  *
46
- * @example
47
- * // Usage with where clause
48
- * InstanceQuery({ where: { name: "John" }}) // this will return all the properties of the subject class with the name "John"
46
+ * The query can be constrained using either:
47
+ * - A `where` clause that matches property values
48
+ * - A custom Prolog `condition` for more complex queries
49
49
  *
50
50
  * @example
51
- * // Usage with condition clause
52
- * InstanceQuery({ condition: "triple(Instance, 'age', Age), Age > 18" }) // this will return all the properties of the subject class with the age greater than 18
51
+ * ```typescript
52
+ * class Recipe extends Ad4mModel {
53
+ * @Property({ through: "recipe://name" })
54
+ * name: string = "";
55
+ *
56
+ * @Property({ through: "recipe://rating" })
57
+ * rating: number = 0;
58
+ *
59
+ * // Get all recipes
60
+ * @InstanceQuery()
61
+ * static async all(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
62
+ *
63
+ * // Get recipes by name
64
+ * @InstanceQuery({ where: { name: "Chocolate Cake" }})
65
+ * static async findByName(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
53
66
  *
54
- * @param {Object} [options] - Query options.
67
+ * // Get highly rated recipes using a custom condition
68
+ * @InstanceQuery({ condition: "triple(Instance, 'recipe://rating', Rating), Rating > 4" })
69
+ * static async topRated(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
70
+ * }
71
+ * ```
72
+ *
73
+ * @param {Object} [options] - Query options
74
+ * @param {object} [options.where] - Object with property-value pairs to match
75
+ * @param {string} [options.condition] - Custom Prolog condition for more complex queries
55
76
  */
56
77
  export function InstanceQuery(options?: InstanceQueryParams) {
57
78
  return function <T>(target: T, key: keyof T, descriptor: PropertyDescriptor) {
@@ -136,31 +157,101 @@ export interface PropertyOptions {
136
157
  * Indicates whether the property is stored locally in the perspective and not in the network. Useful for properties that are not meant to be shared with the network.
137
158
  */
138
159
  local?: boolean;
160
+
161
+ /**
162
+ * Optional transform function to modify the property value after it is retrieved.
163
+ * This is useful for transforming raw data into a more usable format.
164
+ * The function takes the raw value as input and returns the transformed value.
165
+ */
166
+ transform?: (value: any) => any;
139
167
  }
140
168
 
169
+
141
170
  /**
142
- * Decorator for defining properties of a subject class.
171
+ * Decorator for defining optional properties on model classes.
143
172
  *
144
173
  * @category Decorators
145
174
  *
146
175
  * @description
147
- * This will allow you to define properties with different conditions and how they would be defined in proflog engine.
176
+ * The most flexible property decorator that allows you to define properties with full control over:
177
+ * - Whether the property is required
178
+ * - Whether the property is writable
179
+ * - How values are stored and retrieved
180
+ * - Custom getter/setter logic
181
+ * - Local vs network storage
148
182
  *
149
- * - All properties must have a `through` option which is the predicate of the property.
150
- * -e If the property is required, it must have an `initial` option which is the initial value of the property.
151
- * - If the property is writable, it will have a setter in prolog engine. A custom setter can be defined with the `setter` option.
152
- * - If resolveLanguage is defined, you can use the default `Literal` Language or use your custom language address that can be used to store the property.
153
- * - If a custom getter is defined, it will be used to get the value of the property in prolog engine. If not, the default getter will be used.
154
- * - If local is defined, the property will be stored locally in the perspective and not in the network. This is useful for properties that are not meant to be shared with the network
183
+ * Both @Property and @ReadOnly are specialized versions of @Optional with preset configurations.
155
184
  *
156
185
  * @example
157
- * // Usage
158
- * SubjectProperty({ through: "ad4m://name", initial: "John", required: true }) // this will define a property with the name "ad4m://name" and the initial value "John"
186
+ * ```typescript
187
+ * class Recipe extends Ad4mModel {
188
+ * // Basic optional property
189
+ * @Optional({
190
+ * through: "recipe://description"
191
+ * })
192
+ * description?: string;
193
+ *
194
+ * // Optional property with custom initial value
195
+ * @Optional({
196
+ * through: "recipe://status",
197
+ * initial: "recipe://draft",
198
+ * required: true
199
+ * })
200
+ * status: string = "";
201
+ *
202
+ * // Read-only property with custom getter
203
+ * @Optional({
204
+ * through: "recipe://rating",
205
+ * writable: false,
206
+ * getter: `
207
+ * findall(Rating, triple(Base, "recipe://user_rating", Rating), Ratings),
208
+ * sum_list(Ratings, Sum),
209
+ * length(Ratings, Count),
210
+ * Value is Sum / Count
211
+ * `
212
+ * })
213
+ * averageRating: number = 0;
214
+ *
215
+ * // Property that resolves to a Literal and is stored locally
216
+ * @Optional({
217
+ * through: "recipe://notes",
218
+ * resolveLanguage: "literal",
219
+ * local: true
220
+ * })
221
+ * notes?: string;
159
222
  *
160
- * @param {PropertyOptions} [opts] - Property options.
223
+ * // Property with custom getter and setter logic
224
+ * @Optional({
225
+ * through: "recipe://ingredients",
226
+ * getter: `
227
+ * triple(Base, "recipe://ingredients", RawValue),
228
+ * atom_json_term(RawValue, Value)
229
+ * `,
230
+ * setter: `
231
+ * atom_json_term(Value, JsonValue),
232
+ * Actions = [{"action": "setSingleTarget", "source": "this", "predicate": "recipe://ingredients", "target": JsonValue}]
233
+ * `
234
+ * })
235
+ * ingredients: string[] = [];
236
+ * }
237
+ * ```
238
+ *
239
+ * @param {PropertyOptions} opts - Property configuration options
240
+ * @param {string} opts.through - The predicate URI for the property
241
+ * @param {string} [opts.initial] - Initial value (required if property is required)
242
+ * @param {boolean} [opts.required] - Whether the property must have a value
243
+ * @param {boolean} [opts.writable=true] - Whether the property can be modified
244
+ * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
245
+ * @param {string} [opts.getter] - Custom Prolog code for getting the property value
246
+ * @param {string} [opts.setter] - Custom Prolog code for setting the property value
247
+ * @param {boolean} [opts.local] - Whether the property should only be stored locally
161
248
  */
162
- export function SubjectProperty(opts: PropertyOptions) {
249
+ export function Optional(opts: PropertyOptions) {
163
250
  return function <T>(target: T, key: keyof T) {
251
+ if(typeof opts.writable === "undefined" && opts.through) {
252
+ opts.writable = true
253
+ }
254
+
164
255
  if (opts.required && !opts.initial) {
165
256
  throw new Error("SubjectProperty requires an 'initial' option if 'required' is true");
166
257
  }
@@ -195,25 +286,59 @@ export interface FlagOptions {
195
286
  }
196
287
 
197
288
  /**
198
- * Decorator for defining flags of a subject class
289
+ * Decorator for defining flags on model classes.
199
290
  *
200
291
  * @category Decorators
201
292
  *
202
293
  * @description
203
- * The idea behind flag decorator is to define a property that is required and has an initial value.
204
- * This will allow you to define a strict instance query. This behaviour can also be achieved with the `SubjectProperty` decorator but the `SubjectFlag` decorator is a shorthand for that.
294
+ * A specialized property decorator for defining immutable type flags or markers on model instances.
295
+ * Flags are always required properties with a fixed value that cannot be changed after creation.
205
296
  *
206
- * NOTE: Use of Flag is discouraged and should be used only when necessary.
297
+ * Common uses for flags:
298
+ * - Type discrimination between different kinds of models
299
+ * - Marking models with specific capabilities or features
300
+ * - Versioning or compatibility markers
207
301
  *
208
- * - All properties must have a `through` & `initial` option which is the predicate of the property.
302
+ * Note: Use of Flag is discouraged unless you specifically need type-based filtering or
303
+ * discrimination between different kinds of models. For most cases, regular properties
304
+ * with @Property or @Optional are more appropriate.
209
305
  *
210
306
  * @example
211
- * // Usage
212
- * SubjectFlag({ through: "ad4m://name", value: "John" }) // this will define a flag with the name "ad4m://name" and the initial value "John"
307
+ * ```typescript
308
+ * class Message extends Ad4mModel {
309
+ * // Type flag to identify message models
310
+ * @Flag({
311
+ * through: "ad4m://type",
312
+ * value: "ad4m://message"
313
+ * })
314
+ * type: string = "";
315
+ *
316
+ * // Version flag for compatibility
317
+ * @Flag({
318
+ * through: "ad4m://version",
319
+ * value: "1.0.0"
320
+ * })
321
+ * version: string = "";
213
322
  *
214
- * @param {FlagOptions} [opts] Flag options.
323
+ * // Feature flag
324
+ * @Flag({
325
+ * through: "message://feature",
326
+ * value: "message://encrypted"
327
+ * })
328
+ * feature: string = "";
329
+ * }
330
+ *
331
+ * // Later you can query for specific types:
332
+ * const messages = await Message.query(perspective)
333
+ * .where({ type: "ad4m://message" })
334
+ * .run();
335
+ * ```
336
+ *
337
+ * @param {FlagOptions} opts - Flag configuration
338
+ * @param {string} opts.through - The predicate URI for the flag
339
+ * @param {string} opts.value - The fixed value for the flag
215
340
  */
216
- export function SubjectFlag(opts: FlagOptions) {
341
+ export function Flag(opts: FlagOptions) {
217
342
  return function <T>(target: T, key: keyof T) {
218
343
  if (!opts.through && !opts.value) {
219
344
  throw new Error("SubjectFlag requires a 'through' and 'value' option")
@@ -267,26 +392,71 @@ export interface CollectionOptions {
267
392
  }
268
393
 
269
394
  /**
270
- * Decorator for defining collections of a subject class.
395
+ * Decorator for defining collections on model classes.
271
396
  *
272
397
  * @category Decorators
273
398
  *
274
399
  * @description
275
- * This will allow you to define collections with different conditions and how they would be defined in proflog engine.
400
+ * Defines a property that represents a collection of values linked to the model instance.
401
+ * Collections are always arrays and support operations for adding, removing, and setting values.
276
402
  *
277
- * NOTE: The property needs to be an array for it to picked up during the initialization phase.
403
+ * For each collection property, the following methods are automatically generated:
404
+ * - `addX(value)` - Add a value to the collection
405
+ * - `removeX(value)` - Remove a value from the collection
406
+ * - `setCollectionX(values)` - Replace all values in the collection
278
407
  *
279
- * - All collections must have a `through` option which is the predicate of the collection.
280
- * - If the collection has a `where` option, it can be used to define a custom condition for the collection.
281
- * - If the collection has a `local` option, the collection will be stored locally in the perspective and not in the network. This is useful for collections that are not meant to be shared with the network.
408
+ * Where X is the capitalized property name.
409
+ *
410
+ * Collections can be filtered using the `where` option to only include values that:
411
+ * - Are instances of a specific model class
412
+ * - Match a custom Prolog condition
282
413
  *
283
414
  * @example
284
- * // Usage
285
- * SubjectCollection({ through: "ad4m://friends" }) // this will define a collection with the name "ad4m://friends"
415
+ * ```typescript
416
+ * class Recipe extends Ad4mModel {
417
+ * // Basic collection of ingredients
418
+ * @Collection({
419
+ * through: "recipe://ingredient"
420
+ * })
421
+ * ingredients: string[] = [];
422
+ *
423
+ * // Collection that only includes instances of another model
424
+ * @Collection({
425
+ * through: "recipe://comment",
426
+ * where: { isInstance: Comment }
427
+ * })
428
+ * comments: string[] = [];
429
+ *
430
+ * // Collection with custom filter condition
431
+ * @Collection({
432
+ * through: "recipe://step",
433
+ * where: { condition: `triple(Target, "step://order", Order), Order < 3` }
434
+ * })
435
+ * firstSteps: string[] = [];
436
+ *
437
+ * // Local-only collection not shared with network
438
+ * @Collection({
439
+ * through: "recipe://note",
440
+ * local: true
441
+ * })
442
+ * privateNotes: string[] = [];
443
+ * }
444
+ *
445
+ * // Using the generated methods:
446
+ * const recipe = new Recipe(perspective);
447
+ * await recipe.addIngredients("ingredient://flour");
448
+ * await recipe.removeIngredients("ingredient://sugar");
449
+ * await recipe.setCollectionIngredients(["ingredient://butter", "ingredient://eggs"]);
450
+ * ```
286
451
  *
287
- * @param opts Collection options.
452
+ * @param {CollectionOptions} opts - Collection configuration
453
+ * @param {string} opts.through - The predicate URI for collection links
454
+ * @param {WhereOptions} [opts.where] - Filter conditions for collection values
455
+ * @param {any} [opts.where.isInstance] - Model class to filter instances by
456
+ * @param {string} [opts.where.condition] - Custom Prolog condition for filtering
457
+ * @param {boolean} [opts.local] - Whether collection links are stored locally only
288
458
  */
289
- export function SubjectCollection(opts: CollectionOptions) {
459
+ export function Collection(opts: CollectionOptions) {
290
460
  return function <T>(target: T, key: keyof T) {
291
461
  target["__collections"] = target["__collections"] || {};
292
462
  target["__collections"][key] = opts;
@@ -310,7 +480,7 @@ export function makeRandomPrologAtom(length: number): string {
310
480
  return result;
311
481
  }
312
482
 
313
- export interface SDNAClassOptions {
483
+ export interface ModelOptionsOptions {
314
484
  /**
315
485
  * The name of the entity.
316
486
  */
@@ -318,22 +488,60 @@ export interface SDNAClassOptions {
318
488
  }
319
489
 
320
490
  /**
321
- * Decorator for defining an SDNA class.
491
+ * Decorator for defining model classes in AD4M.
322
492
  *
323
493
  * @category Decorators
324
494
  *
325
495
  * @description
326
- * This will create a new SDNA class with the given name and add custom methods to generate the SDNA for the class, for this to work the class need to have the properties defined using the decorators like `SubjectProperty`.
496
+ * The root decorator that must be applied to any class that represents a model in AD4M.
497
+ * It registers the class as a Social DNA (SDNA) subject class and provides the infrastructure
498
+ * for storing and retrieving instances.
327
499
  *
328
- * Note: This decorator is required for the class to be picked up during the initialization phase.
500
+ * This decorator:
501
+ * - Registers the class with a unique name in the AD4M system
502
+ * - Generates the necessary SDNA code for the model's properties and collections
503
+ * - Enables the use of other model decorators (@Property, @Collection, etc.)
504
+ * - Provides static query methods through the Ad4mModel base class
329
505
  *
330
506
  * @example
331
- * // Usage
332
- * SDNAClass({ name: "Person" }) // this will create a new SDNA class with the name "Person"
507
+ * ```typescript
508
+ * @ModelOptions({ name: "Recipe" })
509
+ * class Recipe extends Ad4mModel {
510
+ * @Property({
511
+ * through: "recipe://name",
512
+ * resolveLanguage: "literal"
513
+ * })
514
+ * name: string = "";
333
515
  *
334
- * @param opts SDNA class options.
516
+ * @Collection({ through: "recipe://ingredient" })
517
+ * ingredients: string[] = [];
518
+ *
519
+ * // Static query methods from Ad4mModel:
520
+ * static async findByName(perspective: PerspectiveProxy, name: string) {
521
+ * return Recipe.query(perspective)
522
+ * .where({ name })
523
+ * .run();
524
+ * }
525
+ * }
526
+ *
527
+ * // Using the model:
528
+ * const recipe = new Recipe(perspective);
529
+ * recipe.name = "Chocolate Cake";
530
+ * await recipe.save();
531
+ *
532
+ * // Querying instances:
533
+ * const recipes = await Recipe.query(perspective)
534
+ * .where({ name: "Chocolate Cake" })
535
+ * .run();
536
+ *
537
+ * // Using with PerspectiveProxy:
538
+ * await perspective.ensureSDNASubjectClass(Recipe);
539
+ * ```
540
+ *
541
+ * @param {ModelOptionsOptions} opts - Model configuration
542
+ * @param {string} opts.name - Unique name for the model class in AD4M
335
543
  */
336
- export function SDNAClass(opts: SDNAClassOptions) {
544
+ export function ModelOptions(opts: ModelOptionsOptions) {
337
545
  return function (target: any) {
338
546
  target.prototype.className = opts.name;
339
547
  target.className = opts.name;
@@ -388,7 +596,7 @@ export function SDNAClass(opts: SDNAClassOptions) {
388
596
 
389
597
  if(setter) {
390
598
  propertyCode += `property_setter(${uuid}, "${property}", Actions) :- ${setter}.\n`
391
- } else if (writable) {
599
+ } else if (writable && through) {
392
600
  let setter = obj[propertyNameToSetterName(property)]
393
601
  if(typeof setter === "function") {
394
602
  let action = [{
@@ -416,7 +624,7 @@ export function SDNAClass(opts: SDNAClassOptions) {
416
624
  action: "removeLink",
417
625
  source: "this",
418
626
  predicate: through,
419
- target: initial,
627
+ target: "*",
420
628
  })
421
629
  }
422
630
  }
@@ -508,4 +716,130 @@ export function SDNAClass(opts: SDNAClassOptions) {
508
716
 
509
717
  Object.defineProperty(target, 'type', {configurable: true});
510
718
  }
719
+ }
720
+
721
+ /**
722
+ * Decorator for defining required and writable properties on model classes.
723
+ *
724
+ * @category Decorators
725
+ *
726
+ * @description
727
+ * A convenience decorator that defines a required property that must have an initial value and is writable by default.
728
+ * This is equivalent to using @Optional with `required: true` and `writable: true`.
729
+ *
730
+ * Properties defined with this decorator:
731
+ * - Must have a value (required)
732
+ * - Can be modified after creation (writable)
733
+ * - Default to "literal://string:uninitialized" if no initial value is provided
734
+ *
735
+ * @example
736
+ * ```typescript
737
+ * class User extends Ad4mModel {
738
+ * // Basic required property with default initial value
739
+ * @Property({
740
+ * through: "user://name"
741
+ * })
742
+ * name: string = "";
743
+ *
744
+ * // Required property with custom initial value
745
+ * @Property({
746
+ * through: "user://status",
747
+ * initial: "user://active"
748
+ * })
749
+ * status: string = "";
750
+ *
751
+ * // Required property with literal resolution
752
+ * @Property({
753
+ * through: "user://bio",
754
+ * resolveLanguage: "literal"
755
+ * })
756
+ * bio: string = "";
757
+ *
758
+ * // Required property with custom getter/setter
759
+ * @Property({
760
+ * through: "user://age",
761
+ * getter: `triple(Base, "user://birthYear", Year), Value is 2024 - Year`,
762
+ * setter: `Year is 2024 - Value, Actions = [{"action": "setSingleTarget", "source": "this", "predicate": "user://birthYear", "target": Year}]`
763
+ * })
764
+ * age: number = 0;
765
+ * }
766
+ * ```
767
+ *
768
+ * @param {PropertyOptions} opts - Property configuration
769
+ * @param {string} opts.through - The predicate URI for the property
770
+ * @param {string} [opts.initial] - Initial value (defaults to "literal://string:uninitialized")
771
+ * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
772
+ * @param {string} [opts.getter] - Custom Prolog code for getting the property value
773
+ * @param {string} [opts.setter] - Custom Prolog code for setting the property value
774
+ * @param {boolean} [opts.local] - Whether the property should only be stored locally
775
+ */
776
+ export function Property(opts: PropertyOptions) {
777
+ return Optional({
778
+ ...opts,
779
+ required: true,
780
+ writable: true,
781
+ initial: opts.initial || "literal://string:uninitialized"
782
+ });
783
+ }
784
+
785
+ /**
786
+ * Decorator for defining read-only properties on model classes.
787
+ *
788
+ * @category Decorators
789
+ *
790
+ * @description
791
+ * A convenience decorator that defines a property that can only be read and cannot be modified after initialization.
792
+ * This is equivalent to using @Optional with `writable: false`.
793
+ *
794
+ * Read-only properties are ideal for:
795
+ * - Computed or derived values
796
+ * - Properties that should never change after creation
797
+ * - Properties that are set by the system
798
+ * - Properties that represent immutable data
799
+ *
800
+ * @example
801
+ * ```typescript
802
+ * class Post extends Ad4mModel {
803
+ * // Read-only property with custom getter for computed value
804
+ * @ReadOnly({
805
+ * through: "post://likes",
806
+ * getter: `findall(User, triple(Base, "post://liked_by", User), Users), length(Users, Value)`
807
+ * })
808
+ * likeCount: number = 0;
809
+ *
810
+ * // Read-only property for creation timestamp
811
+ * @ReadOnly({
812
+ * through: "post://created_at",
813
+ * initial: new Date().toISOString()
814
+ * })
815
+ * createdAt: string = "";
816
+ *
817
+ * // Read-only property that resolves to a Literal
818
+ * @ReadOnly({
819
+ * through: "post://author",
820
+ * resolveLanguage: "literal"
821
+ * })
822
+ * author: string = "";
823
+ *
824
+ * // Read-only property for system-managed data
825
+ * @ReadOnly({
826
+ * through: "post://version",
827
+ * initial: "1.0.0"
828
+ * })
829
+ * version: string = "";
830
+ * }
831
+ * ```
832
+ *
833
+ * @param {PropertyOptions} opts - Property configuration
834
+ * @param {string} opts.through - The predicate URI for the property
835
+ * @param {string} [opts.initial] - Initial value (if property should have one)
836
+ * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
837
+ * @param {string} [opts.getter] - Custom Prolog code for getting the property value
838
+ * @param {boolean} [opts.local] - Whether the property should only be stored locally
839
+ */
840
+ export function ReadOnly(opts: PropertyOptions) {
841
+ return Optional({
842
+ ...opts,
843
+ writable: false
844
+ });
511
845
  }