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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/lib/index.cjs +4968 -4805
  2. package/lib/index.js +4936 -4801
  3. package/lib/src/agent/AgentClient.d.ts +4 -0
  4. package/lib/src/agent/AgentClient.js +34 -0
  5. package/lib/src/index.d.ts +2 -3
  6. package/lib/src/index.js +2 -3
  7. package/lib/src/model/Ad4mModel.d.ts +8 -812
  8. package/lib/src/model/Ad4mModel.js +78 -2390
  9. package/lib/src/model/ModelQueryBuilder.d.ts +370 -0
  10. package/lib/src/model/ModelQueryBuilder.js +556 -0
  11. package/lib/src/model/decorators.d.ts +2 -20
  12. package/lib/src/model/decorators.js +5 -410
  13. package/lib/src/model/hydration.d.ts +102 -0
  14. package/lib/src/model/hydration.js +709 -0
  15. package/lib/src/model/index.d.ts +20 -0
  16. package/lib/src/model/index.js +20 -0
  17. package/lib/src/model/{schema/fromJSONSchema.d.ts → json-schema.d.ts} +45 -12
  18. package/lib/src/model/json-schema.js +326 -0
  19. package/lib/src/model/prolog-facts.d.ts +37 -0
  20. package/lib/src/model/{prolog/generatePrologFacts.js → prolog-facts.js} +47 -52
  21. package/lib/src/model/query-common.d.ts +14 -0
  22. package/lib/src/model/query-common.js +36 -0
  23. package/lib/src/model/query-prolog.d.ts +15 -0
  24. package/lib/src/model/query-prolog.js +140 -0
  25. package/lib/src/model/query-surreal.d.ts +44 -0
  26. package/lib/src/model/query-surreal.js +249 -0
  27. package/lib/src/model/sdna.d.ts +14 -0
  28. package/lib/src/model/sdna.js +141 -0
  29. package/lib/src/model/shacl-gen.d.ts +31 -0
  30. package/lib/src/model/shacl-gen.js +246 -0
  31. package/lib/src/model/surreal-utils.d.ts +1 -1
  32. package/lib/src/model/types.d.ts +75 -96
  33. package/lib/src/model/types.js +4 -4
  34. package/lib/src/model/util.d.ts +4 -5
  35. package/lib/src/model/util.js +12 -32
  36. package/lib/src/perspectives/PerspectiveClient.d.ts +1 -1
  37. package/lib/src/perspectives/PerspectiveProxy.d.ts +1 -1
  38. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +79 -0
  39. package/lib/src/perspectives/WakerSubscriptionManager.js +196 -0
  40. package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
  41. package/lib/src/runtime/RuntimeResolver.js +73 -0
  42. package/lib/src/schema.gql +14 -0
  43. package/lib/src/typeDefs.js +14 -0
  44. package/package.json +13 -8
  45. package/src/agent/AgentClient.ts +45 -0
  46. package/src/index.ts +2 -3
  47. package/src/model/Ad4mModel.ts +1084 -3818
  48. package/src/model/ModelQueryBuilder.ts +617 -0
  49. package/src/model/Subject.ts +1 -1
  50. package/src/model/decorators.ts +17 -475
  51. package/src/model/hydration.ts +796 -0
  52. package/src/model/index.ts +21 -0
  53. package/src/model/json-schema.ts +424 -0
  54. package/src/model/prolog-facts.ts +145 -0
  55. package/src/model/query-common.ts +48 -0
  56. package/src/model/query-prolog.ts +148 -0
  57. package/src/model/query-surreal.ts +280 -0
  58. package/src/model/relation-filtering.test.ts +0 -1
  59. package/src/model/sdna.ts +170 -0
  60. package/src/model/shacl-gen.ts +292 -0
  61. package/src/model/surreal-utils.ts +1 -1
  62. package/src/model/types.ts +182 -0
  63. package/src/model/util.ts +13 -36
  64. package/src/perspectives/PerspectiveClient.ts +1 -1
  65. package/src/perspectives/PerspectiveProxy.ts +1 -1
  66. package/src/perspectives/WakerSubscriptionManager.ts +292 -0
  67. package/src/runtime/RuntimeResolver.ts +53 -0
  68. package/lib/src/Ad4mClient.test.d.ts +0 -1
  69. package/lib/src/Ad4mClient.test.js +0 -1204
  70. package/lib/src/Literal.test.d.ts +0 -1
  71. package/lib/src/Literal.test.js +0 -41
  72. package/lib/src/model/mutation.d.ts +0 -81
  73. package/lib/src/model/mutation.js +0 -317
  74. package/lib/src/model/parentUtils.d.ts +0 -32
  75. package/lib/src/model/parentUtils.js +0 -64
  76. package/lib/src/model/prolog/generatePrologFacts.d.ts +0 -36
  77. package/lib/src/model/prolog/index.d.ts +0 -1
  78. package/lib/src/model/prolog/index.js +0 -1
  79. package/lib/src/model/query/ModelQueryBuilder.d.ts +0 -82
  80. package/lib/src/model/query/ModelQueryBuilder.js +0 -115
  81. package/lib/src/model/query/QueryBuilder.d.ts +0 -101
  82. package/lib/src/model/query/QueryBuilder.js +0 -193
  83. package/lib/src/model/query/SurrealQueryBuilder.d.ts +0 -48
  84. package/lib/src/model/query/SurrealQueryBuilder.js +0 -371
  85. package/lib/src/model/query/fetchInstance.d.ts +0 -24
  86. package/lib/src/model/query/fetchInstance.js +0 -144
  87. package/lib/src/model/query/hydration.d.ts +0 -54
  88. package/lib/src/model/query/hydration.js +0 -214
  89. package/lib/src/model/query/operations.d.ts +0 -59
  90. package/lib/src/model/query/operations.js +0 -384
  91. package/lib/src/model/query/snapshot.d.ts +0 -59
  92. package/lib/src/model/query/snapshot.js +0 -106
  93. package/lib/src/model/query/surrealCompiler.d.ts +0 -42
  94. package/lib/src/model/query/surrealCompiler.js +0 -304
  95. package/lib/src/model/schema/fromJSONSchema.js +0 -264
  96. package/lib/src/model/schema/metadata.d.ts +0 -15
  97. package/lib/src/model/schema/metadata.js +0 -112
  98. package/lib/src/model/subscription.d.ts +0 -47
  99. package/lib/src/model/subscription.js +0 -231
  100. package/lib/src/model/transaction.d.ts +0 -27
  101. package/lib/src/model/transaction.js +0 -32
  102. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  103. package/lib/src/shims/type-graphql.d.ts +0 -32
  104. package/lib/src/src/Ad4mClient.d.ts +0 -28
  105. package/lib/src/src/Address.d.ts +0 -1
  106. package/lib/src/src/DID.d.ts +0 -1
  107. package/lib/src/src/Exception.d.ts +0 -7
  108. package/lib/src/src/Literal.d.ts +0 -7
  109. package/lib/src/src/PubSub.d.ts +0 -17
  110. package/lib/src/src/SmartLiteral.d.ts +0 -12
  111. package/lib/src/src/agent/Agent.d.ts +0 -110
  112. package/lib/src/src/agent/AgentClient.d.ts +0 -62
  113. package/lib/src/src/agent/AgentResolver.d.ts +0 -30
  114. package/lib/src/src/agent/AgentStatus.d.ts +0 -8
  115. package/lib/src/src/ai/AIClient.d.ts +0 -32
  116. package/lib/src/src/ai/AIResolver.d.ts +0 -75
  117. package/lib/src/src/ai/Tasks.d.ts +0 -37
  118. package/lib/src/src/buildSchema.d.ts +0 -1
  119. package/lib/src/src/expression/Expression.d.ts +0 -28
  120. package/lib/src/src/expression/ExpressionClient.d.ts +0 -13
  121. package/lib/src/src/expression/ExpressionRef.d.ts +0 -9
  122. package/lib/src/src/expression/ExpressionResolver.d.ts +0 -10
  123. package/lib/src/src/index.d.ts +0 -35
  124. package/lib/src/src/jestSetup.d.ts +0 -1
  125. package/lib/src/src/language/Icon.d.ts +0 -4
  126. package/lib/src/src/language/Language.d.ts +0 -206
  127. package/lib/src/src/language/LanguageClient.d.ts +0 -17
  128. package/lib/src/src/language/LanguageContext.d.ts +0 -37
  129. package/lib/src/src/language/LanguageHandle.d.ts +0 -9
  130. package/lib/src/src/language/LanguageMeta.d.ts +0 -35
  131. package/lib/src/src/language/LanguageRef.d.ts +0 -6
  132. package/lib/src/src/language/LanguageResolver.d.ts +0 -19
  133. package/lib/src/src/links/Links.d.ts +0 -39
  134. package/lib/src/src/links/Links.test.d.ts +0 -1
  135. package/lib/src/src/model/Ad4mModel.d.ts +0 -1438
  136. package/lib/src/src/model/Ad4mModel.test.d.ts +0 -1
  137. package/lib/src/src/model/Subject.d.ts +0 -25
  138. package/lib/src/src/model/decorators.d.ts +0 -545
  139. package/lib/src/src/model/util.d.ts +0 -12
  140. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +0 -10
  141. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +0 -25
  142. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +0 -19
  143. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +0 -1
  144. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +0 -24
  145. package/lib/src/src/perspectives/LinkQuery.d.ts +0 -11
  146. package/lib/src/src/perspectives/Perspective.d.ts +0 -38
  147. package/lib/src/src/perspectives/Perspective.test.d.ts +0 -1
  148. package/lib/src/src/perspectives/PerspectiveClient.d.ts +0 -97
  149. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +0 -9
  150. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +0 -18
  151. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +0 -865
  152. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +0 -57
  153. package/lib/src/src/runtime/RuntimeClient.d.ts +0 -56
  154. package/lib/src/src/runtime/RuntimeResolver.d.ts +0 -132
  155. package/lib/src/src/shacl/SHACLFlow.d.ts +0 -171
  156. package/lib/src/src/shacl/SHACLFlow.test.d.ts +0 -1
  157. package/lib/src/src/shacl/SHACLShape.d.ts +0 -117
  158. package/lib/src/src/shacl/SHACLShape.test.d.ts +0 -1
  159. package/lib/src/src/typeDefs.d.ts +0 -1
  160. package/lib/src/src/unwrapApolloResult.d.ts +0 -2
  161. package/lib/src/src/utils.d.ts +0 -25
