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

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 (153) hide show
  1. package/jest.config.js +10 -3
  2. package/lib/index.cjs +6893 -5884
  3. package/lib/index.js +6889 -5872
  4. package/lib/src/Ad4mClient.d.ts +9 -16
  5. package/lib/src/Ad4mClient.js +46 -25
  6. package/lib/src/Literal.d.ts +1 -2
  7. package/lib/src/Literal.js +38 -35
  8. package/lib/src/SmartLiteral.d.ts +1 -2
  9. package/lib/src/SmartLiteral.js +30 -15
  10. package/lib/src/agent/AgentClient.d.ts +1 -4
  11. package/lib/src/agent/AgentClient.js +79 -99
  12. package/lib/src/ai/AIClient.d.ts +1 -2
  13. package/lib/src/ai/AIClient.js +224 -220
  14. package/lib/src/expression/ExpressionClient.d.ts +1 -1
  15. package/lib/src/expression/ExpressionClient.js +73 -86
  16. package/lib/src/index.d.ts +1 -1
  17. package/lib/src/index.js +1 -1
  18. package/lib/src/language/LanguageClient.d.ts +1 -1
  19. package/lib/src/language/LanguageClient.js +52 -52
  20. package/lib/src/model/Ad4mModel.d.ts +1351 -144
  21. package/lib/src/model/Ad4mModel.js +3760 -228
  22. package/lib/src/model/Ad4mModel.test.js +522 -979
  23. package/lib/src/model/Subject.d.ts +3 -3
  24. package/lib/src/model/Subject.js +25 -25
  25. package/lib/src/model/decorators.d.ts +444 -100
  26. package/lib/src/model/decorators.js +686 -321
  27. package/lib/src/model/util.d.ts +6 -6
  28. package/lib/src/model/util.js +24 -24
  29. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +1 -5
  30. package/lib/src/neighbourhood/NeighbourhoodClient.js +179 -242
  31. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +1 -2
  32. package/lib/src/neighbourhood/NeighbourhoodProxy.js +28 -13
  33. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +5 -1
  34. package/lib/src/perspectives/PerspectiveClient.d.ts +9 -9
  35. package/lib/src/perspectives/PerspectiveClient.js +240 -316
  36. package/lib/src/perspectives/PerspectiveProxy.d.ts +99 -61
  37. package/lib/src/perspectives/PerspectiveProxy.js +485 -832
  38. package/lib/src/runtime/RuntimeClient.d.ts +1 -5
  39. package/lib/src/runtime/RuntimeClient.js +238 -412
  40. package/lib/src/shacl/SHACLFlow.test.js +105 -164
  41. package/lib/src/shacl/SHACLShape.d.ts +12 -17
  42. package/lib/src/shacl/SHACLShape.js +115 -128
  43. package/lib/src/shacl/SHACLShape.test.js +176 -244
  44. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  45. package/lib/src/shims/type-graphql.d.ts +32 -0
  46. package/lib/src/src/Ad4mClient.d.ts +28 -0
  47. package/lib/src/src/Address.d.ts +1 -0
  48. package/lib/src/src/DID.d.ts +1 -0
  49. package/lib/src/src/Exception.d.ts +7 -0
  50. package/lib/src/src/Literal.d.ts +7 -0
  51. package/lib/src/src/PubSub.d.ts +17 -0
  52. package/lib/src/src/SmartLiteral.d.ts +12 -0
  53. package/lib/src/src/agent/Agent.d.ts +110 -0
  54. package/lib/src/src/agent/AgentClient.d.ts +62 -0
  55. package/lib/src/src/agent/AgentResolver.d.ts +30 -0
  56. package/lib/src/src/agent/AgentStatus.d.ts +8 -0
  57. package/lib/src/src/ai/AIClient.d.ts +32 -0
  58. package/lib/src/src/ai/AIResolver.d.ts +75 -0
  59. package/lib/src/src/ai/Tasks.d.ts +37 -0
  60. package/lib/src/src/buildSchema.d.ts +1 -0
  61. package/lib/src/src/expression/Expression.d.ts +28 -0
  62. package/lib/src/src/expression/ExpressionClient.d.ts +13 -0
  63. package/lib/src/src/expression/ExpressionRef.d.ts +9 -0
  64. package/lib/src/src/expression/ExpressionResolver.d.ts +10 -0
  65. package/lib/src/src/index.d.ts +35 -0
  66. package/lib/src/src/jestSetup.d.ts +1 -0
  67. package/lib/src/src/language/Icon.d.ts +4 -0
  68. package/lib/src/src/language/Language.d.ts +206 -0
  69. package/lib/src/src/language/LanguageClient.d.ts +17 -0
  70. package/lib/src/src/language/LanguageContext.d.ts +37 -0
  71. package/lib/src/src/language/LanguageHandle.d.ts +9 -0
  72. package/lib/src/src/language/LanguageMeta.d.ts +35 -0
  73. package/lib/src/src/language/LanguageRef.d.ts +6 -0
  74. package/lib/src/src/language/LanguageResolver.d.ts +19 -0
  75. package/lib/src/src/links/Links.d.ts +39 -0
  76. package/lib/src/src/links/Links.test.d.ts +1 -0
  77. package/lib/src/src/model/Ad4mModel.d.ts +1438 -0
  78. package/lib/src/src/model/Ad4mModel.test.d.ts +1 -0
  79. package/lib/src/src/model/Subject.d.ts +25 -0
  80. package/lib/src/src/model/decorators.d.ts +545 -0
  81. package/lib/src/src/model/util.d.ts +12 -0
  82. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +10 -0
  83. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +25 -0
  84. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +19 -0
  85. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +1 -0
  86. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +24 -0
  87. package/lib/src/src/perspectives/LinkQuery.d.ts +11 -0
  88. package/lib/src/src/perspectives/Perspective.d.ts +38 -0
  89. package/lib/src/src/perspectives/Perspective.test.d.ts +1 -0
  90. package/lib/src/src/perspectives/PerspectiveClient.d.ts +97 -0
  91. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +9 -0
  92. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +18 -0
  93. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +865 -0
  94. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +57 -0
  95. package/lib/src/src/runtime/RuntimeClient.d.ts +56 -0
  96. package/lib/src/src/runtime/RuntimeResolver.d.ts +132 -0
  97. package/lib/src/src/shacl/SHACLFlow.d.ts +171 -0
  98. package/lib/src/src/shacl/SHACLFlow.test.d.ts +1 -0
  99. package/lib/src/src/shacl/SHACLShape.d.ts +117 -0
  100. package/lib/src/src/shacl/SHACLShape.test.d.ts +1 -0
  101. package/lib/src/src/typeDefs.d.ts +1 -0
  102. package/lib/src/src/unwrapApolloResult.d.ts +2 -0
  103. package/lib/src/src/utils.d.ts +25 -0
  104. package/lib/src/utils.d.ts +0 -8
  105. package/lib/src/utils.js +7 -21
  106. package/package.json +15 -14
  107. package/src/Ad4mClient.test.ts +1315 -1564
  108. package/src/Ad4mClient.ts +54 -55
  109. package/src/Literal.test.ts +26 -45
  110. package/src/Literal.ts +66 -82
  111. package/src/SmartLiteral.ts +58 -74
  112. package/src/agent/AgentClient.ts +99 -144
  113. package/src/ai/AIClient.ts +359 -409
  114. package/src/expression/ExpressionClient.ts +96 -142
  115. package/src/index.ts +1 -1
  116. package/src/language/LanguageClient.ts +113 -137
  117. package/src/model/Ad4mModel.test.ts +616 -1114
  118. package/src/model/Ad4mModel.ts +4386 -451
  119. package/src/model/Subject.ts +159 -0
  120. package/src/model/decorators.ts +1168 -667
  121. package/src/model/util.ts +54 -53
  122. package/src/neighbourhood/NeighbourhoodClient.ts +266 -392
  123. package/src/neighbourhood/NeighbourhoodProxy.test.ts +7 -3
  124. package/src/neighbourhood/NeighbourhoodProxy.ts +40 -58
  125. package/src/perspectives/PerspectiveClient.ts +540 -779
  126. package/src/perspectives/PerspectiveProxy.ts +2067 -2860
  127. package/src/runtime/RuntimeClient.ts +476 -775
  128. package/src/shacl/SHACLFlow.test.ts +129 -196
  129. package/src/shacl/SHACLShape.test.ts +190 -284
  130. package/src/shacl/SHACLShape.ts +200 -224
  131. package/src/utils.ts +17 -31
  132. package/tsconfig.json +10 -9
  133. package/src/model/IMPROVEMENTS.md +0 -482
  134. package/src/model/PREDICATE_COLLISION_FIX.md +0 -651
  135. package/src/model/README.md +0 -317
  136. package/src/model/SHACL_MUTATION_DECOUPLING.md +0 -356
  137. package/src/model/SUBSCRIPTION_STRATEGY.md +0 -317
  138. package/src/model/TC39_STAGE_3_DECORATORS.md +0 -609
  139. package/src/model/mutation.ts +0 -461
  140. package/src/model/parentUtils.ts +0 -91
  141. package/src/model/prolog/generatePrologFacts.ts +0 -176
  142. package/src/model/prolog/index.ts +0 -1
  143. package/src/model/query/ModelQueryBuilder.ts +0 -173
  144. package/src/model/query/fetchInstance.ts +0 -181
  145. package/src/model/query/hydration.ts +0 -273
  146. package/src/model/query/operations.ts +0 -510
  147. package/src/model/query/snapshot.ts +0 -126
  148. package/src/model/query/surrealCompiler.ts +0 -376
  149. package/src/model/schema/fromJSONSchema.ts +0 -411
  150. package/src/model/schema/metadata.ts +0 -148
  151. package/src/model/subscription.ts +0 -307
  152. package/src/model/transaction.ts +0 -60
  153. package/src/model/types.ts +0 -207
