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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/lib/index.cjs +5052 -4446
  2. package/lib/index.js +5019 -4442
  3. package/lib/src/agent/AgentClient.d.ts +4 -0
  4. package/lib/src/agent/AgentClient.js +34 -0
  5. package/lib/src/index.d.ts +2 -3
  6. package/lib/src/index.js +2 -3
  7. package/lib/src/model/Ad4mModel.d.ts +8 -782
  8. package/lib/src/model/Ad4mModel.js +160 -2354
  9. package/lib/src/model/ModelQueryBuilder.d.ts +370 -0
  10. package/lib/src/model/ModelQueryBuilder.js +556 -0
  11. package/lib/src/model/decorators.d.ts +71 -23
  12. package/lib/src/model/decorators.js +133 -384
  13. package/lib/src/model/hydration.d.ts +102 -0
  14. package/lib/src/model/hydration.js +709 -0
  15. package/lib/src/model/index.d.ts +20 -0
  16. package/lib/src/model/index.js +20 -0
  17. package/lib/src/model/{schema/fromJSONSchema.d.ts → json-schema.d.ts} +45 -12
  18. package/lib/src/model/json-schema.js +326 -0
  19. package/lib/src/model/prolog-facts.d.ts +37 -0
  20. package/lib/src/model/{prolog/generatePrologFacts.js → prolog-facts.js} +47 -52
  21. package/lib/src/model/query-common.d.ts +14 -0
  22. package/lib/src/model/query-common.js +36 -0
  23. package/lib/src/model/query-prolog.d.ts +15 -0
  24. package/lib/src/model/query-prolog.js +140 -0
  25. package/lib/src/model/query-surreal.d.ts +44 -0
  26. package/lib/src/model/query-surreal.js +249 -0
  27. package/lib/src/model/relation-filtering.test.js +838 -0
  28. package/lib/src/model/sdna.d.ts +14 -0
  29. package/lib/src/model/sdna.js +141 -0
  30. package/lib/src/model/shacl-gen.d.ts +31 -0
  31. package/lib/src/model/shacl-gen.js +246 -0
  32. package/lib/src/model/surreal-utils.d.ts +42 -0
  33. package/lib/src/model/surreal-utils.js +128 -0
  34. package/lib/src/model/types.d.ts +75 -96
  35. package/lib/src/model/types.js +4 -4
  36. package/lib/src/model/util.d.ts +4 -5
  37. package/lib/src/model/util.js +12 -32
  38. package/lib/src/perspectives/PerspectiveClient.d.ts +1 -1
  39. package/lib/src/perspectives/PerspectiveProxy.d.ts +1 -1
  40. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +79 -0
  41. package/lib/src/perspectives/WakerSubscriptionManager.js +196 -0
  42. package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
  43. package/lib/src/runtime/RuntimeResolver.js +73 -0
  44. package/lib/src/schema.gql +14 -0
  45. package/lib/src/shacl/SHACLShape.d.ts +23 -0
  46. package/lib/src/shacl/SHACLShape.js +45 -0
  47. package/lib/src/typeDefs.js +14 -0
  48. package/package.json +13 -8
  49. package/src/agent/AgentClient.ts +45 -0
  50. package/src/index.ts +2 -3
  51. package/src/model/Ad4mModel.ts +1089 -3686
  52. package/src/model/ModelQueryBuilder.ts +617 -0
  53. package/src/model/Subject.ts +1 -1
  54. package/src/model/decorators.ts +218 -453
  55. package/src/model/hydration.ts +796 -0
  56. package/src/model/index.ts +21 -0
  57. package/src/model/json-schema.ts +424 -0
  58. package/src/model/prolog-facts.ts +145 -0
  59. package/src/model/query-common.ts +48 -0
  60. package/src/model/query-prolog.ts +148 -0
  61. package/src/model/query-surreal.ts +280 -0
  62. package/src/model/relation-filtering.test.ts +803 -0
  63. package/src/model/sdna.ts +170 -0
  64. package/src/model/shacl-gen.ts +292 -0
  65. package/src/model/surreal-utils.ts +147 -0
  66. package/src/model/types.ts +182 -0
  67. package/src/model/util.ts +13 -36
  68. package/src/perspectives/PerspectiveClient.ts +1 -1
  69. package/src/perspectives/PerspectiveProxy.ts +1 -1
  70. package/src/perspectives/WakerSubscriptionManager.ts +292 -0
  71. package/src/runtime/RuntimeResolver.ts +53 -0
  72. package/src/shacl/SHACLShape.ts +83 -0
  73. package/lib/src/Ad4mClient.test.js +0 -1204
  74. package/lib/src/Literal.test.d.ts +0 -1
  75. package/lib/src/Literal.test.js +0 -41
  76. package/lib/src/model/mutation.d.ts +0 -81
  77. package/lib/src/model/mutation.js +0 -317
  78. package/lib/src/model/parentUtils.d.ts +0 -32
  79. package/lib/src/model/parentUtils.js +0 -64
  80. package/lib/src/model/prolog/generatePrologFacts.d.ts +0 -36
  81. package/lib/src/model/prolog/index.d.ts +0 -1
  82. package/lib/src/model/prolog/index.js +0 -1
  83. package/lib/src/model/query/ModelQueryBuilder.d.ts +0 -82
  84. package/lib/src/model/query/ModelQueryBuilder.js +0 -115
  85. package/lib/src/model/query/QueryBuilder.d.ts +0 -101
  86. package/lib/src/model/query/QueryBuilder.js +0 -193
  87. package/lib/src/model/query/SurrealQueryBuilder.d.ts +0 -48
  88. package/lib/src/model/query/SurrealQueryBuilder.js +0 -371
  89. package/lib/src/model/query/fetchInstance.d.ts +0 -24
  90. package/lib/src/model/query/fetchInstance.js +0 -144
  91. package/lib/src/model/query/hydration.d.ts +0 -54
  92. package/lib/src/model/query/hydration.js +0 -214
  93. package/lib/src/model/query/operations.d.ts +0 -59
  94. package/lib/src/model/query/operations.js +0 -384
  95. package/lib/src/model/query/snapshot.d.ts +0 -59
  96. package/lib/src/model/query/snapshot.js +0 -106
  97. package/lib/src/model/query/surrealCompiler.d.ts +0 -42
  98. package/lib/src/model/query/surrealCompiler.js +0 -304
  99. package/lib/src/model/schema/fromJSONSchema.js +0 -264
  100. package/lib/src/model/schema/metadata.d.ts +0 -15
  101. package/lib/src/model/schema/metadata.js +0 -112
  102. package/lib/src/model/subscription.d.ts +0 -47
  103. package/lib/src/model/subscription.js +0 -231
  104. package/lib/src/model/transaction.d.ts +0 -27
  105. package/lib/src/model/transaction.js +0 -32
  106. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  107. package/lib/src/shims/type-graphql.d.ts +0 -32
  108. package/lib/src/src/Ad4mClient.d.ts +0 -28
  109. package/lib/src/src/Address.d.ts +0 -1
  110. package/lib/src/src/DID.d.ts +0 -1
  111. package/lib/src/src/Exception.d.ts +0 -7
  112. package/lib/src/src/Literal.d.ts +0 -7
  113. package/lib/src/src/PubSub.d.ts +0 -17
  114. package/lib/src/src/SmartLiteral.d.ts +0 -12
  115. package/lib/src/src/agent/Agent.d.ts +0 -110
  116. package/lib/src/src/agent/AgentClient.d.ts +0 -62
  117. package/lib/src/src/agent/AgentResolver.d.ts +0 -30
  118. package/lib/src/src/agent/AgentStatus.d.ts +0 -8
  119. package/lib/src/src/ai/AIClient.d.ts +0 -32
  120. package/lib/src/src/ai/AIResolver.d.ts +0 -75
  121. package/lib/src/src/ai/Tasks.d.ts +0 -37
  122. package/lib/src/src/buildSchema.d.ts +0 -1
  123. package/lib/src/src/expression/Expression.d.ts +0 -28
  124. package/lib/src/src/expression/ExpressionClient.d.ts +0 -13
  125. package/lib/src/src/expression/ExpressionRef.d.ts +0 -9
  126. package/lib/src/src/expression/ExpressionResolver.d.ts +0 -10
  127. package/lib/src/src/index.d.ts +0 -35
  128. package/lib/src/src/jestSetup.d.ts +0 -1
  129. package/lib/src/src/language/Icon.d.ts +0 -4
  130. package/lib/src/src/language/Language.d.ts +0 -206
  131. package/lib/src/src/language/LanguageClient.d.ts +0 -17
  132. package/lib/src/src/language/LanguageContext.d.ts +0 -37
  133. package/lib/src/src/language/LanguageHandle.d.ts +0 -9
  134. package/lib/src/src/language/LanguageMeta.d.ts +0 -35
  135. package/lib/src/src/language/LanguageRef.d.ts +0 -6
  136. package/lib/src/src/language/LanguageResolver.d.ts +0 -19
  137. package/lib/src/src/links/Links.d.ts +0 -39
  138. package/lib/src/src/links/Links.test.d.ts +0 -1
  139. package/lib/src/src/model/Ad4mModel.d.ts +0 -1438
  140. package/lib/src/src/model/Ad4mModel.test.d.ts +0 -1
  141. package/lib/src/src/model/Subject.d.ts +0 -25
  142. package/lib/src/src/model/decorators.d.ts +0 -545
  143. package/lib/src/src/model/util.d.ts +0 -12
  144. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +0 -10
  145. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +0 -25
  146. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +0 -19
  147. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +0 -1
  148. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +0 -24
  149. package/lib/src/src/perspectives/LinkQuery.d.ts +0 -11
  150. package/lib/src/src/perspectives/Perspective.d.ts +0 -38
  151. package/lib/src/src/perspectives/Perspective.test.d.ts +0 -1
  152. package/lib/src/src/perspectives/PerspectiveClient.d.ts +0 -97
  153. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +0 -9
  154. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +0 -18
  155. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +0 -865
  156. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +0 -57
  157. package/lib/src/src/runtime/RuntimeClient.d.ts +0 -56
  158. package/lib/src/src/runtime/RuntimeResolver.d.ts +0 -132
  159. package/lib/src/src/shacl/SHACLFlow.d.ts +0 -171
  160. package/lib/src/src/shacl/SHACLFlow.test.d.ts +0 -1
  161. package/lib/src/src/shacl/SHACLShape.d.ts +0 -117
  162. package/lib/src/src/shacl/SHACLShape.test.d.ts +0 -1
  163. package/lib/src/src/typeDefs.d.ts +0 -1
  164. package/lib/src/src/unwrapApolloResult.d.ts +0 -2
  165. package/lib/src/src/utils.d.ts +0 -25
  166. /package/lib/src/{Ad4mClient.test.d.ts → model/relation-filtering.test.d.ts} +0 -0