@@ -0,0 +1,31 @@
1
+ /**
2
+ * SHACL shape generation for AD4M model classes.
3
+ *
4
+ * Builds a W3C SHACL `SHACLShape` (with AD4M-specific action extensions)
5
+ * from a model's property and relation metadata. The heavy lifting used
6
+ * to live inside the `@Model` decorator closure — it is extracted here so
7
+ * decorators.ts stays focused on decorator registration logic.
8
+ */
9
+ import { SHACLShape } from "../shacl/SHACLShape";
10
+ import type { ConformanceCondition } from "../shacl/SHACLShape";
11
+ import type { PropertyMetadataEntry, RelationMetadataEntry, Ad4mModelLike } from "./decorators";
12
+ /** Signature for the conformance-filter builder injected by the caller. */
13
+ export type ConformanceFilterFn = (relationPredicate: string, targetClass: Ad4mModelLike) => {
14
+ getter: string;
15
+ conformanceConditions: ConformanceCondition[];
16
+ } | undefined;
17
+ /**
18
+ * Build a SHACL shape for a model class.
19
+ *
20
+ * @param subjectName - The model's registered name (from `@Model({ name })`)
21
+ * @param target - The class constructor (used for prototype access,
22
+ * inheritance chain, and relation target resolution)
23
+ * @param properties - Merged property metadata (from `getPropertiesMetadata`)
24
+ * @param allRelationsMeta - Merged relation metadata (from `getRelationsMetadata`)
25
+ * @param conformanceFilterFn - Injected conformance-filter builder
26
+ * (avoids circular dependency back into decorators.ts)
27
+ */
28
+ export declare function buildSHACL(subjectName: string, target: any, properties: Record<string, PropertyMetadataEntry>, allRelationsMeta: Record<string, RelationMetadataEntry>, conformanceFilterFn: ConformanceFilterFn): {
29
+ shape: SHACLShape;
30
+ name: string;
31
+ };
@@ -0,0 +1,246 @@
1
+ /**
2
+ * SHACL shape generation for AD4M model classes.
3
+ *
4
+ * Builds a W3C SHACL `SHACLShape` (with AD4M-specific action extensions)
5
+ * from a model's property and relation metadata. The heavy lifting used
6
+ * to live inside the `@Model` decorator closure — it is extracted here so
7
+ * decorators.ts stays focused on decorator registration logic.
8
+ */
9
+ import { SHACLShape } from "../shacl/SHACLShape";
10
+ import { escapeSurrealString } from "../utils";
11
+ import { compileWhereClause } from "./surreal-utils";
12
+ import { propertyNameToSetterName } from "./util";
13
+ /**
14
+ * Build a SHACL shape for a model class.
15
+ *
16
+ * @param subjectName - The model's registered name (from `@Model({ name })`)
17
+ * @param target - The class constructor (used for prototype access,
18
+ * inheritance chain, and relation target resolution)
19
+ * @param properties - Merged property metadata (from `getPropertiesMetadata`)
20
+ * @param allRelationsMeta - Merged relation metadata (from `getRelationsMetadata`)
21
+ * @param conformanceFilterFn - Injected conformance-filter builder
22
+ * (avoids circular dependency back into decorators.ts)
23
+ */
24
+ export function buildSHACL(subjectName, target, properties, allRelationsMeta, conformanceFilterFn) {
25
+ const obj = target.prototype;
26
+ // ── Determine namespace from first property or relation ─────────────
27
+ let namespace = "ad4m://";
28
+ const relations = Object.fromEntries(Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));
29
+ // Try properties first
30
+ if (Object.keys(properties).length > 0) {
31
+ const firstProp = properties[Object.keys(properties)[0]];
32
+ if (firstProp.through) {
33
+ const match = firstProp.through.match(/^([^:]+:\/\/)/);
34
+ if (match) {
35
+ namespace = match[1];
36
+ }
37
+ }
38
+ }
39
+ // Fall back to relations if no properties
40
+ else if (Object.keys(relations).length > 0) {
41
+ const firstRel = relations[Object.keys(relations)[0]];
42
+ if (firstRel.predicate) {
43
+ const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
44
+ if (match) {
45
+ namespace = match[1];
46
+ }
47
+ }
48
+ }
49
+ // ── Create SHACL shape ──────────────────────────────────────────────
50
+ const shapeUri = `${namespace}${subjectName}Shape`;
51
+ const targetClass = `${namespace}${subjectName}`;
52
+ const shape = new SHACLShape(shapeUri, targetClass);
53
+ // Detect @Model inheritance — if the parent class also has
54
+ // generateSHACL it is itself a @Model and we reference its shape
55
+ // via sh:node so SHACL validators can walk the hierarchy.
56
+ const parentCtor = Object.getPrototypeOf(target);
57
+ if (parentCtor && typeof parentCtor.generateSHACL === 'function') {
58
+ const parentSHACL = parentCtor.generateSHACL();
59
+ if (parentSHACL?.shape?.nodeShapeUri) {
60
+ shape.addParentShape(parentSHACL.shape.nodeShapeUri);
61
+ }
62
+ }
63
+ // ── Constructor / Destructor actions ────────────────────────────────
64
+ let constructorActions = [];
65
+ if (obj.subjectConstructor && obj.subjectConstructor.length) {
66
+ constructorActions = constructorActions.concat(obj.subjectConstructor);
67
+ }
68
+ let destructorActions = [];
69
+ // ── Convert properties to SHACL property shapes ────────────────────
70
+ for (const propName in properties) {
71
+ const propMeta = properties[propName];
72
+ if (!propMeta.through)
73
+ continue; // Skip properties without predicates
74
+ const propShape = {
75
+ name: propName,
76
+ path: propMeta.through,
77
+ };
78
+ // Determine datatype from initial value or resolveLanguage
79
+ if (propMeta.resolveLanguage === "literal") {
80
+ propShape.datatype = "xsd://string";
81
+ }
82
+ else if (propMeta.initial) {
83
+ const initialType = typeof obj[propName];
84
+ if (initialType === "number") {
85
+ propShape.datatype = "xsd://integer";
86
+ }
87
+ else if (initialType === "boolean") {
88
+ propShape.datatype = "xsd://boolean";
89
+ }
90
+ else if (initialType === "string") {
91
+ propShape.datatype = "xsd://string";
92
+ }
93
+ }
94
+ // Cardinality constraints
95
+ if (propMeta.required) {
96
+ propShape.minCount = 1;
97
+ }
98
+ // Single-valued properties get maxCount 1
99
+ propShape.maxCount = 1;
100
+ // Flag properties have fixed value
101
+ if (propMeta.flag && propMeta.initial) {
102
+ propShape.hasValue = propMeta.initial;
103
+ }
104
+ // AD4M-specific metadata
105
+ if (propMeta.local !== undefined) {
106
+ propShape.local = propMeta.local;
107
+ }
108
+ if (propMeta.writable !== undefined) {
109
+ propShape.writable = propMeta.writable;
110
+ }
111
+ if (propMeta.resolveLanguage) {
112
+ propShape.resolveLanguage = propMeta.resolveLanguage;
113
+ }
114
+ // ── Setter actions ──────────────────────────────────────────────
115
+ if (propMeta.prologSetter) {
116
+ console.warn(`[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
117
+ `The property will be created without setter actions. Consider using standard writable properties or provide explicit SHACL JSON.`);
118
+ }
119
+ else if (propMeta.writable && propMeta.through) {
120
+ let setter = obj[propertyNameToSetterName(propName)];
121
+ if (typeof setter === "function") {
122
+ propShape.setter = [{
123
+ action: "setSingleTarget",
124
+ source: "this",
125
+ predicate: propMeta.through,
126
+ target: "value",
127
+ ...(propMeta.local && { local: true })
128
+ }];
129
+ }
130
+ }
131
+ // ── Constructor / Destructor entries ────────────────────────────
132
+ const effectiveInitial = propMeta.initial
133
+ ?? (propMeta.required && propMeta.writable && !propMeta.flag && propMeta.through
134
+ ? "literal://string:" : undefined);
135
+ if (effectiveInitial) {
136
+ constructorActions.push({
137
+ action: "addLink",
138
+ source: "this",
139
+ predicate: propMeta.through,
140
+ target: effectiveInitial,
141
+ });
142
+ destructorActions.push({
143
+ action: "removeLink",
144
+ source: "this",
145
+ predicate: propMeta.through,
146
+ target: "*",
147
+ });
148
+ }
149
+ shape.addProperty(propShape);
150
+ }
151
+ // ── Convert relations to SHACL property shapes ─────────────────────
152
+ for (const relName in relations) {
153
+ const relMeta = relations[relName];
154
+ if (!relMeta.predicate)
155
+ continue;
156
+ const relShape = {
157
+ name: relName,
158
+ path: relMeta.predicate,
159
+ };
160
+ // Relations typically contain IRIs
161
+ relShape.nodeKind = 'IRI';
162
+ // AD4M-specific metadata
163
+ if (relMeta.local !== undefined) {
164
+ relShape.local = relMeta.local;
165
+ }
166
+ // Adder action
167
+ relShape.adder = [{
168
+ action: "addLink",
169
+ source: "this",
170
+ predicate: relMeta.predicate,
171
+ target: "value",
172
+ ...(relMeta.local && { local: true })
173
+ }];
174
+ // Remover action
175
+ relShape.remover = [{
176
+ action: "removeLink",
177
+ source: "this",
178
+ predicate: relMeta.predicate,
179
+ target: "value",
180
+ ...(relMeta.local && { local: true })
181
+ }];
182
+ // ── Build Getter (conformance filter) ───────────────────────────
183
+ // Priority chain:
184
+ // 1. Explicit getter string → use verbatim
185
+ // 2. `where` clause → compile DSL to SurrealQL getter
186
+ // 3. target + filter !== false → auto-derive from shape
187
+ if (relMeta.getter) {
188
+ relShape.getter = relMeta.getter;
189
+ }
190
+ else if (relMeta.where) {
191
+ try {
192
+ const TargetClass = relMeta.target?.();
193
+ const targetMetadata = TargetClass
194
+ ? TargetClass.getModelMetadata?.() ?? null
195
+ : null;
196
+ const conditions = compileWhereClause(relMeta.where, targetMetadata);
197
+ if (conditions.length > 0) {
198
+ const escapedPredicate = escapeSurrealString(relMeta.predicate);
199
+ relShape.getter = `(->link[WHERE predicate = '${escapedPredicate}'].out[WHERE ${conditions.join(' AND ')}].uri)`;
200
+ }
201
+ }
202
+ catch (e) {
203
+ // Target metadata may not be available yet
204
+ }
205
+ }
206
+ else if (relMeta.target && relMeta.filter !== false) {
207
+ try {
208
+ const TargetClass = relMeta.target();
209
+ const filter = conformanceFilterFn(relMeta.predicate, TargetClass);
210
+ if (filter) {
211
+ relShape.getter = filter.getter;
212
+ relShape.conformanceConditions = filter.conformanceConditions;
213
+ }
214
+ }
215
+ catch (e) {
216
+ // Target class may not be available yet — getter will be
217
+ // absent and runtime will fall back to unfiltered get_links
218
+ }
219
+ }
220
+ // ── sh:class — target shape reference ───────────────────────────
221
+ if (relMeta.target) {
222
+ try {
223
+ const TargetClass = relMeta.target();
224
+ const targetSHACL = TargetClass.generateSHACL?.();
225
+ if (targetSHACL?.shape?.nodeShapeUri) {
226
+ relShape.class = targetSHACL.shape.nodeShapeUri;
227
+ }
228
+ }
229
+ catch (e) {
230
+ // Target class may not be available yet
231
+ }
232
+ }
233
+ shape.addProperty(relShape);
234
+ }
235
+ // Always set constructor and destructor actions on the shape, even
236
+ // when empty. An empty array serialises to `literal://string:[]`
237
+ // which the Rust executor parses as a valid (no-op) command list,
238
+ // avoiding "No SHACL constructor found" errors for models whose
239
+ // properties are all optional and have no @Flag.
240
+ shape.setConstructorActions(constructorActions);
241
+ shape.setDestructorActions(destructorActions);
242
+ return {
243
+ shape,
244
+ name: subjectName
245
+ };
246
+ }
@@ -4,7 +4,7 @@
4
4
  * These functions are used by both the runtime query builder (`Ad4mModel`) and
5
5
  * the compile-time SHACL generator (`decorators.ts`).
6
6
  */
7
- import type { WhereCondition, Where, ModelMetadata } from "./Ad4mModel";
7
+ import type { WhereCondition, Where, ModelMetadata } from "./types";
8
8
  /**
9
9
  * Format a JavaScript value for embedding in a SurrealQL expression.
10
10
  *
@@ -1,11 +1,12 @@
1
1
  /**
2
- * Public types for the AD4M model layer.
2
+ * Shared type definitions for the Ad4mModel system.
3
3
  *
4
- * Extracted from Ad4mModel.ts so they can be imported by query builders,
5
- * hydration helpers, and external consumers without pulling in the full
6
- * Ad4mModel class.
4
+ * Extracted into a standalone module so that utility files
5
+ * (`surreal-utils.ts`, `decorators.ts`, etc.) can import types without
6
+ * creating circular runtime dependencies on `Ad4mModel.ts`.
7
7
  */
8
- type WhereOps = {
8
+ import type { Ad4mModel } from "./Ad4mModel";
9
+ export type WhereOps = {
9
10
  not: string | number | boolean | string[] | number[];
10
11
  between: [number, number];
11
12
  lt: number;
@@ -24,109 +25,78 @@ export type Order = {
24
25
  [propertyName: string]: "ASC" | "DESC";
25
26
  };
26
27
  /**
27
- * Prisma-style eager-loading map.
28
+ * Discriminated union for parent-scoped queries.
28
29
  *
29
- * Key = relation field name on the model.
30
- * Value = `true` (hydrate all with no filter) or a `Query` to
31
- * filter / order / limit the nested set.
30
+ * **Model form** (preferred) — predicate auto-resolved from the parent model's
31
+ * relation metadata. Use `field` to disambiguate when the parent has multiple
32
+ * relations targeting the same child class.
32
33
  *
33
- * @example
34
- * ```typescript
35
- * Recipe.findAll(perspective, {
36
- * include: {
37
- * comments: true,
38
- * tags: { where: { active: true }, order: { name: 'ASC' }, limit: 5 },
39
- * },
40
- * });
41
- * ```
34
+ * **Raw form** — explicit predicate string, no metadata lookup.
42
35
  */
43
- export type IncludeMap = {
44
- [relationName: string]: true | Query;
45
- };
46
- /**
47
- * Minimal interface a parent model class must satisfy for the model-backed
48
- * `parent` query form. Avoids a circular import between types.ts and Ad4mModel.ts.
49
- */
50
- type ParentQueryParentCtor = {
51
- getModelMetadata(): ModelMetadata;
52
- };
53
- /** Raw predicate form — use for ad-hoc or cross-package predicates. */
54
- export type ParentQueryByPredicate = {
36
+ export type ParentScope = {
37
+ model: typeof Ad4mModel;
38
+ id: string;
39
+ field?: string;
40
+ } | {
55
41
  id: string;
56
42
  predicate: string;
57
43
  };
58
44
  /**
59
- * Model-backed form — DRY alternative that resolves the predicate from the
60
- * parent model's `@HasMany` decorator metadata at query time.
45
+ * Describes which relations to eager-load when querying.
46
+ *
47
+ * Each value is either:
48
+ * - `true` — hydrate the relation one level deep
49
+ * - A `RelationSubQuery` — scoped sub-query (filter / sort / paginate / nested include)
50
+ *
51
+ * @example
52
+ * ```typescript
53
+ * // One level deep
54
+ * { comments: true }
55
+ *
56
+ * // Sub-query: only the 5 most-recent comments
57
+ * { comments: { order: { createdAt: 'DESC' }, limit: 5 } }
58
+ *
59
+ * // Nested eager-load
60
+ * { comments: { include: { author: true } } }
61
+ * ```
61
62
  */
62
- export type ParentQueryByModel = {
63
- id: string;
64
- model: ParentQueryParentCtor;
65
- /** The `@HasMany` field name on `model`. Optional when unambiguous. */
66
- field?: string;
67
- };
68
- /** Union of the two `parent` query forms accepted by {@link Query}. */
69
- export type ParentQuery = ParentQueryByPredicate | ParentQueryByModel;
63
+ export interface IncludeMap {
64
+ [relation: string]: boolean | RelationSubQuery;
65
+ }
70
66
  export type Query = {
67
+ /** Filter to instances that are the target of a link from a given parent. */
68
+ parent?: ParentScope;
71
69
  properties?: string[];
72
- /** Eagerly hydrate relations. Key = field name; value = `true` or a sub-`Query`. See {@link IncludeMap}. */
73
70
  include?: IncludeMap;
74
71
  where?: Where;
75
72
  order?: Order;
76
73
  offset?: number;
77
74
  limit?: number;
78
75
  count?: boolean;
79
- /**
80
- * When provided, restricts results to instances reachable from the given
81
- * parent node via the given predicate.
82
- *
83
- * The subscription layer also watches this predicate so that adding or
84
- * removing a child link triggers a live re-query.
85
- *
86
- * Two equivalent forms are accepted:
87
- * - Raw: `{ id, predicate }` — use for ad-hoc / foreign predicates.
88
- * - Model-backed: `{ id, model, field? }` — DRY, refactor-safe; the
89
- * predicate is resolved automatically from the parent model's `@HasMany`
90
- * decorator metadata. `field` is the `@HasMany` field name; when the
91
- * parent has exactly one `@HasMany` pointing to the child type it may be
92
- * omitted (but is recommended for clarity).
93
- *
94
- * @example
95
- * // Raw form (still valid for foreign predicates)
96
- * parent: { id: parentId, predicate: 'custom://my_pred' }
97
- *
98
- * // Model-backed form (preferred for schema-declared relations)
99
- * parent: { id: poll.id, model: Poll, field: 'answers' }
100
- */
101
- parent?: ParentQuery;
102
76
  };
103
77
  /**
104
- * Extends `Query` (minus `count`) with subscription delivery options.
105
- * Pass to {@link Ad4mModel.subscribe} or the builder's `.subscribe()`.
78
+ * Sub-query options for a specific relation inside an `IncludeMap`.
79
+ *
80
+ * Equivalent to `Query` without top-level scoping (`parent`) or `count`,
81
+ * since the result set is already constrained to the linked relation.
82
+ *
83
+ * @example
84
+ * ```typescript
85
+ * await post.get({ include: { comments: { order: { createdAt: 'DESC' }, limit: 5 } } });
86
+ * ```
106
87
  */
107
- export type SubscribeOptions = Omit<Query, "count"> & {
108
- /**
109
- * Debounce delay in milliseconds. Multiple link changes within this window
110
- * trigger only one re-query. Default: `0` (no debouncing).
111
- */
112
- debounce?: number;
113
- /**
114
- * Called when the re-query or the callback throws.
115
- * Defaults to `console.error` so failures are always visible without
116
- * requiring every caller to handle them.
117
- */
118
- onError?: (err: Error) => void;
119
- };
88
+ export type RelationSubQuery = Omit<Query, 'parent' | 'count'>;
120
89
  /**
121
- * Handle returned by `Ad4mModel.subscribe()`. Call `unsubscribe()` in cleanup.
122
- * `lastError` holds the most recent unhandled error, or `null`.
90
+ * Options accepted by the instance `get()` method.
91
+ *
92
+ * A subset of `Query` — only hydration controls apply to a single known instance.
123
93
  */
124
- export type Subscription = {
125
- unsubscribe(): void;
126
- /** The most recent unhandled error from re-query or callback, or `null`. */
127
- readonly lastError: Error | null;
94
+ export type GetOptions = Pick<Query, 'include' | 'properties'>;
95
+ export type AllInstancesResult = {
96
+ AllInstances: Ad4mModel[];
97
+ TotalCount?: number;
98
+ isInit?: boolean;
128
99
  };
129
- export type AllInstancesResult = any;
130
100
  export type ResultsWithTotalCount<T> = {
131
101
  results: T[];
132
102
  totalCount?: number;
@@ -137,6 +107,7 @@ export type PaginationResult<T> = {
137
107
  pageSize: number;
138
108
  pageNumber: number;
139
109
  };
110
+ export type ValueTuple = [name: string, value: any, resolve?: boolean];
140
111
  /**
141
112
  * Metadata for a single property extracted from decorators.
142
113
  */
@@ -147,12 +118,16 @@ export interface PropertyMetadata {
147
118
  predicate: string;
148
119
  /** Whether the property is required */
149
120
  required: boolean;
150
- /** Whether the property is read-only (default: false, i.e. writable) */
151
- readOnly?: boolean;
121
+ /** Whether the property is read-only */
122
+ readOnly: boolean;
152
123
  /** Initial value if specified */
153
124
  initial?: string;
154
125
  /** Language for resolution (e.g., "literal") */
155
126
  resolveLanguage?: string;
127
+ /** Custom Prolog getter code */
128
+ prologGetter?: string;
129
+ /** Custom Prolog setter code */
130
+ prologSetter?: string;
156
131
  /** Custom SurrealQL getter code */
157
132
  getter?: string;
158
133
  /** Whether stored locally only */
@@ -174,22 +149,26 @@ export interface RelationMetadata {
174
149
  getter?: string;
175
150
  /** Whether stored locally only */
176
151
  local?: boolean;
177
- /** Traversal direction — "forward" (default) for @HasMany/@HasOne, "reverse" for @BelongsToOne/@BelongsToMany */
178
- direction?: "forward" | "reverse";
179
- /** Maximum number of results (1 for @BelongsToOne / @HasOne) */
180
- maxCount?: number;
181
- /** Model factory for eager hydration — set when decorator is called with () => ModelClass */
182
- relatedModel?: () => any;
152
+ /** Link direction: 'forward' for HasMany/HasOne, 'reverse' for BelongsToMany/BelongsToOne */
153
+ direction?: 'forward' | 'reverse';
154
+ /** Target model class thunk for hydration and type filtering */
155
+ target?: () => any;
156
+ /**
157
+ * Whether to auto-generate a conformance filter when `target` is set.
158
+ * Defaults to `true` — set to `false` to opt out of DB-level type filtering.
159
+ */
160
+ filter?: boolean;
161
+ /** Where clause for relation filtering (query DSL) */
162
+ where?: Where;
183
163
  }
184
164
  /**
185
165
  * Complete model metadata extracted from decorators.
186
166
  */
187
167
  export interface ModelMetadata {
188
- /** The model class name from @ModelOptions */
168
+ /** The model class name from @Model */
189
169
  className: string;
190
170
  /** Map of property name to metadata */
191
171
  properties: Record<string, PropertyMetadata>;
192
172
  /** Map of relation name to metadata */
193
173
  relations: Record<string, RelationMetadata>;
194
174
  }
195
- export {};
@@ -1,8 +1,8 @@
1
1
  /**
2
- * Public types for the AD4M model layer.
2
+ * Shared type definitions for the Ad4mModel system.
3
3
  *
4
- * Extracted from Ad4mModel.ts so they can be imported by query builders,
5
- * hydration helpers, and external consumers without pulling in the full
6
- * Ad4mModel class.
4
+ * Extracted into a standalone module so that utility files
5
+ * (`surreal-utils.ts`, `decorators.ts`, etc.) can import types without
6
+ * creating circular runtime dependencies on `Ad4mModel.ts`.
7
7
  */
8
8
  export {};
@@ -1,12 +1,11 @@
1
1
  export declare function capitalize(str: string): string;
2
2
  export declare function propertyNameToSetterName(property: string): string;
3
- export declare function setterNameToPropertyName(setter: string): string;
4
- export declare function singularToPlural(singular: string): string;
5
3
  export declare function pluralToSingular(plural: string): string;
6
4
  export declare function relationToAdderName(relation: string): string;
7
- export declare function relationAdderToName(adderName: string): string;
8
5
  export declare function relationToRemoverName(relation: string): string;
9
- export declare function relationRemoverToName(removerName: string): string;
10
- export declare function relationSetterToName(setterName: string): string;
11
6
  export declare function relationToSetterName(relation: string): string;
7
+ /**
8
+ * Generate a random identifier string of the given length (lowercase alpha).
9
+ */
10
+ export declare function makeRandomId(length: number): string;
12
11
  export declare function stringifyObjectLiteral(obj: any): any;
@@ -5,18 +5,6 @@ export function capitalize(str) {
5
5
  export function propertyNameToSetterName(property) {
6
6
  return `set${capitalize(property)}`;
7
7
  }
8
- // e.g. "setName" -> "name"
9
- export function setterNameToPropertyName(setter) {
10
- return setter.replace("set", "").replace(/^[A-Z]/, (m) => m.toLowerCase());
11
- }
12
- export function singularToPlural(singular) {
13
- if (singular.endsWith("y")) {
14
- return singular.slice(0, -1) + "ies";
15
- }
16
- else {
17
- return singular + "s";
18
- }
19
- }
20
8
  export function pluralToSingular(plural) {
21
9
  if (plural.endsWith("ies")) {
22
10
  return plural.slice(0, -3) + "y";
@@ -32,34 +20,26 @@ export function pluralToSingular(plural) {
32
20
  export function relationToAdderName(relation) {
33
21
  return `add${capitalize(pluralToSingular(relation))}`;
34
22
  }
35
- // e.g. "addComments" -> "comments"
36
- export function relationAdderToName(adderName) {
37
- // Extract the relation name after "add" and lowercase first char
38
- // The method name already has the plural relation name (e.g., "addComments")
39
- let relationName = adderName.substring(3);
40
- return relationName.charAt(0).toLowerCase() + relationName.slice(1);
41
- }
42
23
  // e.g. "comments" -> "removeComment"
43
24
  export function relationToRemoverName(relation) {
44
25
  return `remove${capitalize(pluralToSingular(relation))}`;
45
26
  }
46
- // e.g. "removeComments" -> "comments"
47
- export function relationRemoverToName(removerName) {
48
- // Extract the relation name after "remove" and lowercase first char
49
- // The method name already has the plural relation name (e.g., "removeComments")
50
- let relationName = removerName.substring(6);
51
- return relationName.charAt(0).toLowerCase() + relationName.slice(1);
52
- }
53
- export function relationSetterToName(setterName) {
54
- // Extract the relation name after "set" and lowercase first char
55
- // The method name already has the plural relation name (e.g., "setComments")
56
- let relationName = setterName.substring(3);
57
- return relationName.charAt(0).toLowerCase() + relationName.slice(1);
58
- }
59
27
  // e.g. "comments" -> "setComments"
60
28
  export function relationToSetterName(relation) {
61
29
  return `set${capitalize(relation)}`;
62
30
  }
31
+ /**
32
+ * Generate a random identifier string of the given length (lowercase alpha).
33
+ */
34
+ export function makeRandomId(length) {
35
+ let result = '';
36
+ const characters = 'abcdefghijklmnopqrstuvwxyz';
37
+ const charactersLength = characters.length;
38
+ for (let i = 0; i < length; i++) {
39
+ result += characters.charAt(Math.floor(Math.random() * charactersLength));
40
+ }
41
+ return result;
42
+ }
63
43
  export function stringifyObjectLiteral(obj) {
64
44
  if (Array.isArray(obj)) {
65
45
  //@ts-ignore
@@ -9,7 +9,7 @@ import { Perspective } from "./Perspective";
9
9
  import { PerspectiveHandle, PerspectiveState } from "./PerspectiveHandle";
10
10
  import { LinkStatus, PerspectiveProxy } from './PerspectiveProxy';
11
11
  import { AIClient } from "../ai/AIClient";
12
- import { AllInstancesResult } from "../model/Ad4mModel";
12
+ import { AllInstancesResult } from "../model/types";
13
13
  export type PerspectiveHandleCallback = (perspective: PerspectiveHandle) => null;
14
14
  export type UuidCallback = (uuid: string) => null;
15
15
  export type LinkCallback = (link: LinkExpression) => null;
@@ -7,7 +7,7 @@ import { ExpressionRendered } from "../expression/Expression";
7
7
  import { NeighbourhoodProxy } from "../neighbourhood/NeighbourhoodProxy";
8
8
  import { NeighbourhoodExpression } from "../neighbourhood/Neighbourhood";
9
9
  import { AIClient } from "../ai/AIClient";
10
- import { AllInstancesResult } from "../model/Ad4mModel";
10
+ import { AllInstancesResult } from "../model/types";
11
11
  import { SHACLShape } from "../shacl/SHACLShape";
12
12
  import { SHACLFlow } from "../shacl/SHACLFlow";
13
13
  type QueryCallback = (result: AllInstancesResult) => void;