@@ -1,74 +1,90 @@
1
- import { capitalize, propertyNameToSetterName, } from "./util";
1
+ import { capitalize, propertyNameToSetterName, stringifyObjectLiteral } from "./util";
2
2
  import { SHACLShape } from "../shacl/SHACLShape";
3
- // Module-level WeakMaps keyed on the constructor function (not the prototype).
4
- // Each class constructor is a unique key, so subclass decorators write into their
5
- // own entry rather than the parent prototype's — preventing silent metadata corruption
6
- // across inherited classes (e.g. BaseBlock and PollBlock stay independent).
7
- export const propertyRegistry = new WeakMap();
8
- export const relationRegistry = new WeakMap();
9
- /** Returns the own + inherited property metadata for a given constructor, with own values winning. */
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
+ */
10
11
  export function getPropertiesMetadata(ctor) {
11
- if (!ctor)
12
- return {};
13
- const own = propertyRegistry.get(ctor) ?? {};
14
- const parent = Object.getPrototypeOf(ctor);
15
- if (!parent || parent === Function.prototype)
16
- return own;
17
- return { ...getPropertiesMetadata(parent), ...own };
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;
18
25
  }
19
- /** Returns the own + inherited relation metadata for a given constructor, with own values winning. */
26
+ /**
27
+ * Retrieve relation metadata for a given class constructor.
28
+ * Walks the prototype chain so subclass decorators compose with parent decorators.
29
+ */
20
30
  export function getRelationsMetadata(ctor) {
21
- if (!ctor)
22
- return {};
23
- const own = relationRegistry.get(ctor) ?? {};
24
- const parent = Object.getPrototypeOf(ctor);
25
- if (!parent || parent === Function.prototype)
26
- return own;
27
- return { ...getRelationsMetadata(parent), ...own };
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;
28
44
  }
29
45
  /**
30
- * Builds a plain, JSON-safe object from a model instance.
31
- *
32
- * Only includes `id` (if present) and decorator-registered \@Property keys.
33
- * All other own enumerable properties are stripped — most importantly the
34
- * TypeScript `private _perspective` field which is stored as a regular
35
- * enumerable property at runtime and holds a PerspectiveProxy whose Apollo
36
- * InMemoryCache creates a circular reference in `JSON.stringify`.
37
- *
38
- * Falls back to a shallow spread for plain objects with no registered props
39
- * (e.g. raw link objects passed through before model hydration).
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.
40
66
  */