@@ -1,201 +1,7 @@
1
1
  import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
2
- import { PropertyOptions } from "./decorators";
3
- interface JSONSchemaProperty {
4
- type: string | string[];
5
- items?: JSONSchemaProperty;
6
- properties?: {
7
- [key: string]: JSONSchemaProperty;
8
- };
9
- required?: string[];
10
- "x-ad4m"?: {
11
- through?: string;
12
- resolveLanguage?: string;
13
- local?: boolean;
14
- writable?: boolean;
15
- initial?: string;
16
- };
17
- }
18
- interface JSONSchema {
19
- $schema?: string;
20
- title?: string;
21
- $id?: string;
22
- type?: string;
23
- properties?: {
24
- [key: string]: JSONSchemaProperty;
25
- };
26
- required?: string[];
27
- "x-ad4m"?: {
28
- namespace?: string;
29
- className?: string;
30
- };
31
- }
32
- interface JSONSchemaToModelOptions {
33
- name: string;
34
- namespace?: string;
35
- predicateTemplate?: string;
36
- predicateGenerator?: (title: string, property: string) => string;
37
- propertyMapping?: Record<string, string>;
38
- resolveLanguage?: string;
39
- local?: boolean;
40
- propertyOptions?: Record<string, Partial<PropertyOptions>>;
41
- }
42
- type ValueTuple = [name: string, value: any, resolve?: boolean];
43
- type WhereOps = {
44
- not: string | number | boolean | string[] | number[];
45
- between: [number, number];
46
- lt: number;
47
- lte: number;
48
- gt: number;
49
- gte: number;
50
- contains: string | number;
51
- };
52
- type WhereCondition = string | number | boolean | string[] | number[] | {
53
- [K in keyof WhereOps]?: WhereOps[K];
54
- };
55
- type Where = {
56
- [propertyName: string]: WhereCondition;
57
- };
58
- type Order = {
59
- [propertyName: string]: "ASC" | "DESC";
60
- };
61
- /**
62
- * Discriminated union for parent-scoped queries.
63
- *
64
- * **Model form** (preferred) — predicate auto-resolved from the parent model's
65
- * relation metadata. Use `field` to disambiguate when the parent has multiple
66
- * relations targeting the same child class.
67
- *
68
- * **Raw form** — explicit predicate string, no metadata lookup.
69
- */
70
- export type ParentScope = {
71
- model: typeof Ad4mModel;
72
- id: string;
73
- field?: string;
74
- } | {
75
- id: string;
76
- predicate: string;
77
- };
78
- /**
79
- * Describes which relations to eager-load when querying.
80
- *
81
- * Each value is either:
82
- * - `true` — hydrate the relation one level deep
83
- * - A `RelationSubQuery` — scoped sub-query (filter / sort / paginate / nested include)
84
- *
85
- * @example
86
- * ```typescript
87
- * // One level deep
88
- * { comments: true }
89
- *
90
- * // Sub-query: only the 5 most-recent comments
91
- * { comments: { order: { createdAt: 'DESC' }, limit: 5 } }
92
- *
93
- * // Nested eager-load
94
- * { comments: { include: { author: true } } }
95
- * ```
96
- */
97
- export interface IncludeMap {
98
- [relation: string]: boolean | RelationSubQuery;
99
- }
100
- export type Query = {
101
- /** Filter to instances that are the target of a link from a given parent. */
102
- parent?: ParentScope;
103
- properties?: string[];
104
- include?: IncludeMap;
105
- where?: Where;
106
- order?: Order;
107
- offset?: number;
108
- limit?: number;
109
- count?: boolean;
110
- };
111
- /**
112
- * Sub-query options for a specific relation inside an `IncludeMap`.
113
- *
114
- * Equivalent to `Query` without top-level scoping (`parent`) or `count`,
115
- * since the result set is already constrained to the linked relation.
116
- *
117
- * @example
118
- * ```typescript
119
- * await post.get({ include: { comments: { order: { createdAt: 'DESC' }, limit: 5 } } });
120
- * ```
121
- */
122
- export type RelationSubQuery = Omit<Query, 'parent' | 'count'>;
123
- /**
124
- * Options accepted by the instance `get()` method.
125
- *
126
- * A subset of `Query` — only hydration controls apply to a single known instance.
127
- */
128
- export type GetOptions = Pick<Query, 'include' | 'properties'>;
129
- export type AllInstancesResult = {
130
- AllInstances: Ad4mModel[];
131
- TotalCount?: number;
132
- isInit?: boolean;
133
- };
134
- export type ResultsWithTotalCount<T> = {
135
- results: T[];
136
- totalCount?: number;
137
- };
138
- export type PaginationResult<T> = {
139
- results: T[];
140
- totalCount?: number;
141
- pageSize: number;
142
- pageNumber: number;
143
- };
144
- /**
145
- * Metadata for a single property extracted from decorators.
146
- */
147
- export interface PropertyMetadata {
148
- /** The property name */
149
- name: string;
150
- /** The predicate URI (through value) */
151
- predicate: string;
152
- /** Whether the property is required */
153
- required: boolean;
154
- /** Whether the property is read-only */
155
- readOnly: boolean;
156
- /** Initial value if specified */
157
- initial?: string;
158
- /** Language for resolution (e.g., "literal") */
159
- resolveLanguage?: string;
160
- /** Custom Prolog getter code */
161
- prologGetter?: string;
162
- /** Custom Prolog setter code */
163
- prologSetter?: string;
164
- /** Custom SurrealQL getter code */
165
- getter?: string;
166
- /** Whether stored locally only */
167
- local?: boolean;
168
- /** Transform function */
169
- transform?: (value: any) => any;
170
- /** Whether this is a flag property */
171
- flag?: boolean;
172
- }
173
- /**
174
- * Metadata for a single relation extracted from decorators.
175
- */
176
- export interface RelationMetadata {
177
- /** The relation name */
178
- name: string;
179
- /** The predicate URI (through value) */
180
- predicate: string;
181
- /** Custom SurrealQL getter code */
182
- getter?: string;
183
- /** Whether stored locally only */
184
- local?: boolean;
185
- /** Link direction: 'forward' for HasMany/HasOne, 'reverse' for BelongsToMany/BelongsToOne */
186
- direction?: 'forward' | 'reverse';
187
- }
188
- /**
189
- * Complete model metadata extracted from decorators.
190
- */
191
- export interface ModelMetadata {
192
- /** The model class name from @Model */
193
- className: string;
194
- /** Map of property name to metadata */
195
- properties: Record<string, PropertyMetadata>;
196
- /** Map of relation name to metadata */
197
- relations: Record<string, RelationMetadata>;
198
- }
2
+ import type { JSONSchema, JSONSchemaToModelOptions } from "./json-schema";
3
+ import { ModelQueryBuilder } from "./ModelQueryBuilder";
4
+ import type { ParentScope, IncludeMap, Query, GetOptions, AllInstancesResult, ResultsWithTotalCount, PaginationResult, ModelMetadata, ValueTuple } from "./types";
199
5
  /**
200
6
  * Base class for defining data models in AD4M.
201
7
  *
@@ -294,7 +100,6 @@ export interface ModelMetadata {
294
100
  */