41
67
  export function instanceToSerializable(instance) {
42
- if (!instance || typeof instance !== "object")
43
- return {};
44
- const ctor = Object.getPrototypeOf(instance)?.constructor;
45
- const registeredProps = ctor ? getPropertiesMetadata(ctor) : null;
46
- const registeredRels = ctor ? getRelationsMetadata(ctor) : null;
47
- const propKeys = registeredProps ? Object.keys(registeredProps) : null;
48
- const relKeys = registeredRels ? Object.keys(registeredRels) : null;
49
- const allKeys = (propKeys ?? relKeys) ? [...(propKeys ?? []), ...(relKeys ?? [])] : null;
50
- if (!allKeys || allKeys.length === 0) {
51
- // Plain object / no @Property decorators — safe to spread.
52
- return { ...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];
53
73
  }
54
- const obj = {};
55
- if (instance.id !== undefined) {
56
- obj.id = instance.id;
57
- }
58
- for (const key of allKeys) {
59
- const val = instance[key];
60
- // For relation arrays containing model instances, serialize only their IDs
61
- // to avoid circular references and keep the fingerprint lightweight.
62
- if (Array.isArray(val)) {
63
- obj[key] = val.map((item) => item && typeof item === "object" && item.id !== undefined
64
- ? item.id
65
- : item);
66
- }
67
- else {
68
- obj[key] = val;
69
- }
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));
70
86
  }
71
- return obj;
87
+ return result;
72
88
  }
73
89
  export class PerspectiveAction {
74
90
  }
@@ -84,29 +100,27 @@ export function hasLink(predicate) {
84
100
  return `triple(this, "${predicate}", _)`;
85
101
  }
86
102
  /**
87
- * Declares a typed property backed by a single link triple in the perspective.
88
- *
89
- * @param opts.through - Predicate URI (required)
90
- * @param opts.initial - Default value written by the constructor action (auto-derived for non-readOnly properties; only needed for custom URIs)
91
- * @param opts.required - Adds `sh:minCount 1` to the SHACL shape
92
- * @param opts.readOnly - Skips setter generation; property cannot be updated after creation (default: false)
93
- * @param opts.resolveLanguage - Language for value resolution (`"literal"`, etc.)
94
- * @param opts.local - Store only in local perspective, not shared with the network
95
- * @param opts.getter - Custom SurrealQL expression for computed / read-only properties
96
- * @param opts.transform - Post-fetch transform applied to the raw value
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
97
107
  */
98
- export function Property(opts) {
108
+ function applyPropertyMetadata(opts) {
99
109
  return function (target, key) {
100
- if (!opts.through) {
101
- throw new Error("@Property requires a 'through' option");
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");
114
+ }
115
+ if (!opts.through && !opts.prologGetter) {
116
+ throw new Error("SubjectProperty requires either 'through' or 'prologGetter' option");
102
117
  }
103
- const _propertyExisting = propertyRegistry.get(target.constructor) ?? {};
104
- const _propertyExistingKey = _propertyExisting[key] ?? {};
105
- propertyRegistry.set(target.constructor, {
106
- ..._propertyExisting,
107
- [key]: { ..._propertyExistingKey, ...opts },
108
- });
109
- if (!opts.readOnly) {
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) {
110
124
  const value = key;
111
125
  target[`set${capitalize(value)}`] = () => { };
112
126
  }
@@ -114,16 +128,84 @@ export function Property(opts) {
114
128
  };
115
129
  }
116
130
  /**
117
- * Immutable type-marker property: written once at creation and never modified.
131
+ * Convenience decorator for defining optional (not required) properties.
132
+ *
133
+ * @category Decorators
118
134
  *
119
- * Use for type-discrimination predicates (e.g. `ad4m://type = "ad4m://message"`).
120
- * For mutable data prefer `@Property`.
135
+ * @description
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.
121
139
  *
122
140
  * @example
123
141
  * ```typescript
124
- * @Flag({ through: "ad4m://type", value: "ad4m://message" })
125
- * type: string = "";
142
+ * class Recipe extends Ad4mModel {
143
+ * @Optional({ through: "recipe://description" })
144
+ * description?: string;
145
+ * }
146
+ * ```
147
+ *
148
+ * @param {PropertyOptions} opts - Property configuration (same options as @Property)
149
+ */
150
+ export function Optional(opts) {
151
+ return applyPropertyMetadata({
152
+ ...opts,
153
+ required: opts.required ?? false,
154
+ readOnly: opts.readOnly ?? false,
155
+ });
156
+ }
157
+ /**
158
+ * Decorator for defining flags on model classes.
159
+ *
160
+ * @category Decorators
161
+ *
162
+ * @description
163
+ * A specialized property decorator for defining immutable type flags or markers on model instances.
164
+ * Flags are always required properties with a fixed value that cannot be changed after creation.
165
+ *
166
+ * Common uses for flags:
167
+ * - Type discrimination between different kinds of models
168
+ * - Marking models with specific capabilities or features
169
+ * - Versioning or compatibility markers
170
+ *
171
+ * Note: Use of Flag is discouraged unless you specifically need type-based filtering or
172
+ * discrimination between different kinds of models. For most cases, regular properties
173
+ * with @Property or @Optional are more appropriate.
174
+ *
175
+ * @example
176
+ * ```typescript
177
+ * class Message extends Ad4mModel {
178
+ * // Type flag to identify message models
179
+ * @Flag({
180
+ * through: "ad4m://type",
181
+ * value: "ad4m://message"
182
+ * })
183
+ * type: string = "";
184
+ *
185
+ * // Version flag for compatibility
186
+ * @Flag({
187
+ * through: "ad4m://version",
188
+ * value: "1.0.0"
189
+ * })
190
+ * version: string = "";
191
+ *
192
+ * // Feature flag
193
+ * @Flag({
194
+ * through: "message://feature",
195
+ * value: "message://encrypted"
196
+ * })
197
+ * feature: string = "";
198
+ * }
199
+ *
200
+ * // Later you can query for specific types:
201
+ * const messages = await Message.query(perspective)
202
+ * .where({ type: "ad4m://message" })
203
+ * .run();
126
204
  * ```
205
+ *
206
+ * @param {FlagOptions} opts - Flag configuration
207
+ * @param {string} opts.through - The predicate URI for the flag
208
+ * @param {string} opts.value - The fixed value for the flag
127
209
  */
128
210
  export function Flag(opts) {
129
211
  return function (target, key) {
@@ -136,148 +218,234 @@ export function Flag(opts) {
136
218
  if (!opts.value) {
137
219
  throw new Error("SubjectFlag requires a 'value' option");
138
220
  }
139
- const _flagExisting = propertyRegistry.get(target.constructor) ?? {};
140
- propertyRegistry.set(target.constructor, {
141
- ..._flagExisting,
142
- [key]: {
143
- ...(_flagExisting[key] ?? {}),
144
- through: opts.through,
145
- required: true,
146
- initial: opts.value,
147
- flag: true,
148
- readOnly: true, // Flags are always immutable after creation
149
- },
150
- });
221
+ const entry = {
222
+ through: opts.through,
223
+ required: true,
224
+ initial: opts.value,
225
+ flag: true,
226
+ readOnly: true,
227
+ writable: false,
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;
151
234
  // @ts-ignore
152
235
  target[key] = opts.value;
153
236
  Object.defineProperty(target, key, { configurable: true, writable: true });
154
237
  };
155
238
  }
156
- export function HasMany(relatedModelOrOpts, opts) {
157
- const resolvedOpts = typeof relatedModelOrOpts === "function" ? opts : relatedModelOrOpts;
158
- const relatedModel = typeof relatedModelOrOpts === "function" ? relatedModelOrOpts : undefined;
159
- return function (target, key) {
160
- if (!resolvedOpts?.through) {
161
- throw new Error(`@HasMany on "${String(key)}" requires a "through" predicate in RelationOptions`);
162
- }
163
- const _hasManyExisting = relationRegistry.get(target.constructor) ?? {};
164
- relationRegistry.set(target.constructor, {
165
- ..._hasManyExisting,
166
- [key]: {
167
- ...resolvedOpts,
168
- direction: "forward",
169
- ...(relatedModel ? { relatedModel } : {}),
170
- },
171
- });
172
- const value = key;
173
- target[`add${capitalize(value)}`] = () => { };
174
- target[`remove${capitalize(value)}`] = () => { };
175
- target[`set${capitalize(value)}`] = () => { };
176
- Object.defineProperty(target, key, { configurable: true, writable: true });
177
- };
178
- }
179
- export function HasOne(relatedModelOrOpts, opts) {
180
- const resolvedOpts = typeof relatedModelOrOpts === "function" ? opts : relatedModelOrOpts;
181
- const relatedModel = typeof relatedModelOrOpts === "function" ? relatedModelOrOpts : undefined;
182
- return function (target, key) {
183
- if (!resolvedOpts?.through) {
184
- throw new Error(`@HasOne on "${String(key)}" requires a "through" predicate in RelationOptions`);
185
- }
186
- const _hasOneExisting = relationRegistry.get(target.constructor) ?? {};
187
- relationRegistry.set(target.constructor, {
188
- ..._hasOneExisting,
189
- [key]: {
190
- ...resolvedOpts,
191
- direction: "forward",
192
- maxCount: 1,
193
- ...(relatedModel ? { relatedModel } : {}),
194
- },
195
- });
196
- const value = key;
197
- target[`add${capitalize(value)}`] = () => { };
198
- target[`remove${capitalize(value)}`] = () => { };
199
- target[`set${capitalize(value)}`] = () => { };
200
- Object.defineProperty(target, key, { configurable: true, writable: true });
201
- };
202
- }
203
- export function BelongsToOne(relatedModel, opts) {
204
- return function (target, key) {
205
- if (!opts?.through) {
206
- throw new Error(`@BelongsToOne on "${String(key)}" requires a "through" predicate in RelationOptions`);
207
- }
208
- const _b2oExisting = relationRegistry.get(target.constructor) ?? {};
209
- relationRegistry.set(target.constructor, {
210
- ..._b2oExisting,
211
- [key]: {
212
- ...opts,
213
- direction: "reverse",
214
- maxCount: 1,
215
- relatedModel,
216
- },
217
- });
218
- Object.defineProperty(target, key, { configurable: true, writable: true });
219
- };
220
- }
221
- export function BelongsToMany(relatedModel, opts) {
222
- return function (target, key) {
223
- if (!opts?.through) {
224
- throw new Error(`@BelongsToMany on "${String(key)}" requires a "through" predicate in RelationOptions`);
225
- }
226
- const _b2mExisting = relationRegistry.get(target.constructor) ?? {};
227
- relationRegistry.set(target.constructor, {
228
- ..._b2mExisting,
229
- [key]: { ...opts, direction: "reverse", relatedModel },
230
- });
231
- Object.defineProperty(target, key, { configurable: true, writable: true });
232
- };
233
- }
234
- export function makeRandomId(length) {
235
- let result = "";
236
- let characters = "abcdefghijklmnopqrstuvwxyz";
237
- let charactersLength = characters.length;
238
- for (let i = 0; i < length; i++) {
239
- result += characters.charAt(Math.floor(Math.random() * charactersLength));
240
- }
241
- return result;
242
- }
243
239
  /**
244
- * Registers the class as an AD4M SDNA subject, enabling `Ad4mModel` static query methods.
240
+ * Decorator for defining model classes in AD4M.
241
+ *
242
+ * @category Decorators
245
243
  *
246
- * Must be applied to every class that extends `Ad4mModel`.
244
+ * @description
245
+ * The root decorator that must be applied to any class that represents a model in AD4M.
246
+ * It registers the class as a Social DNA (SDNA) subject class and provides the infrastructure
247
+ * for storing and retrieving instances.
248
+ *
249
+ * This decorator:
250
+ * - Registers the class with a unique name in the AD4M system
251
+ * - Generates the necessary SDNA code for the model's properties and relations
252
+ * - Enables the use of other model decorators (@Property, @HasMany, etc.)
253
+ * - Provides static query methods through the Ad4mModel base class
247
254
  *
248
255
  * @example
249
256
  * ```typescript
250
257
  * @Model({ name: "Recipe" })
251
- * class Recipe extends Ad4mModel { ... }
258
+ * class Recipe extends Ad4mModel {
259
+ * @Property({
260
+ * through: "recipe://name",
261
+ * resolveLanguage: "literal"
262
+ * })
263
+ * name: string = "";
264
+ *
265
+ * @HasMany({ through: "recipe://ingredient" })
266
+ * ingredients: string[] = [];
267
+ *
268
+ * // Static query methods from Ad4mModel:
269
+ * static async findByName(perspective: PerspectiveProxy, name: string) {
270
+ * return Recipe.query(perspective)
271
+ * .where({ name })
272
+ * .run();
273
+ * }
274
+ * }
275
+ *
276
+ * // Using the model:
277
+ * const recipe = new Recipe(perspective);
278
+ * recipe.name = "Chocolate Cake";
279
+ * await recipe.save();
280
+ *
281
+ * // Querying instances:
282
+ * const recipes = await Recipe.query(perspective)
283
+ * .where({ name: "Chocolate Cake" })
284
+ * .run();
285
+ *
286
+ * // Using with PerspectiveProxy:
287
+ * await perspective.ensureSDNASubjectClass(Recipe);
252
288
  * ```
289
+ *
290
+ * @param {ModelConfig} opts - Model configuration
291
+ * @param {string} opts.name - Unique name for the model class in AD4M
253
292
  */
254
293
  export function Model(opts) {
255
294
  return function (target) {
256
295
  target.prototype.className = opts.name;
257
296
  target.className = opts.name;
297
+ target.generateSDNA = function () {
298
+ let sdna = "";
299
+ let subjectName = opts.name;
300
+ let obj = target.prototype;
301
+ let uuid = makeRandomId(8);
302
+ sdna += `subject_class("${subjectName}", ${uuid}).\n`;
303
+ let classRemoverActions = [];
304
+ let constructorActions = [];
305
+ if (obj.subjectConstructor && obj.subjectConstructor.length) {
306
+ constructorActions = constructorActions.concat(obj.subjectConstructor);
307
+ }
308
+ let instanceConditions = [];
309
+ if (obj.isSubjectInstance && obj.isSubjectInstance.length) {
310
+ instanceConditions = instanceConditions.concat(obj.isSubjectInstance);
311
+ }
312
+ let propertiesCode = [];
313
+ let properties = getPropertiesMetadata(target);
314
+ for (let property in properties) {
315
+ let propertyCode = `property(${uuid}, "${property}").\n`;
316
+ let { through, initial, required, resolveLanguage, writable, flag, prologGetter, prologSetter, local } = properties[property];
317
+ if (resolveLanguage) {
318
+ propertyCode += `property_resolve(${uuid}, "${property}").\n`;
319
+ propertyCode += `property_resolve_language(${uuid}, "${property}", "${resolveLanguage}").\n`;
320
+ }
321
+ if (prologGetter) {
322
+ propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- ${prologGetter}.\n`;
323
+ }
324
+ else if (through) {
325
+ propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- triple(Base, "${through}", Value).\n`;
326
+ if (required) {
327
+ if (flag) {
328
+ instanceConditions.push(`triple(Base, "${through}", "${initial}")`);
329
+ }
330
+ else {
331
+ instanceConditions.push(`triple(Base, "${through}", _)`);
332
+ }
333
+ }
334
+ }
335
+ if (prologSetter) {
336
+ propertyCode += `property_setter(${uuid}, "${property}", Actions) :- ${prologSetter}.\n`;
337
+ }
338
+ else if (writable && through) {
339
+ let setter = obj[propertyNameToSetterName(property)];
340
+ if (typeof setter === "function") {
341
+ let action = [{
342
+ action: "setSingleTarget",
343
+ source: "this",
344
+ predicate: through,
345
+ target: "value",
346
+ ...(local && { local: true })
347
+ }];
348
+ propertyCode += `property_setter(${uuid}, "${property}", '${stringifyObjectLiteral(action)}').\n`;
349
+ }
350
+ }
351
+ propertiesCode.push(propertyCode);
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) {
359
+ constructorActions.push({
360
+ action: "addLink",
361
+ source: "this",
362
+ predicate: through,
363
+ target: effectiveInitial,
364
+ });
365
+ classRemoverActions.push({
366
+ action: "removeLink",
367
+ source: "this",
368
+ predicate: through,
369
+ target: "*",
370
+ });
371
+ }
372
+ }
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];
379
+ if (through) {
380
+ relationCode += `collection_getter(${uuid}, Base, "${relation}", List) :- findall(C, triple(Base, "${through}", C), List).\n`;
381
+ let relationAdderAction = [{
382
+ action: "addLink",
383
+ source: "this",
384
+ predicate: through,
385
+ target: "value",
386
+ ...(local && { local: true })
387
+ }];
388
+ let relationRemoverAction = [{
389
+ action: "removeLink",
390
+ source: "this",
391
+ predicate: through,
392
+ target: "value",
393
+ }];
394
+ let relationSetterAction = [{
395
+ action: "collectionSetter",
396
+ source: "this",
397
+ predicate: through,
398
+ target: "value",
399
+ ...(local && { local: true })
400
+ }];
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`;
404
+ }
405
+ relationsCode.push(relationCode);
406
+ }
407
+ let subjectContructorJSONString = stringifyObjectLiteral(constructorActions);
408
+ sdna += `constructor(${uuid}, '${subjectContructorJSONString}').\n`;
409
+ if (instanceConditions.length > 0) {
410
+ let instanceConditionProlog = instanceConditions.join(", ");
411
+ sdna += `instance(${uuid}, Base) :- ${instanceConditionProlog}.\n`;
412
+ sdna += "\n";
413
+ }
414
+ sdna += `destructor(${uuid}, '${stringifyObjectLiteral(classRemoverActions)}').\n`;
415
+ sdna += "\n";
416
+ sdna += propertiesCode.join("\n");
417
+ sdna += "\n";
418
+ sdna += relationsCode.join("\n");
419
+ return {
420
+ sdna,
421
+ name: subjectName
422
+ };
423
+ };
258
424
  // Generate SHACL shape (W3C standard + AD4M action definitions)
259
425
  target.generateSHACL = function () {
260
426
  const subjectName = opts.name;
261
427
  const obj = target.prototype;
262
428
  // Determine namespace from first property or relation, or use default
263
429
  let namespace = "ad4m://";
264
- const fields = getPropertiesMetadata(target);
265
- const relations = getRelationsMetadata(target);
266
- // Try fields first
267
- if (Object.keys(fields).length > 0) {
268
- const firstProp = fields[Object.keys(fields)[0]];
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'));
433
+ // Try properties first
434
+ if (Object.keys(properties).length > 0) {
435
+ const firstProp = properties[Object.keys(properties)[0]];
269
436
  if (firstProp.through) {
437
+ // Extract namespace from through predicate (e.g., "recipe://name" -> "recipe://")
270
438
  const match = firstProp.through.match(/^([^:]+:\/\/)/);
271
439
  if (match) {
272
440
  namespace = match[1];
273
441
  }
274
442
  }
275
443
  }
276
- // Fall back to relations if no fields
444
+ // Fall back to relations if no properties
277
445
  else if (Object.keys(relations).length > 0) {
278
- const firstRelation = relations[Object.keys(relations)[0]];
279
- if (firstRelation.through) {
280
- const match = firstRelation.through.match(/^([^:]+:\/\/)/);
446
+ const firstRel = relations[Object.keys(relations)[0]];
447
+ if (firstRel.predicate) {
448
+ const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
281
449
  if (match) {
282
450
  namespace = match[1];
283
451
  }
@@ -287,45 +455,16 @@ export function Model(opts) {
287
455
  const shapeUri = `${namespace}${subjectName}Shape`;
288
456
  const targetClass = `${namespace}${subjectName}`;
289
457
  const shape = new SHACLShape(shapeUri, targetClass);
290
- // ── Detect @Model parent for sh:node inheritance ──────────────────────
291
- // If the immediate prototype constructor is also @Model-decorated,
292
- // emit sh:node <ParentShape> and use only OWN properties/relations
293
- // rather than duplicating the parent's properties in the child shape.
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.
294
461
  const parentCtor = Object.getPrototypeOf(target);
295
- const parentClassName = parentCtor?.prototype?.className;
296
- const isParentModel = parentClassName &&
297
- parentClassName !== "Ad4mModel" &&
298
- (propertyRegistry.has(parentCtor) || relationRegistry.has(parentCtor));
299
- let shapeFields;
300
- let shapeRelations;
301
- if (isParentModel) {
302
- // Own-only fields/relations — parent's are covered by sh:node
303
- shapeFields = propertyRegistry.get(target) ?? {};
304
- shapeRelations = relationRegistry.get(target) ?? {};
305
- // Derive parent shape URI from parent's own properties' namespace
306
- const parentOwnFields = Object.values(propertyRegistry.get(parentCtor) ?? {});
307
- const parentOwnRelations = Object.values(relationRegistry.get(parentCtor) ?? {});
308
- let parentNamespace = "ad4m://";
309
- if (parentOwnFields.length > 0 && parentOwnFields[0].through) {
310
- const m = parentOwnFields[0].through.match(/^([^:]+:\/\/)/);
311
- if (m)
312
- parentNamespace = m[1];
462
+ if (parentCtor && typeof parentCtor.generateSHACL === 'function') {
463
+ const parentSHACL = parentCtor.generateSHACL();
464
+ if (parentSHACL?.shape?.nodeShapeUri) {
465
+ shape.addParentShape(parentSHACL.shape.nodeShapeUri);
313
466
  }
314
- else if (parentOwnRelations.length > 0 &&
315
- parentOwnRelations[0].through) {
316
- const m = parentOwnRelations[0].through.match(/^([^:]+:\/\/)/);
317
- if (m)
318
- parentNamespace = m[1];
319
- }
320
- const parentShapeUri = `${parentNamespace}${parentClassName}Shape`;
321
- shape.addParentShape(parentShapeUri);
322
- }
323
- else {
324
- // No @Model parent — include all inherited properties directly
325
- shapeFields = fields;
326
- shapeRelations = relations;
327
467
  }
328
- // ──────────────────────────────────────────────────────────────────────
329
468
  // === Extract Constructor Actions (same logic as generateSDNA) ===
330
469
  let constructorActions = [];
331
470
  if (obj.subjectConstructor && obj.subjectConstructor.length) {
@@ -333,47 +472,39 @@ export function Model(opts) {
333
472
  }
334
473
  // === Extract Destructor Actions ===
335
474
  let destructorActions = [];
336
- // Convert fields to SHACL property shapes
337
- for (const propName in shapeFields) {
338
- const propMeta = shapeFields[propName];
475
+ // Convert properties to SHACL property shapes
476
+ for (const propName in properties) {
477
+ const propMeta = properties[propName];
339
478
  if (!propMeta.through)
340
479
  continue; // Skip properties without predicates
341
480
  const propShape = {
342
481
  name: propName,
343
482
  path: propMeta.through,
344
483
  };
345
- // Auto-derive a constructor placeholder for non-readOnly, non-flag properties
346
- // that don't have an explicit initial. Only do this when the prototype
347
- // has a defined default value — optional fields (title?: string) have
348
- // no prototype default (undefined), and we must NOT write an empty
349
- // literal link for them. The specific placeholder value doesn't matter
350
- // for fields with an actual default — createSubject's initialValues
351
- // mechanism overwrites it with the real value via the setter actions.
352
- const protoDefault = obj[propName];
353
- const effectiveInitial = propMeta.initial ??
354
- (!propMeta.readOnly && !propMeta.flag && protoDefault !== undefined
355
- ? "literal://string:"
356
- : undefined);
357
- // Determine datatype from the TypeScript default value type.
358
- // resolveLanguage: "literal" is now the implicit default — literal://
359
- // URIs can carry any type (string/number/boolean), so always infer
360
- // from the prototype's default value rather than forcing xsd://string.
361
- const initialType = typeof obj[propName];
362
- if (initialType === "number") {
363
- propShape.datatype = "xsd://integer";
364
- }
365
- else if (initialType === "boolean") {
366
- propShape.datatype = "xsd://boolean";
367
- }
368
- else if (initialType === "string") {
484
+ // Determine datatype from initial value or resolveLanguage
485
+ if (propMeta.resolveLanguage === "literal") {
486
+ // If it resolves via literal language, it's likely a string
369
487
  propShape.datatype = "xsd://string";
370
488
  }
489
+ else if (propMeta.initial) {
490
+ // Try to infer from initial value type
491
+ const initialType = typeof obj[propName];
492
+ if (initialType === "number") {
493
+ propShape.datatype = "xsd://integer";
494
+ }
495
+ else if (initialType === "boolean") {
496
+ propShape.datatype = "xsd://boolean";
497
+ }
498
+ else if (initialType === "string") {
499
+ propShape.datatype = "xsd://string";
500
+ }
501
+ }
371
502
  // Cardinality constraints
372
503
  if (propMeta.required) {
373
504
  propShape.minCount = 1;
374
505
  }
375
- // @Property fields are always single-valued; maxCount 1 is unconditional.
376
- // Multi-valued relations live in relationRegistry and are handled below.
506
+ // Single-valued properties get maxCount 1
507
+ // (relations are handled separately below)
377
508
  propShape.maxCount = 1;
378
509
  // Flag properties have fixed value
379
510
  if (propMeta.flag && propMeta.initial) {
@@ -383,43 +514,38 @@ export function Model(opts) {
383
514
  if (propMeta.local !== undefined) {
384
515
  propShape.local = propMeta.local;
385
516
  }
386
- if (propMeta.readOnly) {
387
- propShape.readOnly = true;
517
+ if (propMeta.writable !== undefined) {
518
+ propShape.writable = propMeta.writable;
388
519
  }
389
520
  if (propMeta.resolveLanguage) {
390
521
  propShape.resolveLanguage = propMeta.resolveLanguage;
391
522
  }
392
- else if (!propMeta.flag) {
393
- // resolveLanguage: "literal" is the implicit default for scalar properties.
394
- // The Rust executor requires this to be explicit in the SHACL shape to
395
- // configure fn::parse_literal correctly in SurrealDB. The user doesn't
396
- // need to write it in their @Property decorator, but the shape must have it.
397
- propShape.resolveLanguage = "literal";
398
- }
399
523
  // === Extract Setter Actions (same logic as generateSDNA) ===
400
- if (propMeta.setter) {
401
- // Custom setter defined - not yet supported in SHACL
524
+ if (propMeta.prologSetter) {
525
+ // Custom Prolog setter defined - not yet supported in SHACL
402
526
  console.warn(`[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
403
527
  `The property will be created without setter actions. Consider using standard writable properties or provide explicit SHACL JSON.`);
404
528
  // TODO: Parse custom Prolog setter to extract actions
405
529
  }
406
- else if (!propMeta.readOnly && propMeta.through) {
530
+ else if (propMeta.writable && propMeta.through) {
407
531
  let setter = obj[propertyNameToSetterName(propName)];
408
532
  if (typeof setter === "function") {
409
- propShape.setter = [
410
- {
533
+ propShape.setter = [{
411
534
  action: "setSingleTarget",
412
535
  source: "this",
413
536
  predicate: propMeta.through,
414
537
  target: "value",
415
- ...(propMeta.local && { local: true }),
416
- },
417
- ];
538
+ ...(propMeta.local && { local: true })
539
+ }];
418
540
  }
419
541
  }
420
- // Add to constructor actions (always for non-readOnly, non-flag, using the
421
- // effective placeholder — createSubject's initialValues will override
422
- // the target with the real instance value via the setter actions).
542
+ // Add to constructor actions if property has initial value
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);
423
549
  if (effectiveInitial) {
424
550
  constructorActions.push({
425
551
  action: "addLink",
@@ -427,10 +553,7 @@ export function Model(opts) {
427
553
  predicate: propMeta.through,
428
554
  target: effectiveInitial,
429
555
  });
430
- }
431
- // Always add destructor action for non-readOnly, non-flag properties so
432
- // delete() cleans them up regardless of whether initial was explicit.
433
- if (!propMeta.readOnly && !propMeta.flag) {
556
+ // Add to destructor actions
434
557
  destructorActions.push({
435
558
  action: "removeLink",
436
559
  source: "this",
@@ -441,66 +564,308 @@ export function Model(opts) {
441
564
  shape.addProperty(propShape);
442
565
  }
443
566
  // Convert relations to SHACL property shapes
444
- for (const relName in shapeRelations) {
445
- const relMeta = shapeRelations[relName];
446
- if (!relMeta.through)
567
+ // (relations variable already declared above for namespace inference)
568
+ for (const relName in relations) {
569
+ const relMeta = relations[relName];
570
+ if (!relMeta.predicate)
447
571
  continue;
448
572
  const relShape = {
449
573
  name: relName,
450
- path: relMeta.through,
574
+ path: relMeta.predicate,
451
575
  // Relations have no maxCount (unlimited)
452
576
  // minCount defaults to 0 (optional)
453
577
  };
454
- // Relations contain references (IRIs) to other entities
455
- relShape.nodeKind = "IRI";
578
+ // Determine node kind — relations typically contain IRIs
579
+ relShape.nodeKind = 'IRI';
456
580
  // AD4M-specific metadata
457
581
  if (relMeta.local !== undefined) {
458
582
  relShape.local = relMeta.local;
459
583
  }
460
- // Relationship metadata
461
- if (relMeta.maxCount !== undefined) {
462
- relShape.maxCount = relMeta.maxCount;
463
- }
464
- if (relMeta.direction === "reverse") {
465
- relShape.inversePath = true;
466
- }
467
584
  // === Extract Relation Actions (adder/remover) ===
468
585
  // Adder action - adds a link to the relation
469
- relShape.adder = [
470
- {
586
+ relShape.adder = [{
471
587
  action: "addLink",
472
588
  source: "this",
473
- predicate: relMeta.through,
589
+ predicate: relMeta.predicate,
474
590
  target: "value",
475
- ...(relMeta.local && { local: true }),
476
- },
477
- ];
591
+ ...(relMeta.local && { local: true })
592
+ }];
478
593
  // Remover action - removes a link from the relation
479
- relShape.remover = [
480
- {
594
+ relShape.remover = [{
481
595
  action: "removeLink",
482
596
  source: "this",
483
- predicate: relMeta.through,
597
+ predicate: relMeta.predicate,
484
598
  target: "value",
485
- ...(relMeta.local && { local: true }),
486
- },
487
- ];
599
+ ...(relMeta.local && { local: true })
600
+ }];
488
601
  shape.addProperty(relShape);
489
602
  }
490
- // Set constructor and destructor actions on the shape.
491
- // Always set constructor actions (even if empty) so the Rust SHACL parser
492
- // emits an ad4m://constructor link — without it get_constructor_actions()
493
- // throws "No SHACL constructor found" for classes with no @Flag or initial
494
- // properties. An empty constructor is valid: it means "do nothing on creation".
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.
495
608
  shape.setConstructorActions(constructorActions);
496
- if (destructorActions.length > 0) {
497
- shape.setDestructorActions(destructorActions);
498
- }
609
+ shape.setDestructorActions(destructorActions);
499
610
  return {
500
611
  shape,
501
- name: subjectName,
612
+ name: subjectName
502
613
  };
503
614
  };
504
- Object.defineProperty(target, "type", { configurable: true });
615
+ Object.defineProperty(target, 'type', { configurable: true });
616
+ };
617
+ }
618
+ /**
619
+ * The primary property decorator for AD4M model classes.
620
+ *
621
+ * @category Decorators
622
+ *
623
+ * @description
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)
632
+ *
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).
638
+ *
639
+ * @example
640
+ * ```typescript
641
+ * class User extends Ad4mModel {
642
+ * // Optional property (default) — no link created until a value is set
643
+ * @Property({
644
+ * through: "user://name"
645
+ * })
646
+ * name: string = "";
647
+ *
648
+ * // Explicitly required property with sentinel initial value
649
+ * @Property({
650
+ * through: "user://status",
651
+ * required: true
652
+ * })
653
+ * status: string = "";
654
+ *
655
+ * // Required property with custom initial value
656
+ * @Property({
657
+ * through: "user://role",
658
+ * required: true,
659
+ * initial: "user://member"
660
+ * })
661
+ * role: string = "";
662
+ *
663
+ * // Optional property with literal resolution
664
+ * @Property({
665
+ * through: "user://bio",
666
+ * resolveLanguage: "literal"
667
+ * })
668
+ * bio: string = "";
669
+ * }
670
+ * ```
671
+ *
672
+ * @param {PropertyOptions} opts - Property configuration
673
+ * @param {string} opts.through - The predicate URI for the property
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)
676
+ * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
677
+ * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
678
+ * @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
679
+ * @param {boolean} [opts.local] - Whether the property should only be stored locally
680
+ */
681
+ export function Property(opts) {
682
+ const required = opts.required ?? false;
683
+ return applyPropertyMetadata({
684
+ ...opts,
685
+ required,
686
+ readOnly: opts.readOnly ?? false,
687
+ resolveLanguage: opts.resolveLanguage ?? "literal",
688
+ initial: opts.initial ?? (required ? "literal://string:uninitialized" : undefined),
689
+ });
690
+ }
691
+ /**
692
+ * Decorator for defining read-only properties on model classes.
693
+ *
694
+ * @category Decorators
695
+ *
696
+ * @description
697
+ * A convenience decorator that defines a read-only property.
698
+ * Equivalent to `@Property` with `readOnly: true`.
699
+ *
700
+ * Read-only properties are ideal for:
701
+ * - Computed or derived values
702
+ * - Properties that should never change after creation
703
+ * - Properties that are set by the system
704
+ * - Properties that represent immutable data
705
+ *
706
+ * @example
707
+ * ```typescript
708
+ * class Post extends Ad4mModel {
709
+ * // Read-only property with custom getter for computed value
710
+ * @ReadOnly({
711
+ * through: "post://likes",
712
+ * getter: `findall(User, triple(Base, "post://liked_by", User), Users), length(Users, Value)`
713
+ * })
714
+ * likeCount: number = 0;
715
+ *
716
+ * // Read-only property for creation timestamp
717
+ * @ReadOnly({
718
+ * through: "post://created_at",
719
+ * initial: new Date().toISOString()
720
+ * })
721
+ * createdAt: string = "";
722
+ *
723
+ * // Read-only property that resolves to a Literal
724
+ * @ReadOnly({
725
+ * through: "post://author",
726
+ * resolveLanguage: "literal"
727
+ * })
728
+ * author: string = "";
729
+ *
730
+ * // Read-only property for system-managed data
731
+ * @ReadOnly({
732
+ * through: "post://version",
733
+ * initial: "1.0.0"
734
+ * })
735
+ * version: string = "";
736
+ * }
737
+ * ```
738
+ *
739
+ * @param {PropertyOptions} opts - Property configuration
740
+ * @param {string} opts.through - The predicate URI for the property
741
+ * @param {string} [opts.initial] - Initial value (if property should have one)
742
+ * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
743
+ * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
744
+ * @param {boolean} [opts.local] - Whether the property should only be stored locally
745
+ */
746
+ export function ReadOnly(opts) {
747
+ return Property({
748
+ ...opts,
749
+ readOnly: true,
750
+ });
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 });
505
870
  };
506
871
  }