295
101
  export declare class Ad4mModel {
296
102
  private _baseExpression;
297
- private _subjectClassName;
298
103
  private _perspective;
299
104
  private _snapshot;
300
105
  author: string;
@@ -397,7 +202,7 @@ export declare class Ad4mModel {
397
202
  */
398
203
  protected get perspective(): PerspectiveProxy;
399
204
  /**
400
- * Get property metadata from decorator (Phase 1: Prolog-free refactor)
205
+ * Get property metadata from decorator.
401
206
  * @private
402
207
  */
403
208
  private getPropertyMetadata;
@@ -407,70 +212,20 @@ export declare class Ad4mModel {
407
212
  */
408
213
  private getRelationOptions;
409
214
  /**
410
- * Generate property setter action from metadata (Phase 1: Prolog-free refactor)
411
- * Replaces Prolog query: property_setter(C, key, Setter)
215
+ * Generate property setter action from metadata.
412
216
  * @private
413
217
  */
414
218
  private generatePropertySetterAction;
415
219
  /**
416
- * Generate relation action from metadata (Phase 1: Prolog-free refactor)
417
- * Replaces Prolog queries: collection_adder, collection_remover, collection_setter
220
+ * Generate relation action from metadata.
418
221
  * @private
419
222
  */
420
223
  private generateRelationAction;
421
224
  /**
422
- * Resolves a raw link target value into a hydrated property value.
423
- *
424
- * Handles, in order:
425
- * 1. Non-literal expression resolution (`perspective.getExpression`)
426
- * 2. Literal URI parsing (`Literal.fromUrl(…).get()`)
427
- * 3. Primitive type coercion (string → number / boolean)
428
- * 4. Transform function application
429
- *
430
- * @param target - The raw target string from the link
431
- * @param propMeta - Property metadata from the decorator registry
432
- * @param perspective - The perspective for expression resolution
433
- * @param expectedType - Optional JS typeof hint for coercion (e.g. 'number')
434
- * @returns The resolved value
435
- * @private
436
- */
437
- private static hydratePropertyValue;
438
- /**
439
- * Link shape accepted by `hydrateFromLinks`.
440
- * Both `getData()` and `instancesFromSurrealResult()` produce this shape.
441
- */
442
- private static readonly _linkShape;
443
- /**
444
- * Hydrates an instance from an array of raw links.
445
- *
446
- * Processes properties (latest-wins semantics), relations
447
- * (chronological accumulation), and timestamps/author in a single
448
- * pass over the links array.
449
- *
450
- * @param instance - The blank model instance to populate
451
- * @param links - Array of link objects (predicate, target, author?, timestamp?)
452
- * @param metadata - Model metadata from `getModelMetadata()`
453
- * @param perspective - The perspective for expression resolution
454
- * @param requestedProperties - Optional sparse fieldset; when provided, only these
455
- * property names are hydrated (relations are unaffected).
456
- * Omit or pass `undefined` to hydrate all properties.
457
- * @private
225
+ * Assigns decoded Prolog property values to an instance.
226
+ * Delegates to the standalone function in hydration.ts.
458
227
  */
459
- private static hydrateFromLinks;
460
228
  static assignValuesToInstance(perspective: PerspectiveProxy, instance: Ad4mModel, values: ValueTuple[]): Promise<void>;
461
- /**
462
- * Captures a shallow snapshot of the instance's current property and
463
- * relation values. Called automatically after hydration (`get()`,
464
- * query results). The snapshot is used by `isDirty()`,
465
- * `changedFields()`, and by `update()` to skip unchanged fields.
466
- * @private
467
- */
468
- /**
469
- * Normalize a value for snapshot storage.
470
- * Arrays of model instances are reduced to their `.id` strings so that
471
- * dirty-tracking compares stable identifiers instead of object references.
472
- */
473
- private static normalizeValue;
474
229
  /**
475
230
  * @param includedRelations Controls which relation fields are recorded
476
231
  * in the snapshot for dirty-tracking:
@@ -514,25 +269,6 @@ export declare class Ad4mModel {
514
269
  changedFields(): string[];
515
270
  private getData;
516
271
  static queryToProlog(perspective: PerspectiveProxy, query: Query, modelClassName?: string | null): Promise<string>;
517
- /**
518
- * Evaluates custom SurrealQL getters for properties and relations on a specific instance.
519
- * @private
520
- */
521
- private static evaluateCustomGettersForInstance;
522
- /**
523
- * Hydrates relation fields on instances according to the provided IncludeMap.
524
- *
525
- * For each relation listed in `includeMap`, the raw expression-URI strings
526
- * stored on the instance are replaced with fully-hydrated model instances
527
- * (fetched via the relation's `target()` class). Nested IncludeMaps are
528
- * supported for multi-level eager loading.
529
- *
530
- * @param instances - The instances whose relations should be hydrated
531
- * @param perspective - The perspective to fetch related instances from
532
- * @param includeMap - Describes which relations to hydrate
533
- * @private
534
- */
535
- private static hydrateRelations;
536
272
  /**
537
273
  * Generates a SurrealQL query from a Query object.
538
274
  *
@@ -570,100 +306,6 @@ export declare class Ad4mModel {
570
306
  * ```
571
307
  */
572
308
  static queryToSurrealQL(perspective: PerspectiveProxy, query: Query): Promise<string>;
573
- /**
574
- * Builds the WHERE clause for SurrealQL queries using graph traversal syntax.
575
- *
576
- * @description
577
- * Translates where conditions into graph traversal filters: `->link[WHERE ...]`
578
- * This is more efficient than nested SELECTs because SurrealDB can optimize graph traversals.
579
- *
580
- * Handles several condition types:
581
- * - Simple equality: `{ name: "Pasta" }` → `->link[WHERE predicate = 'X' AND out.uri = 'Pasta']`
582
- * - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → `->link[WHERE predicate = 'X' AND out.uri IN [...]]`
583
- * - NOT operators: Use `NOT` prefix
584
- * - Comparison operators (gt, gte, lt, lte, etc.): Handled in post-query JavaScript filtering
585
- * - Special fields: base uses `uri` directly, author/timestamp handled post-query
586
- *
587
- * @param metadata - Model metadata containing property predicates
588
- * @param where - Where conditions from the query
589
- * @returns Graph traversal WHERE clause filters, or empty string if no conditions
590
- *
591
- * @private
592
- */
593
- private static buildGraphTraversalWhereClause;
594
- /**
595
- * Builds the WHERE clause for SurrealQL queries.
596
- *
597
- * @description
598
- * Translates the where conditions from the Query object into SurrealQL WHERE clause fragments.
599
- * For each property filter, generates a subquery that checks for links with the appropriate
600
- * predicate and target value.
601
- *
602
- * Handles several condition types:
603
- * - Simple equality: `{ name: "Pasta" }` → subquery checking for predicate and target match
604
- * - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → target IN [...]
605
- * - Operators: `{ rating: { gt: 4 } }` → target > '4'
606
- * - gt, gte, lt, lte: comparison operators
607
- * - not: negation (single value or array)
608
- * - between: range check
609
- * - contains: substring/element check (uses SurrealQL CONTAINS)
610
- * - Special fields: base, author, timestamp are accessed directly, not via subqueries
611
- *
612
- * All conditions are joined with AND.
613
- *
614
- * @param metadata - Model metadata containing property predicates
615
- * @param where - Where conditions from the query
616
- * @returns WHERE clause string (without the "WHERE" keyword), or empty string if no conditions
617
- *
618
- * @private
619
- */
620
- private static buildSurrealWhereClause;
621
- /**
622
- * Builds the SELECT fields for SurrealQL queries.
623
- *
624
- * @description
625
- * Generates the field list for the SELECT clause, resolving properties and relations
626
- * via subqueries. Each property is fetched with a subquery that finds the link with the
627
- * appropriate predicate and returns its target. Relations are similar but don't use LIMIT 1.
628
- *
629
- * Field types:
630
- * - Properties: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X' LIMIT 1) AS propName`
631
- * - Relations: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X') AS relName`
632
- * - Author/Timestamp: Always included to provide metadata about each instance
633
- *
634
- * If properties or relations arrays are provided, only those fields are included.
635
- * Otherwise, all properties/relations from metadata are included.
636
- *
637
- * @param metadata - Model metadata containing property and relation predicates
638
- * @param properties - Optional array of property names to include (default: all)
639
- * @param relations - Optional array of relation names to include (default: all)
640
- * @returns Comma-separated SELECT field list
641
- *
642
- * @private
643
- */
644
- private static buildSurrealSelectFields;
645
- /**
646
- * Builds the SELECT fields for SurrealQL queries using aggregation functions.
647
- * Compatible with GROUP BY source queries.
648
- *
649
- * @private
650
- */
651
- private static buildSurrealSelectFieldsWithAggregation;
652
- /**
653
- * Formats a value for use in SurrealQL queries.
654
- *
655
- * @description
656
- * Handles different value types:
657
- * - Strings: Wrapped in single quotes with backslash-escaped special characters
658
- * - Numbers/booleans: Converted to string
659
- * - Arrays: Recursively formatted and wrapped in brackets
660
- *
661
- * @param value - The value to format
662
- * @returns Formatted value string ready for SurrealQL
663
- *
664
- * @private
665
- */
666
- private static formatSurrealValue;
667
309
  static instancesFromPrologResult<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query: Query, result: AllInstancesResult): Promise<ResultsWithTotalCount<T>>;
668
310
  /**
669
311
  * Converts SurrealDB query results to Ad4mModel instances.
@@ -676,11 +318,6 @@ export declare class Ad4mModel {
676
318
  * @internal
677
319
  */
678
320
  static instancesFromSurrealResult<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query: Query, result: any[]): Promise<ResultsWithTotalCount<T>>;
679
- /**
680
- * Checks if a value matches a condition (for post-query filtering).
681
- * @private
682
- */
683
- private static matchesCondition;
684
321
  /**
685
322
  * Gets all instances of the model in the perspective that match the query params.
686
323
  *
@@ -881,10 +518,6 @@ export declare class Ad4mModel {
881
518
  * ```
882
519
  */
883
520
  delete(batchId?: string): Promise<void>;
884
- /**
885
- * Options for `Ad4mModel.create()`.
886
- */
887
- static readonly CreateOptions: undefined;
888
521
  /**
889
522
  * Creates and saves a new model instance in one step.
890
523
  *
@@ -1091,411 +724,4 @@ export declare class Ad4mModel {
1091
724
  * @throws Error when namespace cannot be inferred
1092
725
  */
1093
726
  static fromJSONSchema(schema: JSONSchema, options: JSONSchemaToModelOptions): typeof Ad4mModel;
1094
- /**
1095
- * Determines the namespace for predicates using cascading precedence
1096
- */
1097
- private static determineNamespace;
1098
- /**
1099
- * Determines the predicate for a specific property using cascading precedence
1100
- */
1101
- private static determinePredicate;
1102
- /**
1103
- * Gets property-specific options using cascading precedence
1104
- */
1105
- private static getPropertyOption;
1106
- /**
1107
- * Gets default value for a JSON Schema type
1108
- */
1109
- private static getDefaultValueForType;
1110
727
  }
1111
- /** Query builder for Ad4mModel queries.
1112
- * Allows building queries with a fluent interface and either running them once
1113
- * or subscribing to updates.
1114
- *
1115
- * @example
1116
- * ```typescript
1117
- * const builder = Recipe.query(perspective)
1118
- * .where({ category: "Dessert" })
1119
- * .order({ rating: "DESC" })
1120
- * .limit(10);
1121
- *
1122
- * // Run once
1123
- * const recipes = await builder.run();
1124
- *
1125
- * // Or subscribe to updates
1126
- * await builder.subscribe(recipes => {
1127
- * console.log("Updated recipes:", recipes);
1128
- * });
1129
- * ```
1130
- */
1131
- export declare class ModelQueryBuilder<T extends Ad4mModel> {
1132
- private perspective;
1133
- private queryParams;
1134
- private modelClassName;
1135
- private ctor;
1136
- private currentSubscription?;
1137
- private useSurrealDBFlag;
1138
- constructor(perspective: PerspectiveProxy, ctor: typeof Ad4mModel, query?: Query);
1139
- /**
1140
- * Disposes of the current subscription if one exists.
1141
- *
1142
- * This method:
1143
- * 1. Stops the keepalive signals to the subscription
1144
- * 2. Unsubscribes from GraphQL subscription updates
1145
- * 3. Notifies the backend to clean up subscription resources
1146
- * 4. Clears the subscription reference
1147
- *
1148
- * You should call this method when you're done with a subscription
1149
- * to prevent memory leaks and ensure proper cleanup.
1150
- */
1151
- dispose(): void;
1152
- /**
1153
- * Adds where conditions to the query.
1154
- *
1155
- * @param conditions - The conditions to filter by
1156
- * @returns The query builder for chaining
1157
- *
1158
- * @example
1159
- * ```typescript
1160
- * .where({
1161
- * category: "Dessert",
1162
- * rating: { gt: 4 },
1163
- * tags: ["vegan", "quick"],
1164
- * published: true
1165
- * })
1166
- * ```
1167
- */
1168
- where(conditions: Where): ModelQueryBuilder<T>;
1169
- /**
1170
- * Sets the order for the query results.
1171
- *
1172
- * @param orderBy - The ordering criteria
1173
- * @returns The query builder for chaining
1174
- *
1175
- * @example
1176
- * ```typescript
1177
- * .order({ createdAt: "DESC" })
1178
- * ```
1179
- */
1180
- order(orderBy: Order): ModelQueryBuilder<T>;
1181
- /**
1182
- * Sets the maximum number of results to return.
1183
- *
1184
- * @param limit - Maximum number of results
1185
- * @returns The query builder for chaining
1186
- *
1187
- * @example
1188
- * ```typescript
1189
- * .limit(10)
1190
- * ```
1191
- */
1192
- limit(limit: number): ModelQueryBuilder<T>;
1193
- /**
1194
- * Sets the number of results to skip.
1195
- *
1196
- * @param offset - Number of results to skip
1197
- * @returns The query builder for chaining
1198
- *
1199
- * @example
1200
- * ```typescript
1201
- * .offset(20) // Skip first 20 results
1202
- * ```
1203
- */
1204
- offset(offset: number): ModelQueryBuilder<T>;
1205
- /**
1206
- * Scopes the query to instances linked from a parent.
1207
- *
1208
- * The predicate is resolved in order of precedence:
1209
- * 1. **Instance only** — the parent's constructor is used as the model
1210
- * class; its relation metadata is scanned for a relation whose
1211
- * `target()` matches the queried model class.
1212
- * 2. **Instance + options with `field`** — direct field-name lookup on
1213
- * the parent model's relation metadata (disambiguates when a parent
1214
- * has multiple relations targeting the same child class).
1215
- * 3. **String id + model class** — same metadata scan (or field lookup if
1216
- * options include `field`).
1217
- * 4. **String id + string predicate** — raw escape hatch, no metadata lookup.
1218
- *
1219
- * Passing a plain string id with no second argument throws because the
1220
- * predicate cannot be resolved without a model class.
1221
- *
1222
- * @param idOrInstance - The parent's expression URI **or** an Ad4mModel instance
1223
- * @param modelOrPredicate - A model class (predicate auto-resolved) **or** a raw predicate string
1224
- * @param options - Optional settings: `field` for direct relation-name lookup
1225
- * @returns The query builder for chaining
1226
- *
1227
- * @example
1228
- * ```typescript
1229
- * // Instance — predicate auto-resolved from Cookbook's @HasMany(() => Recipe)
1230
- * Recipe.query(perspective).parent(cookbook).get();
1231
- *
1232
- * // Instance + field — disambiguate when parent has multiple relations to same child
1233
- * Recipe.query(perspective).parent(cookbook, { field: "recipes" }).get();
1234
- *
1235
- * // String id + model class
1236
- * Recipe.query(perspective).parent(cookbookId, Cookbook).get();
1237
- *
1238
- * // String id + model class + field
1239
- * Recipe.query(perspective).parent(cookbookId, Cookbook, { field: "recipes" }).get();
1240
- *
1241
- * // String id + raw predicate (escape hatch)
1242
- * Recipe.query(perspective).parent(cookbookId, "cookbook://recipe").get();
1243
- * ```
1244
- */
1245
- parent(idOrInstance: string | Ad4mModel, modelOrPredicate?: typeof Ad4mModel | string | {
1246
- field: string;
1247
- }, options?: {
1248
- field?: string;
1249
- }): ModelQueryBuilder<T>;
1250
- /**
1251
- * Specifies which properties to include in the results.
1252
- *
1253
- * @param properties - Array of property names to include
1254
- * @returns The query builder for chaining
1255
- *
1256
- * @example
1257
- * ```typescript
1258
- * .properties(["name", "description", "rating"])
1259
- * ```
1260
- */
1261
- properties(properties: string[]): ModelQueryBuilder<T>;
1262
- /**
1263
- * Specifies which relations to eager-load (hydrate into model instances).
1264
- *
1265
- * Without `include`, relation fields contain raw expression URIs (strings).
1266
- * With `include`, the URIs are resolved into fully-hydrated model instances
1267
- * using the `target` class declared in the relation decorator.
1268
- *
1269
- * Supports nested includes for multi-level eager loading.
1270
- *
1271
- * @param map - An IncludeMap describing which relations to hydrate
1272
- * @returns The query builder for chaining
1273
- *
1274
- * @example
1275
- * ```typescript
1276
- * // Hydrate comments one level deep
1277
- * const recipes = await Recipe.query(perspective)
1278
- * .include({ comments: true })
1279
- * .run();
1280
- * // recipe.comments is now Comment[] (model instances), not string[]
1281
- *
1282
- * // Nested: hydrate comments AND each comment's author
1283
- * const recipes = await Recipe.query(perspective)
1284
- * .include({ comments: { author: true } })
1285
- * .run();
1286
- * ```
1287
- */
1288
- include(map: IncludeMap): ModelQueryBuilder<T>;
1289
- overrideModelClassName(className: string): ModelQueryBuilder<T>;
1290
- /**
1291
- * Enables or disables SurrealDB query path.
1292
- *
1293
- * @param enabled - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
1294
- * @returns The query builder for chaining
1295
- *
1296
- * @example
1297
- * ```typescript
1298
- * // Use SurrealDB (default)
1299
- * const recipes = await Recipe.query(perspective)
1300
- * .where({ category: "Dessert" })
1301
- * .useSurrealDB(true)
1302
- * .get();
1303
- *
1304
- * // Use Prolog (legacy)
1305
- * const recipesProlog = await Recipe.query(perspective)
1306
- * .where({ category: "Dessert" })
1307
- * .useSurrealDB(false)
1308
- * .get();
1309
- * ```
1310
- *
1311
- * @remarks
1312
- * Note: Subscriptions (subscribe(), countSubscribe(), paginateSubscribe()) default to SurrealDB live queries
1313
- * if useSurrealDB(true) is set (default).
1314
- */
1315
- useSurrealDB(enabled?: boolean): ModelQueryBuilder<T>;
1316
- /**
1317
- * Executes the query once and returns the results.
1318
- *
1319
- * @returns Array of matching entities
1320
- *
1321
- * @example
1322
- * ```typescript
1323
- * const recipes = await Recipe.query(perspective)
1324
- * .where({ category: "Dessert" })
1325
- * .get();
1326
- * ```
1327
- */
1328
- get(): Promise<T[]>;
1329
- /**
1330
- * Returns the first matching instance, or `null` if none match.
1331
- *
1332
- * Internally sets `limit: 1` and delegates to `get()`.
1333
- *
1334
- * @returns The first matching instance, or `null`
1335
- *
1336
- * @example
1337
- * ```typescript
1338
- * const recipe = await Recipe.query(perspective)
1339
- * .where({ name: "Pasta" })
1340
- * .first();
1341
- * ```
1342
- */
1343
- first(): Promise<T | null>;
1344
- /**
1345
- * Subscribes to the query and receives updates when results change.
1346
- *
1347
- * This method:
1348
- * 1. Creates and initializes a SurrealDB live query subscription (default)
1349
- * 2. Sets up the callback to process future updates
1350
- * 3. Returns the initial results immediately
1351
- *
1352
- * Remember to call dispose() when you're done with the subscription
1353
- * to clean up resources.
1354
- *
1355
- * @param callback - Function to call with updated results
1356
- * @returns Initial results array
1357
- *
1358
- * @example
1359
- * ```typescript
1360
- * const builder = Recipe.query(perspective)
1361
- * .where({ status: "cooking" });
1362
- *
1363
- * const initialRecipes = await builder.subscribe(recipes => {
1364
- * console.log("Updated recipes:", recipes);
1365
- * });
1366
- *
1367
- * // When done with subscription:
1368
- * builder.dispose();
1369
- * ```
1370
- *
1371
- * @remarks
1372
- * By default, this uses SurrealDB live queries for real-time updates.
1373
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
1374
- */
1375
- subscribe(callback: (results: T[]) => void): Promise<T[]>;
1376
- /**
1377
- * Gets the total count of matching entities.
1378
- *
1379
- * @returns Total count
1380
- *
1381
- * @example
1382
- * ```typescript
1383
- * const totalDesserts = await Recipe.query(perspective)
1384
- * .where({ category: "Dessert" })
1385
- * .count();
1386
- * ```
1387
- */
1388
- count(): Promise<number>;
1389
- /**
1390
- * Subscribes to count updates for matching entities.
1391
- *
1392
- * This method:
1393
- * 1. Creates and initializes a SurrealDB live query subscription for the count (default)
1394
- * 2. Sets up the callback to process future count updates
1395
- * 3. Returns the initial count immediately
1396
- *
1397
- * Remember to call dispose() when you're done with the subscription
1398
- * to clean up resources.
1399
- *
1400
- * @param callback - Function to call with updated count
1401
- * @returns Initial count
1402
- *
1403
- * @example
1404
- * ```typescript
1405
- * const builder = Recipe.query(perspective)
1406
- * .where({ status: "active" });
1407
- *
1408
- * const initialCount = await builder.countSubscribe(count => {
1409
- * console.log("Active items:", count);
1410
- * });
1411
- *
1412
- * // When done with subscription:
1413
- * builder.dispose();
1414
- * ```
1415
- *
1416
- * @remarks
1417
- * By default, this uses SurrealDB live queries for real-time updates.
1418
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
1419
- */
1420
- countSubscribe(callback: (count: number) => void): Promise<number>;
1421
- /**
1422
- * Gets a page of results with pagination metadata.
1423
- *
1424
- * @param pageSize - Number of items per page
1425
- * @param pageNumber - Which page to retrieve (1-based)
1426
- * @returns Paginated results with metadata
1427
- *
1428
- * @example
1429
- * ```typescript
1430
- * const page = await Recipe.query(perspective)
1431
- * .where({ category: "Main" })
1432
- * .paginate(10, 1);
1433
- * console.log(`Page ${page.pageNumber}, ${page.results.length} of ${page.totalCount}`);
1434
- * ```
1435
- */
1436
- paginate(pageSize: number, pageNumber: number): Promise<PaginationResult<T>>;
1437
- /**
1438
- * Subscribes to paginated results updates.
1439
- *
1440
- * This method:
1441
- * 1. Creates and initializes a SurrealDB live query subscription for the paginated results (default)
1442
- * 2. Sets up the callback to process future page updates
1443
- * 3. Returns the initial page immediately
1444
- *
1445
- * Remember to call dispose() when you're done with the subscription
1446
- * to clean up resources.
1447
- *
1448
- * @param pageSize - Number of items per page
1449
- * @param pageNumber - Which page to retrieve (1-based)
1450
- * @param callback - Function to call with updated pagination results
1451
- * @returns Initial pagination results
1452
- *
1453
- * @example
1454
- * ```typescript
1455
- * const builder = Recipe.query(perspective)
1456
- * .where({ category: "Main" });
1457
- *
1458
- * const initialPage = await builder.paginateSubscribe(10, 1, page => {
1459
- * console.log("Updated page:", page.results);
1460
- * });
1461
- *
1462
- * // When done with subscription:
1463
- * builder.dispose();
1464
- * ```
1465
- *
1466
- * @remarks
1467
- * By default, this uses SurrealDB live queries for real-time updates.
1468
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
1469
- */
1470
- paginateSubscribe(pageSize: number, pageNumber: number, callback: (results: PaginationResult<T>) => void): Promise<PaginationResult<T>>;
1471
- }
1472
- /**
1473
- * Generate Prolog predicate facts from a model class's decorator metadata.
1474
- *
1475
- * Given a model class decorated with `@Model` (and its `@Flag`, `@Property`,
1476
- * `@HasMany`, `@BelongsToMany` decorators), this function emits a string of
1477
- * Prolog clauses that can be prepended to any `perspective.infer()` call.
1478
- *
1479
- * The generated predicates are:
1480
- * - **Instance recognizer** — `modelName(X)` — matches instances of the model
1481
- * - **Property getters** — `modelName_propName(X, Value)` — one per property
1482
- * - **Relation getters** — `modelName_relName(X, Values)` — one per relation
1483
- *
1484
- * @example
1485
- * ```typescript
1486
- * import { generatePrologFacts } from '@coasys/ad4m';
1487
- *
1488
- * const facts = generatePrologFacts(Poll);
1489
- * const result = await perspective.infer(\`
1490
- * \${facts}
1491
- * recent_popular_poll(X) :-
1492
- * poll(X),
1493
- * poll_vote_count(X, N), N > 10.
1494
- * \`);
1495
- * ```
1496
- *
1497
- * @param ModelClass - A class decorated with `@Model` that extends `Ad4mModel`
1498
- * @returns A multi-line Prolog string ready for use with `perspective.infer()`
1499
- */
1500
- export declare function generatePrologFacts(ModelClass: typeof Ad4mModel): string;
1501
- export {};