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

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 (128) hide show
  1. package/jest.config.js +4 -4
  2. package/lib/index.cjs +5999 -6046
  3. package/lib/index.js +5977 -6040
  4. package/lib/src/Ad4mClient.d.ts +16 -9
  5. package/lib/src/Ad4mClient.js +25 -46
  6. package/lib/src/Ad4mClient.test.d.ts +1 -0
  7. package/lib/src/Ad4mClient.test.js +1204 -0
  8. package/lib/src/Literal.d.ts +2 -1
  9. package/lib/src/Literal.js +35 -38
  10. package/lib/src/Literal.test.d.ts +1 -0
  11. package/lib/src/Literal.test.js +41 -0
  12. package/lib/src/SmartLiteral.d.ts +2 -1
  13. package/lib/src/SmartLiteral.js +15 -30
  14. package/lib/src/agent/AgentClient.d.ts +4 -1
  15. package/lib/src/agent/AgentClient.js +99 -79
  16. package/lib/src/ai/AIClient.d.ts +2 -1
  17. package/lib/src/ai/AIClient.js +220 -224
  18. package/lib/src/expression/ExpressionClient.d.ts +1 -1
  19. package/lib/src/expression/ExpressionClient.js +86 -73
  20. package/lib/src/index.d.ts +1 -1
  21. package/lib/src/index.js +1 -1
  22. package/lib/src/language/LanguageClient.d.ts +1 -1
  23. package/lib/src/language/LanguageClient.js +52 -52
  24. package/lib/src/model/Ad4mModel.d.ts +157 -937
  25. package/lib/src/model/Ad4mModel.js +212 -2799
  26. package/lib/src/model/Ad4mModel.test.js +1002 -561
  27. package/lib/src/model/decorators.d.ts +94 -426
  28. package/lib/src/model/decorators.js +333 -741
  29. package/lib/src/model/mutation.d.ts +81 -0
  30. package/lib/src/model/mutation.js +317 -0
  31. package/lib/src/model/parentUtils.d.ts +32 -0
  32. package/lib/src/model/parentUtils.js +64 -0
  33. package/lib/src/model/prolog/generatePrologFacts.d.ts +36 -0
  34. package/lib/src/model/prolog/generatePrologFacts.js +139 -0
  35. package/lib/src/model/prolog/index.d.ts +1 -0
  36. package/lib/src/model/prolog/index.js +1 -0
  37. package/lib/src/model/query/ModelQueryBuilder.d.ts +82 -0
  38. package/lib/src/model/query/ModelQueryBuilder.js +115 -0
  39. package/lib/src/model/query/QueryBuilder.d.ts +101 -0
  40. package/lib/src/model/query/QueryBuilder.js +193 -0
  41. package/lib/src/model/query/SurrealQueryBuilder.d.ts +48 -0
  42. package/lib/src/model/query/SurrealQueryBuilder.js +371 -0
  43. package/lib/src/model/query/fetchInstance.d.ts +24 -0
  44. package/lib/src/model/query/fetchInstance.js +144 -0
  45. package/lib/src/model/query/hydration.d.ts +54 -0
  46. package/lib/src/model/query/hydration.js +214 -0
  47. package/lib/src/model/query/operations.d.ts +59 -0
  48. package/lib/src/model/query/operations.js +384 -0
  49. package/lib/src/model/query/snapshot.d.ts +59 -0
  50. package/lib/src/model/query/snapshot.js +106 -0
  51. package/lib/src/model/query/surrealCompiler.d.ts +42 -0
  52. package/lib/src/model/query/surrealCompiler.js +304 -0
  53. package/lib/src/model/schema/fromJSONSchema.d.ts +67 -0
  54. package/lib/src/model/schema/fromJSONSchema.js +264 -0
  55. package/lib/src/model/schema/metadata.d.ts +15 -0
  56. package/lib/src/model/schema/metadata.js +112 -0
  57. package/lib/src/model/subscription.d.ts +47 -0
  58. package/lib/src/model/subscription.js +231 -0
  59. package/lib/src/model/transaction.d.ts +27 -0
  60. package/lib/src/model/transaction.js +32 -0
  61. package/lib/src/model/types.d.ts +195 -0
  62. package/lib/src/model/types.js +8 -0
  63. package/lib/src/model/util.js +7 -7
  64. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +5 -1
  65. package/lib/src/neighbourhood/NeighbourhoodClient.js +263 -181
  66. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +2 -1
  67. package/lib/src/neighbourhood/NeighbourhoodProxy.js +13 -28
  68. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +1 -5
  69. package/lib/src/perspectives/PerspectiveClient.d.ts +9 -9
  70. package/lib/src/perspectives/PerspectiveClient.js +316 -240
  71. package/lib/src/perspectives/PerspectiveProxy.d.ts +54 -92
  72. package/lib/src/perspectives/PerspectiveProxy.js +803 -444
  73. package/lib/src/runtime/RuntimeClient.d.ts +5 -1
  74. package/lib/src/runtime/RuntimeClient.js +412 -238
  75. package/lib/src/shacl/SHACLFlow.test.js +164 -105
  76. package/lib/src/shacl/SHACLShape.d.ts +17 -3
  77. package/lib/src/shacl/SHACLShape.js +127 -90
  78. package/lib/src/shacl/SHACLShape.test.js +244 -176
  79. package/lib/src/utils.d.ts +8 -0
  80. package/lib/src/utils.js +21 -7
  81. package/package.json +8 -13
  82. package/src/Ad4mClient.test.ts +1564 -1315
  83. package/src/Ad4mClient.ts +55 -54
  84. package/src/Literal.test.ts +45 -26
  85. package/src/Literal.ts +82 -66
  86. package/src/SmartLiteral.ts +74 -58
  87. package/src/agent/AgentClient.ts +144 -99
  88. package/src/ai/AIClient.ts +409 -359
  89. package/src/expression/ExpressionClient.ts +142 -96
  90. package/src/index.ts +1 -1
  91. package/src/language/LanguageClient.ts +137 -113
  92. package/src/model/Ad4mModel.test.ts +1128 -647
  93. package/src/model/Ad4mModel.ts +485 -3249
  94. package/src/model/IMPROVEMENTS.md +482 -0
  95. package/src/model/PREDICATE_COLLISION_FIX.md +651 -0
  96. package/src/model/README.md +317 -0
  97. package/src/model/SHACL_MUTATION_DECOUPLING.md +356 -0
  98. package/src/model/SUBSCRIPTION_STRATEGY.md +317 -0
  99. package/src/model/TC39_STAGE_3_DECORATORS.md +609 -0
  100. package/src/model/decorators.ts +689 -1046
  101. package/src/model/mutation.ts +461 -0
  102. package/src/model/parentUtils.ts +91 -0
  103. package/src/model/prolog/generatePrologFacts.ts +176 -0
  104. package/src/model/prolog/index.ts +1 -0
  105. package/src/model/query/ModelQueryBuilder.ts +173 -0
  106. package/src/model/query/fetchInstance.ts +181 -0
  107. package/src/model/query/hydration.ts +273 -0
  108. package/src/model/query/operations.ts +510 -0
  109. package/src/model/query/snapshot.ts +126 -0
  110. package/src/model/query/surrealCompiler.ts +376 -0
  111. package/src/model/schema/fromJSONSchema.ts +411 -0
  112. package/src/model/schema/metadata.ts +148 -0
  113. package/src/model/subscription.ts +307 -0
  114. package/src/model/transaction.ts +60 -0
  115. package/src/model/types.ts +207 -0
  116. package/src/model/util.ts +47 -48
  117. package/src/neighbourhood/NeighbourhoodClient.ts +393 -251
  118. package/src/neighbourhood/NeighbourhoodProxy.test.ts +3 -7
  119. package/src/neighbourhood/NeighbourhoodProxy.ts +58 -40
  120. package/src/perspectives/PerspectiveClient.ts +779 -540
  121. package/src/perspectives/PerspectiveProxy.ts +2860 -2053
  122. package/src/runtime/RuntimeClient.ts +775 -476
  123. package/src/shacl/SHACLFlow.test.ts +196 -129
  124. package/src/shacl/SHACLShape.test.ts +284 -190
  125. package/src/shacl/SHACLShape.ts +225 -172
  126. package/src/utils.ts +31 -17
  127. package/tsconfig.json +9 -10
  128. package/src/model/Subject.ts +0 -159
@@ -1,3408 +1,644 @@
1
1
  import { Literal } from "../Literal";
2
2
  import { Link } from "../links/Links";
3
+ import { LinkQuery } from "../perspectives/LinkQuery";
3
4
  import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
4
- import { makeRandomPrologAtom, PropertyOptions, CollectionOptions, ModelOptions } from "./decorators";
5
- import { singularToPlural, pluralToSingular, propertyNameToSetterName, collectionToAdderName, collectionToRemoverName, collectionToSetterName } from "./util";
6
- import { escapeSurrealString } from "../utils";
7
-
8
- // JSON Schema type definitions
9
- interface JSONSchemaProperty {
10
- type: string | string[];
11
- items?: JSONSchemaProperty;
12
- properties?: { [key: string]: JSONSchemaProperty };
13
- required?: string[];
14
- "x-ad4m"?: {
15
- through?: string;
16
- resolveLanguage?: string;
17
- local?: boolean;
18
- writable?: boolean;
19
- initial?: string;
20
- };
21
- }
22
-
23
- interface JSONSchema {
24
- $schema?: string;
25
- title?: string;
26
- $id?: string;
27
- type?: string;
28
- properties?: { [key: string]: JSONSchemaProperty };
29
- required?: string[];
30
- "x-ad4m"?: {
31
- namespace?: string;
32
- className?: string;
33
- };
34
- }
35
-
36
- interface JSONSchemaToModelOptions {
37
- name: string;
38
- namespace?: string;
39
- predicateTemplate?: string;
40
- predicateGenerator?: (title: string, property: string) => string;
41
- propertyMapping?: Record<string, string>;
42
- resolveLanguage?: string;
43
- local?: boolean;
44
- propertyOptions?: Record<string, Partial<PropertyOptions>>;
45
- }
46
-
47
- type ValueTuple = [name: string, value: any, resolve?: boolean];
48
- type WhereOps = {
49
- not: string | number | boolean | string[] | number[];
50
- between: [number, number];
51
- lt: number; // less than
52
- lte: number; // less than or equal to
53
- gt: number; // greater than
54
- gte: number; // greater than or equal to
55
- contains: string | number; // substring/element check
56
- };
57
- type WhereCondition = string | number | boolean | string[] | number[] | { [K in keyof WhereOps]?: WhereOps[K] };
58
- type Where = { [propertyName: string]: WhereCondition };
59
- type Order = { [propertyName: string]: "ASC" | "DESC" };
60
-
61
- export type Query = {
62
- source?: string;
63
- properties?: string[];
64
- collections?: string[]; // replace with include: Query[]
65
- where?: Where;
66
- order?: Order;
67
- offset?: number;
68
- limit?: number;
69
- count?: boolean;
70
- };
71
-
72
- export type AllInstancesResult = { AllInstances: Ad4mModel[]; TotalCount?: number; isInit?: boolean };
73
- export type ResultsWithTotalCount<T> = { results: T[]; totalCount?: number };
74
- export type PaginationResult<T> = { results: T[]; totalCount?: number; pageSize: number; pageNumber: number };
75
-
76
- /**
77
- * Metadata for a single property extracted from decorators.
78
- */
79
- export interface PropertyMetadata {
80
- /** The property name */
81
- name: string;
82
- /** The predicate URI (through value) */
83
- predicate: string;
84
- /** Whether the property is required */
85
- required: boolean;
86
- /** Whether the property is writable */
87
- writable: boolean;
88
- /** Initial value if specified */
89
- initial?: string;
90
- /** Language for resolution (e.g., "literal") */
91
- resolveLanguage?: string;
92
- /** Custom Prolog getter code */
93
- prologGetter?: string;
94
- /** Custom Prolog setter code */
95
- prologSetter?: string;
96
- /** Custom SurrealQL getter code */
97
- getter?: string;
98
- /** Whether stored locally only */
99
- local?: boolean;
100
- /** Transform function */
101
- transform?: (value: any) => any;
102
- /** Whether this is a flag property */
103
- flag?: boolean;
104
- }
105
-
106
- /**
107
- * Metadata for a single collection extracted from decorators.
108
- */
109
- export interface CollectionMetadata {
110
- /** The collection name */
111
- name: string;
112
- /** The predicate URI (through value) */
113
- predicate: string;
114
- /** Filter conditions */
115
- where?: { isInstance?: any; prologCondition?: string; condition?: string };
116
- /** Custom SurrealQL getter code */
117
- getter?: string;
118
- /** Whether stored locally only */
119
- local?: boolean;
120
- }
121
-
122
- /**
123
- * Complete model metadata extracted from decorators.
124
- */
125
- export interface ModelMetadata {
126
- /** The model class name from @ModelOptions */
127
- className: string;
128
- /** Map of property name to metadata */
129
- properties: Record<string, PropertyMetadata>;
130
- /** Map of collection name to metadata */
131
- collections: Record<string, CollectionMetadata>;
132
- }
133
-
134
- function capitalize(word: string): string {
135
- return word.charAt(0).toUpperCase() + word.slice(1);
136
- }
137
-
138
- function buildSourceQuery(source?: string): string {
139
- // Constrains the query to instances that have the provided source
140
- if (!source) return "";
141
- return `triple("${source}", "ad4m://has_child", Base)`;
142
- }
143
-
144
- // todo: only return Timestamp & Author from query (Base, AllLinks, and SortLinks not required)
145
- function buildAuthorAndTimestampQuery(): string {
146
- // Gets the author and timestamp of a Ad4mModel instance (based on the first link mentioning the base)
147
- return `
148
- findall(
149
- [T, A],
150
- link(Base, _, _, T, A),
151
- AllLinks
152
- ),
153
- sort(AllLinks, SortedLinks),
154
- SortedLinks = [[Timestamp, Author]|_]
155
- `;
156
- }
157
-
158
- function buildPropertiesQuery(properties?: string[]): string {
159
- // Gets the name, value, and resolve boolean for all (or some) properties on a Ad4mModel instance
160
- // Resolves literals (if property_resolve/2 is true) to their value - either the data field if it is
161
- // an Expression in JSON literal, or the direct literal value if it is a simple literal
162
- // If no properties are provided, all are included
163
- return `
164
- findall([PropertyName, PropertyValue, Resolve], (
165
- % Constrain to specified properties if provided
166
- ${properties ? `member(PropertyName, [${properties.map((name) => `"${name}"`).join(", ")}]),` : ""}
167
- resolve_property(SubjectClass, Base, PropertyName, PropertyValue, Resolve)
168
- ), Properties)
169
- `;
170
- }
171
-
172
- function buildCollectionsQuery(collections?: string[]): string {
173
- // Gets the name and array of values for all (or some) collections on a Ad4mModel instance
174
- // If no collections are provided, all are included
175
- return `
176
- findall([CollectionName, CollectionValues], (
177
- % Constrain to specified collections if provided
178
- ${collections ? `member(CollectionName, [${collections.map((name) => `"${name}"`).join(", ")}]),` : ""}
179
-
180
- collection(SubjectClass, CollectionName),
181
- collection_getter(SubjectClass, Base, CollectionName, CollectionValues)
182
- ), Collections)
183
- `;
184
- }
185
-
186
- function buildWhereQuery(where: Where = {}): string {
187
- // Constrains the query to instances that match the provided where conditions
188
-
189
- function formatValue(value) {
190
- // Wrap strings in quotes
191
- return typeof value === "string" ? `"${value}"` : value;
192
- }
193
-
194
- return (Object.entries(where) as [string, WhereCondition][])
195
- .map(([key, value]) => {
196
- const isSpecial = ["base", "author", "timestamp"].includes(key);
197
- const getter = `resolve_property(SubjectClass, Base, "${key}", Value${key}, _)`;
198
- // const getter = `property_getter(SubjectClass, Base, "${key}", URI), literal_from_url(URI, V, _)`;
199
- const field = capitalize(key);
200
-
201
- // Handle direct array values (for IN conditions)
202
- if (Array.isArray(value)) {
203
- const formattedValues = value.map((v) => formatValue(v)).join(", ");
204
- if (isSpecial) return `member(${field}, [${formattedValues}])`;
205
- else return `${getter}, member(Value${key}, [${formattedValues}])`;
206
- }
207
-
208
- // Handle operation object
209
- if (typeof value === "object" && value !== null) {
210
- const { not, between, lt, lte, gt, gte } = value;
211
-
212
- // Handle NOT operation
213
- if (not !== undefined) {
214
- if (Array.isArray(not)) {
215
- // NOT IN array
216
- const formattedValues = not.map((v) => formatValue(v)).join(", ");
217
- if (isSpecial) return `\\+ member(${field}, [${formattedValues}])`;
218
- else return `${getter}, \\+ member(Value${key}, [${formattedValues}])`;
219
- } else {
220
- // NOT EQUAL
221
- if (isSpecial) return `${field} \\= ${formatValue(not)}`;
222
- else return `${getter}, Value${key} \\= ${formatValue(not)}`;
223
- }
224
- }
225
-
226
- // Handle BETWEEN
227
- if (between !== undefined && Array.isArray(between) && between.length === 2) {
228
- if (isSpecial) return `${field} >= ${between[0]}, ${field} =< ${between[1]}`;
229
- else return `${getter}, Value${key} >= ${between[0]}, Value${key} =< ${between[1]}`;
230
- }
231
-
232
- // Handle lt, lte, gt, & gte operations
233
- const operators = [
234
- { value: lt, symbol: "<" }, // LESS THAN
235
- { value: lte, symbol: "=<" }, // LESS THAN OR EQUAL TO
236
- { value: gt, symbol: ">" }, // GREATER THAN
237
- { value: gte, symbol: ">=" }, // GREATER THAN OR EQUAL TO
238
- ];
239
-
240
- for (const { value, symbol } of operators) {
241
- if (value !== undefined)
242
- return isSpecial ? `${field} ${symbol} ${value}` : `${getter}, Value${key} ${symbol} ${value}`;
243
- }
244
- }
245
-
246
- // Default to direct equality
247
- if (isSpecial) return `${field} = ${formatValue(value)}`;
248
- else return `${getter}, Value${key} = ${formatValue(value)}`;
249
- })
250
- .join(", ");
251
- }
252
-
253
- function buildCountQuery(count?: boolean): string {
254
- return count ? "length(UnsortedInstances, TotalCount)" : "";
255
- }
256
-
257
- function buildOrderQuery(order?: Order): string {
258
- if (!order) return "SortedInstances = UnsortedInstances";
259
- const [propertyName, direction] = Object.entries(order)[0];
260
- return `sort_instances(UnsortedInstances, "${propertyName}", "${direction}", SortedInstances)`;
261
- }
262
-
263
- function buildOffsetQuery(offset?: number): string {
264
- if (!offset || offset < 0) return "InstancesWithOffset = SortedInstances";
265
- return `skipN(SortedInstances, ${offset}, InstancesWithOffset)`;
266
- }
267
-
268
- function buildLimitQuery(limit?: number): string {
269
- if (!limit || limit < 0) return "AllInstances = InstancesWithOffset";
270
- return `takeN(InstancesWithOffset, ${limit}, AllInstances)`;
271
- }
272
-
273
- function normalizeNamespaceString(namespace: string): string {
274
- if (!namespace) return '';
275
- if (namespace.includes('://')) {
276
- const [scheme, rest] = namespace.split('://');
277
- const path = (rest || '').replace(/\/+$/,'');
278
- return `${scheme}://${path}`;
279
- } else {
280
- return namespace.replace(/\/+$/,'');
281
- }
282
- }
283
-
284
- function normalizeSchemaType(type?: string | string[]): string | undefined {
285
- if (!type) return undefined;
286
- if (typeof type === "string") return type;
287
- if (Array.isArray(type) && type.length > 0) {
288
- const nonNull = type.find((t) => t !== "null");
289
- return nonNull || type[0];
290
- }
291
- return undefined;
292
- }
293
-
294
- function isSchemaType(schema: JSONSchemaProperty, expectedType: string): boolean {
295
- return normalizeSchemaType(schema.type) === expectedType;
296
- }
297
-
298
- function isArrayType(schema: JSONSchemaProperty): boolean {
299
- return isSchemaType(schema, "array");
300
- }
301
-
302
- function isObjectType(schema: JSONSchemaProperty): boolean {
303
- return isSchemaType(schema, "object");
304
- }
305
-
306
- function isNumericType(schema: JSONSchemaProperty): boolean {
307
- const normalized = normalizeSchemaType(schema.type);
308
- return normalized === "number" || normalized === "integer";
309
- }
5
+ import { SHACLShape } from "../shacl/SHACLShape";
6
+ import { makeRandomId, getRelationsMetadata } from "./decorators";
7
+ import { resolveParentPredicate } from "./parentUtils";
8
+ export { resolveParentPredicate, normalizeParentQuery } from "./parentUtils";
9
+ import * as mutation from "./mutation";
10
+ export type { MutationContext } from "./mutation";
11
+ import { capitalize } from "./util";
12
+
13
+ // ── Public types (re-exported so consumers see no change) ──────────────────
14
+ export type {
15
+ Query,
16
+ Where,
17
+ Order,
18
+ WhereCondition,
19
+ AllInstancesResult,
20
+ ResultsWithTotalCount,
21
+ PaginationResult,
22
+ PropertyMetadata,
23
+ RelationMetadata,
24
+ ModelMetadata,
25
+ IncludeMap,
26
+ SubscribeOptions,
27
+ Subscription,
28
+ ParentQuery,
29
+ ParentQueryByPredicate,
30
+ ParentQueryByModel,
31
+ } from "./types";
310
32
 
311
33
  /**
312
- * Base class for defining data models in AD4M.
313
- *
314
- * @description
315
- * Ad4mModel provides the foundation for creating data models that are stored in AD4M perspectives.
316
- * Each model instance is represented as a subgraph in the perspective, with properties and collections
317
- * mapped to links in that graph. The class uses Prolog-based queries to efficiently search and filter
318
- * instances based on their properties and relationships.
319
- *
320
- * Key concepts:
321
- * - Each model instance has a unique base expression that serves as its identifier
322
- * - Properties are stored as links with predicates defined by the `through` option
323
- * - Collections represent one-to-many relationships as sets of links
324
- * - Queries are translated to Prolog for efficient graph pattern matching
325
- * - Changes are tracked through the perspective's subscription system
326
- *
34
+ * Options for linking a newly created instance to an existing parent node.
35
+ * Pass as the third argument to `Model.create()`.
36
+ *
327
37
  * @example
328
- * ```typescript
329
- * // Define a recipe model
330
- * @ModelOptions({ name: "Recipe" })
331
- * class Recipe extends Ad4mModel {
332
- * // Required property with literal value
333
- * @Property({
334
- * through: "recipe://name",
335
- * resolveLanguage: "literal"
336
- * })
337
- * name: string = "";
338
- *
339
- * // Optional property with custom initial value
340
- * @Optional({
341
- * through: "recipe://status",
342
- * initial: "recipe://draft"
343
- * })
344
- * status: string = "";
345
- *
346
- * // Read-only computed property
347
- * @ReadOnly({
348
- * through: "recipe://rating",
349
- * getter: `
350
- * findall(Rating, triple(Base, "recipe://user_rating", Rating), Ratings),
351
- * sum_list(Ratings, Sum),
352
- * length(Ratings, Count),
353
- * Value is Sum / Count
354
- * `
355
- * })
356
- * averageRating: number = 0;
357
- *
358
- * // Collection of ingredients
359
- * @Collection({ through: "recipe://ingredient" })
360
- * ingredients: string[] = [];
361
- *
362
- * // Collection of comments that are instances of another model
363
- * @Collection({
364
- * through: "recipe://comment",
365
- * where: { isInstance: Comment }
366
- * })
367
- * comments: Comment[] = [];
368
- * }
369
- *
370
- * // Create and save a new recipe
371
- * const recipe = new Recipe(perspective);
372
- * recipe.name = "Chocolate Cake";
373
- * recipe.ingredients = ["flour", "sugar", "cocoa"];
374
- * await recipe.save();
375
- *
376
- * // Query recipes in different ways
377
- * // Get all recipes
378
- * const allRecipes = await Recipe.findAll(perspective);
379
- *
380
- * // Find recipes with specific criteria
381
- * const desserts = await Recipe.findAll(perspective, {
382
- * where: {
383
- * status: "recipe://published",
384
- * averageRating: { gt: 4 }
385
- * },
386
- * order: { name: "ASC" },
387
- * limit: 10
388
- * });
389
- *
390
- * // Use the fluent query builder
391
- * const popularRecipes = await Recipe.query(perspective)
392
- * .where({ averageRating: { gt: 4.5 } })
393
- * .order({ averageRating: "DESC" })
394
- * .limit(5)
395
- * .get();
396
- *
397
- * // Subscribe to real-time updates
398
- * await Recipe.query(perspective)
399
- * .where({ status: "recipe://cooking" })
400
- * .subscribe(recipes => {
401
- * console.log("Currently being cooked:", recipes);
402
- * });
403
- *
404
- * // Paginate results
405
- * const { results, totalCount, pageNumber } = await Recipe.query(perspective)
406
- * .where({ status: "recipe://published" })
407
- * .paginate(10, 1);
408
- * ```
38
+ * // Field inferred — only one @HasMany on Channel points to Poll
39
+ * await Poll.create(perspective, { title }, { parent: { model: Channel, id: channelId } })
40
+ *
41
+ * // Field explicit — needed when multiple @HasMany on the parent point to the same type
42
+ * await Poll.create(perspective, { title }, { parent: { model: Channel, id: channelId, field: 'featuredPolls' } })
409
43
  */
410
- export class Ad4mModel {
411
- #baseExpression: string;
412
- #subjectClassName: string;
413
- #source: string;
414
- #perspective: PerspectiveProxy;
415
- author: string;
416
- createdAt: any;
417
- updatedAt: any;
418
-
419
- private static classNamesByClass = new WeakMap<typeof Ad4mModel, { [perspectiveId: string]: string }>();
420
-
421
- static async getClassName(perspective: PerspectiveProxy) {
422
- // Check if this is the Ad4mModel class itself or a subclass
423
- const isBaseClass = this === Ad4mModel;
424
-
425
- // For the base Ad4mModel class, we can't use the cache
426
- if (isBaseClass) {
427
- return await perspective.stringOrTemplateObjectToSubjectClassName(this);
428
- }
429
-
430
- // Get or create the cache for this class
431
- let classCache = this.classNamesByClass.get(this);
432
- if (!classCache) {
433
- classCache = {};
434
- this.classNamesByClass.set(this, classCache);
435
- }
436
-
437
- // Get or create the cached name for this perspective
438
- const perspectiveID = perspective.uuid;
439
- if (!classCache[perspectiveID]) {
440
- classCache[perspectiveID] = await perspective.stringOrTemplateObjectToSubjectClassName(this);
441
- }
442
-
443
- return classCache[perspectiveID];
444
- }
445
-
446
- /**
447
- * Backwards compatibility alias for createdAt.
448
- * @deprecated Use createdAt instead. This will be removed in a future version.
449
- */
450
- get timestamp(): any {
451
- return (this as any).createdAt;
452
- }
453
-
454
- /**
455
- * Extracts metadata from decorators for query building.
456
- *
457
- * @description
458
- * This method reads the metadata stored by decorators (@Property, @Collection, etc.)
459
- * and returns it in a structured format that's easier to work with for query builders
460
- * and other systems that need to introspect model structure.
461
- *
462
- * The metadata includes:
463
- * - Class name from @ModelOptions
464
- * - Property metadata (predicates, types, constraints, etc.)
465
- * - Collection metadata (predicates, filters, etc.)
466
- *
467
- * For models created via `fromJSONSchema()`, this method will derive metadata from
468
- * the stored `__properties` and `__collections` structures that were populated during
469
- * the dynamic class creation. If these structures are empty but a JSON schema was
470
- * attached to the class, it can fall back to deriving metadata from that schema.
471
- *
472
- * @returns Structured metadata object containing className, properties, and collections
473
- * @throws Error if the class doesn't have @ModelOptions decorator
474
- *
475
- * @example
476
- * ```typescript
477
- * @ModelOptions({ name: "Recipe" })
478
- * class Recipe extends Ad4mModel {
479
- * @Property({ through: "recipe://name", resolveLanguage: "literal" })
480
- * name: string = "";
481
- *
482
- * @Collection({ through: "recipe://ingredient" })
483
- * ingredients: string[] = [];
484
- * }
485
- *
486
- * const metadata = Recipe.getModelMetadata();
487
- * console.log(metadata.className); // "Recipe"
488
- * console.log(metadata.properties.name.predicate); // "recipe://name"
489
- * console.log(metadata.collections.ingredients.predicate); // "recipe://ingredient"
490
- * ```
491
- */
492
- public static getModelMetadata(): ModelMetadata {
493
- // Access the prototype with any type to access decorator-added properties
494
- const prototype = this.prototype as any;
495
-
496
- // Validate that the class has @ModelOptions decorator
497
- // The decorator sets prototype.className, so we check for its existence
498
- if (!prototype.className || prototype.className === 'Ad4mModel') {
499
- throw new Error("Model class must be decorated with @ModelOptions");
500
- }
501
-
502
- // Extract className
503
- const className = prototype.className;
504
-
505
- // Extract properties from prototype.__properties
506
- const propertiesMetadata: Record<string, PropertyMetadata> = {};
507
- const prototypeProperties = prototype.__properties || {};
508
-
509
- for (const [propertyName, opts] of Object.entries(prototypeProperties)) {
510
- const options = opts as PropertyOptions & { required?: boolean; flag?: boolean };
511
- propertiesMetadata[propertyName] = {
512
- name: propertyName,
513
- predicate: options.through || "",
514
- required: options.required || false,
515
- writable: options.writable || false,
516
- ...(options.initial !== undefined && { initial: options.initial }),
517
- ...(options.resolveLanguage !== undefined && { resolveLanguage: options.resolveLanguage }),
518
- ...(options.prologGetter !== undefined && { prologGetter: options.prologGetter }),
519
- ...(options.getter !== undefined && { getter: options.getter }),
520
- ...(options.prologSetter !== undefined && { prologSetter: options.prologSetter }),
521
- ...(options.local !== undefined && { local: options.local }),
522
- ...(options.transform !== undefined && { transform: options.transform }),
523
- ...(options.flag !== undefined && { flag: options.flag })
524
- };
525
- }
526
-
527
- // Extract collections from prototype.__collections
528
- const collectionsMetadata: Record<string, CollectionMetadata> = {};
529
- const prototypeCollections = prototype.__collections || {};
530
-
531
- for (const [collectionName, opts] of Object.entries(prototypeCollections)) {
532
- const options = opts as CollectionOptions;
533
- collectionsMetadata[collectionName] = {
534
- name: collectionName,
535
- predicate: options.through || "",
536
- ...(options.where !== undefined && { where: options.where }),
537
- ...(options.local !== undefined && { local: options.local }),
538
- ...(options.getter !== undefined && { getter: options.getter })
539
- };
540
- }
541
-
542
- // Fallback: If both structures are empty but a JSON schema is attached, derive from it
543
- // This handles edge cases where fromJSONSchema() was called but metadata wasn't properly populated
544
- const hasProperties = Object.keys(propertiesMetadata).length > 0;
545
- const hasCollections = Object.keys(collectionsMetadata).length > 0;
546
- const hasMetadata = hasProperties || hasCollections;
547
-
548
- if (!hasMetadata && prototype.__jsonSchema) {
549
- // Derive metadata from the attached JSON schema
550
- const schema = prototype.__jsonSchema;
551
- const options = prototype.__jsonSchemaOptions || {};
552
-
553
- if (schema.properties) {
554
- for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
555
- const isArray = isArrayType(propertySchema as JSONSchemaProperty);
556
- const predicate = this.determinePredicate(
557
- schema,
558
- propertyName,
559
- propertySchema as JSONSchemaProperty,
560
- this.determineNamespace(schema, options),
561
- options
562
- );
563
-
564
- if (isArray) {
565
- collectionsMetadata[propertyName] = {
566
- name: propertyName,
567
- predicate: predicate,
568
- ...(propertySchema["x-ad4m"]?.local !== undefined && { local: propertySchema["x-ad4m"].local })
569
- };
570
- } else {
571
- const isRequired = schema.required?.includes(propertyName) || false;
572
- propertiesMetadata[propertyName] = {
573
- name: propertyName,
574
- predicate: predicate,
575
- required: isRequired,
576
- writable: propertySchema["x-ad4m"]?.writable !== false,
577
- ...(propertySchema["x-ad4m"]?.resolveLanguage && { resolveLanguage: propertySchema["x-ad4m"].resolveLanguage }),
578
- ...(propertySchema["x-ad4m"]?.initial && { initial: propertySchema["x-ad4m"].initial }),
579
- ...(propertySchema["x-ad4m"]?.local !== undefined && { local: propertySchema["x-ad4m"].local })
580
- };
581
- }
582
- }
583
- }
584
- }
585
-
586
- return {
587
- className,
588
- properties: propertiesMetadata,
589
- collections: collectionsMetadata
590
- };
591
- }
592
-
593
- /**
594
- * Constructs a new model instance.
595
- *
596
- * @param perspective - The perspective where this model will be stored
597
- * @param baseExpression - Optional unique identifier for this instance
598
- * @param source - Optional source expression this instance is linked to
599
- *
600
- * @example
601
- * ```typescript
602
- * // Create a new recipe with auto-generated base expression
603
- * const recipe = new Recipe(perspective);
604
- *
605
- * // Create with specific base expression
606
- * const recipe = new Recipe(perspective, "recipe://chocolate-cake");
607
- *
608
- * // Create with source link
609
- * const recipe = new Recipe(perspective, undefined, "cookbook://desserts");
610
- * ```
611
- */
612
- constructor(perspective: PerspectiveProxy, baseExpression?: string, source?: string) {
613
- this.#baseExpression = baseExpression ? baseExpression : Literal.from(makeRandomPrologAtom(24)).toUrl();
614
- this.#perspective = perspective;
615
- this.#source = source || "ad4m://self";
616
- }
617
-
618
- /**
619
- * Gets the base expression of the subject.
620
- */
621
- get baseExpression() {
622
- return this.#baseExpression;
623
- }
624
-
625
- /**
626
- * Protected getter for the perspective.
627
- * Allows subclasses to access the perspective while keeping it private from external code.
628
- */
629
- protected get perspective(): PerspectiveProxy {
630
- return this.#perspective;
631
- }
632
-
633
- /**
634
- * Get property metadata from decorator (Phase 1: Prolog-free refactor)
635
- * @private
636
- */
637
- private getPropertyMetadata(key: string): PropertyOptions | undefined {
638
- const proto = Object.getPrototypeOf(this);
639
- return proto.__properties?.[key];
640
- }
641
-
642
- /**
643
- * Get collection metadata from decorator (Phase 1: Prolog-free refactor)
644
- * @private
645
- */
646
- private getCollectionMetadata(key: string): CollectionOptions | undefined {
647
- const proto = Object.getPrototypeOf(this);
648
- return proto.__collections?.[key];
649
- }
650
-
651
- /**
652
- * Generate property setter action from metadata (Phase 1: Prolog-free refactor)
653
- * Replaces Prolog query: property_setter(C, key, Setter)
654
- * @private
655
- */
656
- private generatePropertySetterAction(key: string, metadata: PropertyOptions): any[] {
657
- // Check if property is read-only
658
- if (metadata.writable === false) {
659
- throw new Error(`Property "${key}" is read-only and cannot be written`);
660
- }
661
-
662
- if (metadata.prologSetter) {
663
- // Custom Prolog setter - throw error for now (Phase 2)
664
- throw new Error(
665
- `Custom Prolog setter for property "${key}" not yet supported without Prolog. ` +
666
- `Use standard @Property decorator or enable Prolog for custom setters.`
667
- );
668
- }
669
-
670
- if (!metadata.through) {
671
- throw new Error(`Property "${key}" has no 'through' predicate defined`);
672
- }
673
-
674
- return [{
675
- action: "setSingleTarget",
676
- source: "this",
677
- predicate: metadata.through,
678
- target: "value",
679
- ...(metadata.local && { local: true })
680
- }];
681
- }
682
-
683
- /**
684
- * Generate collection action from metadata (Phase 1: Prolog-free refactor)
685
- * Replaces Prolog queries: collection_adder, collection_remover, collection_setter
686
- * @private
687
- */
688
- private generateCollectionAction(key: string, actionType: 'adder' | 'remover' | 'setter'): any[] {
689
- const metadata = this.getCollectionMetadata(key);
690
- if (!metadata) {
691
- throw new Error(`Collection "${key}" has no metadata defined`);
692
- }
693
-
694
- if (!metadata.through) {
695
- throw new Error(`Collection "${key}" has no 'through' predicate defined`);
696
- }
697
-
698
- const actionMap = {
699
- adder: "addLink",
700
- remover: "removeLink",
701
- setter: "collectionSetter"
702
- };
703
-
704
- return [{
705
- action: actionMap[actionType],
706
- source: "this",
707
- predicate: metadata.through,
708
- target: "value",
709
- ...(metadata.local && { local: true })
710
- }];
711
- }
712
-
713
- public static async assignValuesToInstance(perspective: PerspectiveProxy, instance: Ad4mModel, values: ValueTuple[]) {
714
- // Map properties to object
715
- const propsObject = Object.fromEntries(
716
- await Promise.all(
717
- values.map(async ([name, value, resolve]) => {
718
- let finalValue = value;
719
-
720
- // Handle UTF-8 byte sequences from Prolog URL decoding
721
- if (!resolve && typeof value === 'string') {
722
- // Only attempt reconstruction if the string looks like a byte string (all code points <= 0xFF)
723
- // and contains at least one high byte (>= 0x80). This avoids mangling valid Unicode.
724
- const codePoints = Array.from(value, ch => ch.codePointAt(0)!);
725
- const looksByteString = codePoints.every(cp => cp <= 0xFF);
726
- const hasHighByte = codePoints.some(cp => cp >= 0x80);
727
- if (looksByteString && hasHighByte) {
728
- try {
729
- const bytes = Uint8Array.from(codePoints);
730
- const decoded = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
731
- if (decoded !== value) finalValue = decoded;
732
- } catch (error) {
733
- // If UTF-8 conversion fails, keep the original value
734
- console.warn(`UTF-8 byte reconstruction failed for property "${name}"`, { value, error });
735
- }
736
- }
737
- }
738
-
739
- // Resolve the value if necessary
740
- if (resolve) {
741
- let resolvedExpression = await perspective.getExpression(value);
742
- if (resolvedExpression) {
743
- try {
744
- // Attempt to parse the data as JSON
745
- finalValue = JSON.parse(resolvedExpression.data);
746
- } catch (error) {
747
- // If parsing fails, keep the original data
748
- finalValue = resolvedExpression.data;
749
- }
750
- }
751
- }
752
- // Apply transform function if it exists
753
- const transform = instance["__properties"]?.[name]?.transform;
754
- if (transform && typeof transform === "function") {
755
- finalValue = transform(finalValue);
756
- }
757
- return [name, finalValue];
758
- })
759
- )
760
- );
761
- // Filter out properties that are read-only (getters without setters)
762
- const writableProps = Object.fromEntries(
763
- Object.entries(propsObject).filter(([key]) => {
764
- const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(instance), key);
765
- if (!descriptor) {
766
- // No descriptor means it's a regular property on the instance, allow it
767
- return true;
768
- }
769
- // Check if it's an accessor descriptor (has get/set) vs data descriptor (has value/writable)
770
- const isAccessor = descriptor.get !== undefined || descriptor.set !== undefined;
771
- if (isAccessor) {
772
- // Accessor descriptor: only allow if it has a setter
773
- return descriptor.set !== undefined;
774
- } else {
775
- // Data descriptor: only allow if writable is not explicitly false
776
- return descriptor.writable !== false;
777
- }
778
- })
779
- );
780
- // Assign properties to instance
781
- Object.assign(instance, writableProps);
782
- }
783
-
784
- private async getData() {
785
- // Builds an object with the author, timestamp, all properties, & all collections on the Ad4mModel and saves it to the instance
786
- // Use SurrealDB for data queries
787
- try {
788
- const ctor = this.constructor as typeof Ad4mModel;
789
- const metadata = ctor.getModelMetadata();
790
-
791
- // Query for all links from this specific node (base expression)
792
- // Using formatSurrealValue to prevent SQL injection by properly escaping the value
793
- const safeBaseExpression = ctor.formatSurrealValue(this.#baseExpression);
794
- // Note: We use ORDER BY timestamp ASC because:
795
- // - For collections: we want chronological order (oldest to newest)
796
- // - For properties: we select the LAST element to get "latest wins" semantics
797
- const linksQuery = `
798
- SELECT id, predicate, out.uri AS target, author, timestamp
799
- FROM link
800
- WHERE in.uri = ${safeBaseExpression}
801
- ORDER BY timestamp ASC
802
- `;
803
- const links = await this.#perspective.querySurrealDB(linksQuery);
804
-
805
- if (links && links.length > 0) {
806
- let minTimestamp = null;
807
- let maxTimestamp = null;
808
- let latestAuthor = null;
809
- let originalAuthor = null;
810
-
811
- // Process properties (skip those with custom getter)
812
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
813
- if (propMeta.getter) continue; // Handle via custom getter evaluation
814
- const matching = links.filter((l: any) => l.predicate === propMeta.predicate);
815
- if (matching.length > 0) {
816
- // "Latest wins" semantics: select the last element since links are ordered ASC.
817
- // The last element has the most recent timestamp and represents the current property value.
818
- const link = matching[matching.length - 1];
819
- let value = link.target;
820
-
821
- // Track timestamps/authors for createdAt and updatedAt
822
- if (link.timestamp) {
823
- if (!minTimestamp || link.timestamp < minTimestamp) {
824
- minTimestamp = link.timestamp;
825
- originalAuthor = link.author;
826
- }
827
- if (!maxTimestamp || link.timestamp > maxTimestamp) {
828
- maxTimestamp = link.timestamp;
829
- latestAuthor = link.author;
830
- }
831
- }
832
-
833
- // Handle resolveLanguage
834
- if (propMeta.resolveLanguage && propMeta.resolveLanguage !== 'literal') {
835
- try {
836
- const expression = await this.#perspective.getExpression(value);
837
- if (expression) {
838
- try {
839
- value = JSON.parse(expression.data);
840
- } catch {
841
- value = expression.data;
842
- }
843
- }
844
- } catch (e) {
845
- console.warn(`Failed to resolve expression for ${propName}:`, e);
846
- }
847
- } else if (propMeta.resolveLanguage === 'literal' && typeof value === 'string' && value.startsWith('literal://')) {
848
- // Only parse literal URIs when resolveLanguage is explicitly 'literal'.
849
- // Without this guard, properties pointing to baseExpressions of other models
850
- // (which may be literal:// strings) would get unwrapped, breaking link URI validation.
851
- try {
852
- const parsed = Literal.fromUrl(value).get();
853
- value = parsed.data !== undefined ? parsed.data : parsed;
854
- } catch (e) {
855
- // Keep original value
856
- }
857
- }
858
-
859
- // Apply transform if exists
860
- if (propMeta.transform && typeof propMeta.transform === 'function') {
861
- value = propMeta.transform(value);
862
- }
863
-
864
- (this as any)[propName] = value;
865
- }
866
- }
867
-
868
- // Process collections (skip those with custom getter)
869
- for (const [collName, collMeta] of Object.entries(metadata.collections)) {
870
- if (collMeta.getter) continue; // Handle via custom getter evaluation
871
- const matching = links.filter((l: any) => l.predicate === collMeta.predicate);
872
- // Collections preserve chronological order: links are sorted ASC by timestamp,
873
- // so the collection reflects the order in which items were added (oldest to newest).
874
- let values = matching.map((l: any) => l.target);
875
-
876
- // Apply where.condition filtering if present
877
- if (collMeta.where?.condition && values.length > 0) {
878
- try {
879
- // Filter values by evaluating condition for each value
880
- const filteredValues: string[] = [];
881
-
882
- for (const value of values) {
883
- let condition = collMeta.where.condition
884
- .replace(/\$perspective/g, `'${this.#perspective.uuid}'`)
885
- .replace(/\$base/g, `'${this.#baseExpression}'`)
886
- .replace(/Target/g, `'${value.replace(/'/g, "\\'")}'`);
887
-
888
- // If condition starts with WHERE, wrap it in array length check pattern
889
- // Using array::len() to properly count matching links
890
- if (condition.trim().startsWith('WHERE')) {
891
- condition = `array::len(SELECT * FROM link ${condition}) > 0`;
892
- }
893
-
894
- const filterQuery = `RETURN ${condition}`;
895
- const result = await this.#perspective.querySurrealDB(filterQuery);
896
-
897
- // RETURN can return the value directly or in an array
898
- const isTrue = result === true || (Array.isArray(result) && result.length > 0 && result[0] === true);
899
- if (isTrue) {
900
- filteredValues.push(value);
901
- }
902
- }
903
-
904
- values = filteredValues;
905
- } catch (error) {
906
- console.warn(`Failed to apply condition filter for ${collName}:`, error);
907
- // Keep unfiltered values on error
908
- }
909
- }
910
-
911
- // Apply where.isInstance filtering if present
912
- if (collMeta.where?.isInstance && values.length > 0) {
913
- try {
914
- const className = typeof collMeta.where.isInstance === 'string'
915
- ? collMeta.where.isInstance
916
- : collMeta.where.isInstance.name;
917
-
918
- const filterMetadata = await this.#perspective.getSubjectClassMetadataFromSDNA(className);
919
- if (filterMetadata) {
920
- values = await this.#perspective.batchCheckSubjectInstances(values, filterMetadata);
921
- }
922
- } catch (error) {
923
- // Keep unfiltered values on error
924
- }
925
- }
926
-
927
- (this as any)[collName] = values;
928
- }
929
-
930
- // Set author and timestamps
931
- if (originalAuthor) {
932
- (this as any).author = originalAuthor;
933
- }
934
- if (minTimestamp) {
935
- (this as any).createdAt = minTimestamp;
936
- }
937
- if (maxTimestamp) {
938
- (this as any).updatedAt = maxTimestamp;
939
- }
940
- }
941
-
942
- // Evaluate SurrealQL getters
943
- await ctor.evaluateCustomGettersForInstance(this, this.#perspective, metadata);
944
-
945
- // Apply where.isInstance filtering to getter collections
946
- // (non-getter collections were already filtered above)
947
- for (const [collName, collMeta] of Object.entries(metadata.collections)) {
948
- if (collMeta.getter && collMeta.where?.isInstance && (this as any)[collName]?.length > 0) {
949
- try {
950
- const className = typeof collMeta.where.isInstance === 'string'
951
- ? collMeta.where.isInstance
952
- : collMeta.where.isInstance.name;
953
-
954
- const filterMetadata = await this.#perspective.getSubjectClassMetadataFromSDNA(className);
955
- if (filterMetadata) {
956
- const filtered = await this.#perspective.batchCheckSubjectInstances((this as any)[collName], filterMetadata);
957
- (this as any)[collName] = filtered;
958
- }
959
- } catch (error) {
960
- // Keep unfiltered values on error
961
- }
962
- }
963
- }
964
- } catch (e) {
965
- console.error(`SurrealDB getData also failed for ${this.#baseExpression}:`, e);
966
- }
967
-
968
- return this;
969
- }
970
-
971
- // Todo: Only return AllInstances (InstancesWithOffset, SortedInstances, & UnsortedInstances not required)
972
- public static async queryToProlog(perspective: PerspectiveProxy, query: Query, modelClassName?: string | null) {
973
- const { source, properties, collections, where, order, offset, limit, count } = query;
974
- const className = modelClassName || (await this.getClassName(perspective));
975
-
976
- const instanceQueries = [
977
- buildAuthorAndTimestampQuery(),
978
- buildSourceQuery(source),
979
- buildPropertiesQuery(properties),
980
- buildCollectionsQuery(collections),
981
- buildWhereQuery(where),
982
- ];
983
-
984
- const resultSetQueries = [buildCountQuery(count), buildOrderQuery(order), buildOffsetQuery(offset), buildLimitQuery(limit)];
985
-
986
- const fullQuery = `
987
- findall([Base, Properties, Collections, Timestamp, Author], (
988
- subject_class("${className}", SubjectClass),
989
- instance(SubjectClass, Base),
990
- ${instanceQueries.filter((q) => q).join(", ")}
991
- ), UnsortedInstances),
992
- ${resultSetQueries.filter((q) => q).join(", ")}
993
- `;
994
-
995
- return fullQuery;
996
- }
997
-
998
- /**
999
- * Evaluates custom SurrealQL getters for properties and collections on a specific instance.
1000
- * @private
1001
- */
1002
- private static async evaluateCustomGettersForInstance(
1003
- instance: any,
1004
- perspective: PerspectiveProxy,
1005
- metadata: any
1006
- ) {
1007
- const safeBaseExpression = this.formatSurrealValue(instance.baseExpression);
1008
-
1009
- // Evaluate property getters
1010
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
1011
- if ((propMeta as any).getter) {
1012
- try {
1013
- // Replace 'Base' placeholder with actual base expression
1014
- const query = (propMeta as any).getter.replace(/Base/g, safeBaseExpression);
1015
- // Query from node table to have graph traversal context
1016
- const result = await perspective.querySurrealDB(
1017
- `SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`
1018
- );
1019
- if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null && result[0].value !== 'None' && result[0].value !== '') {
1020
- instance[propName] = result[0].value;
1021
- }
1022
- } catch (error) {
1023
- console.warn(`Failed to evaluate getter for ${propName}:`, error);
1024
- }
1025
- }
1026
- }
1027
-
1028
- // Evaluate collection getters
1029
- for (const [collName, collMeta] of Object.entries(metadata.collections)) {
1030
- if ((collMeta as any).getter) {
1031
- try {
1032
- // Replace 'Base' placeholder with actual base expression
1033
- const query = (collMeta as any).getter.replace(/Base/g, safeBaseExpression);
1034
- // Query from node table to have graph traversal context
1035
- const result = await perspective.querySurrealDB(
1036
- `SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`
1037
- );
1038
- if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null) {
1039
- // Filter out 'None' from collection results
1040
- const value = result[0].value;
1041
- instance[collName] = Array.isArray(value)
1042
- ? value.filter((v: any) => v !== undefined && v !== null && v !== '' && v !== 'None')
1043
- : value;
1044
- }
1045
- } catch (error) {
1046
- console.warn(`Failed to evaluate getter for ${collName}:`, error);
1047
- }
1048
- }
1049
- }
1050
- }
1051
-
1052
- /**
1053
- * Generates a SurrealQL query from a Query object.
1054
- *
1055
- * @description
1056
- * This method translates high-level query parameters into a SurrealQL query string
1057
- * that can be executed against the SurrealDB backend. Unlike Prolog queries which
1058
- * operate on SDNA-aware predicates, SurrealQL queries operate directly on raw links
1059
- * stored in SurrealDB.
1060
- *
1061
- * The generated query uses a CTE (Common Table Expression) pattern:
1062
- * 1. First, identify candidate base expressions by filtering links based on where conditions
1063
- * 2. Then, for each candidate base, resolve properties and collections via subqueries
1064
- * 3. Finally, apply ordering, pagination (LIMIT/START) at the SQL level
1065
- *
1066
- * Key architectural notes:
1067
- * - SurrealDB stores only raw links (source, predicate, target, author, timestamp)
1068
- * - No SDNA knowledge at the database level
1069
- * - Properties are resolved via subqueries that look for links with specific predicates
1070
- * - Collections are similar but return multiple values instead of one
1071
- * - Special fields (base, author, timestamp) are accessed directly, not via subqueries
1072
- *
1073
- * @param perspective - The perspective to query (used for metadata extraction)
1074
- * @param query - Query parameters (where, order, limit, offset, properties, collections)
1075
- * @returns Complete SurrealQL query string ready for execution
1076
- *
1077
- * @example
1078
- * ```typescript
1079
- * const query = Recipe.queryToSurrealQL(perspective, {
1080
- * where: { name: "Pasta", rating: { gt: 4 } },
1081
- * order: { timestamp: "DESC" },
1082
- * limit: 10
1083
- * });
1084
- * // Returns: SELECT source AS base, array::first(target[WHERE predicate = ...]) AS name, ...
1085
- * // FROM link WHERE ... GROUP BY source ORDER BY timestamp DESC LIMIT 10
1086
- * ```
1087
- */
1088
- public static async queryToSurrealQL(perspective: PerspectiveProxy, query: Query): Promise<string> {
1089
- const metadata = this.getModelMetadata();
1090
- const { source, where, order, offset, limit } = query;
1091
-
1092
- // Build list of graph traversal filters for required predicates
1093
- const graphTraversalFilters: string[] = [];
1094
-
1095
- // Add source filter if specified (filter to nodes that are children of this source)
1096
- // Source filter means: find targets of 'ad4m://has_child' links from the specified source
1097
- if (source) {
1098
- // Use graph traversal: node must be target of has_child link from source
1099
- graphTraversalFilters.push(
1100
- `count(<-link[WHERE perspective = $perspective AND in.uri = ${this.formatSurrealValue(source)} AND predicate = 'ad4m://has_child']) > 0`
1101
- );
1102
- }
1103
-
1104
- // Add filters for required properties
1105
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
1106
- if (propMeta.required) {
1107
- // For flag properties, also filter by the target value
1108
- if (propMeta.flag && propMeta.initial) {
1109
- graphTraversalFilters.push(
1110
- `count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`
1111
- );
1112
- } else {
1113
- graphTraversalFilters.push(
1114
- `count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`
1115
- );
1116
- }
1117
- }
1118
- }
1119
-
1120
- // If no required properties, we need at least one property to define the model
1121
- // Use any property with an initial value as the defining characteristic
1122
- if (graphTraversalFilters.length === 0) {
1123
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
1124
- if (propMeta.initial) {
1125
- // For flag properties, also filter by the target value
1126
- if (propMeta.flag) {
1127
- graphTraversalFilters.push(
1128
- `count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`
1129
- );
1130
- } else {
1131
- graphTraversalFilters.push(
1132
- `count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`
1133
- );
1134
- }
1135
- break; // Just need one defining property
1136
- }
1137
- }
1138
- }
1139
-
1140
- // Build user WHERE clause filters using graph traversal
1141
- const userWhereClause = this.buildGraphTraversalWhereClause(metadata, where);
1142
-
1143
- // Build complete WHERE clause using graph traversal filters
1144
- const whereConditions: string[] = [];
1145
-
1146
- // Add all graph traversal filters for required properties
1147
- whereConditions.push(...graphTraversalFilters);
1148
-
1149
- // Add user where conditions if any
1150
- if (userWhereClause) {
1151
- whereConditions.push(userWhereClause);
1152
- }
1153
-
1154
- // Always ensure node has at least one link in this perspective
1155
- whereConditions.push(`count(->link[WHERE perspective = $perspective]) > 0`);
1156
-
1157
- // Build the query FROM node using direct graph traversal in WHERE
1158
- // This avoids slow subqueries and uses graph indexes for fast traversal
1159
- const fullQuery = `
1160
- SELECT
1161
- id AS source,
1162
- uri AS source_uri,
1163
- ->link[WHERE perspective = $perspective] AS links
1164
- FROM node
1165
- WHERE ${whereConditions.join(' AND ')}
1166
- `.trim();
1167
-
1168
- return fullQuery;
1169
- }
1170
-
1171
- /**
1172
- * Builds the WHERE clause for SurrealQL queries using graph traversal syntax.
1173
- *
1174
- * @description
1175
- * Translates where conditions into graph traversal filters: `->link[WHERE ...]`
1176
- * This is more efficient than nested SELECTs because SurrealDB can optimize graph traversals.
1177
- *
1178
- * Handles several condition types:
1179
- * - Simple equality: `{ name: "Pasta" }` → `->link[WHERE predicate = 'X' AND out.uri = 'Pasta']`
1180
- * - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → `->link[WHERE predicate = 'X' AND out.uri IN [...]]`
1181
- * - NOT operators: Use `NOT` prefix
1182
- * - Comparison operators (gt, gte, lt, lte, etc.): Handled in post-query JavaScript filtering
1183
- * - Special fields: base uses `uri` directly, author/timestamp handled post-query
1184
- *
1185
- * @param metadata - Model metadata containing property predicates
1186
- * @param where - Where conditions from the query
1187
- * @returns Graph traversal WHERE clause filters, or empty string if no conditions
1188
- *
1189
- * @private
1190
- */
1191
- private static buildGraphTraversalWhereClause(metadata: ModelMetadata, where?: Where): string {
1192
- if (!where) return '';
1193
-
1194
- const conditions: string[] = [];
1195
-
1196
- for (const [propertyName, condition] of Object.entries(where)) {
1197
- // Check if this is a special field (base, author, timestamp)
1198
- // Note: author and timestamp filtering is done in JavaScript after query
1199
- const isSpecial = ['base', 'author', 'timestamp'].includes(propertyName);
1200
-
1201
- if (isSpecial) {
1202
- // Skip author and timestamp - they'll be filtered in JavaScript
1203
- // Only handle 'base' (which maps to 'uri') here
1204
- if (propertyName === 'author' || propertyName === 'timestamp') {
1205
- continue; // Skip - will be filtered post-query
1206
- }
1207
-
1208
- const columnName = 'uri'; // base maps to uri in node table
1209
-
1210
- // Handle base/uri field directly
1211
- if (Array.isArray(condition)) {
1212
- // Array values (IN clause)
1213
- const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
1214
- conditions.push(`${columnName} IN [${formattedValues}]`);
1215
- } else if (typeof condition === 'object' && condition !== null) {
1216
- // Operator object
1217
- const ops = condition as any;
1218
- if (ops.not !== undefined) {
1219
- if (Array.isArray(ops.not)) {
1220
- const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1221
- conditions.push(`${columnName} NOT IN [${formattedValues}]`);
1222
- } else {
1223
- conditions.push(`${columnName} != ${this.formatSurrealValue(ops.not)}`);
1224
- }
1225
- }
1226
- if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
1227
- conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.between[0])} AND ${columnName} <= ${this.formatSurrealValue(ops.between[1])}`);
1228
- }
1229
- if (ops.gt !== undefined) {
1230
- conditions.push(`${columnName} > ${this.formatSurrealValue(ops.gt)}`);
1231
- }
1232
- if (ops.gte !== undefined) {
1233
- conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.gte)}`);
1234
- }
1235
- if (ops.lt !== undefined) {
1236
- conditions.push(`${columnName} < ${this.formatSurrealValue(ops.lt)}`);
1237
- }
1238
- if (ops.lte !== undefined) {
1239
- conditions.push(`${columnName} <= ${this.formatSurrealValue(ops.lte)}`);
1240
- }
1241
- if (ops.contains !== undefined) {
1242
- conditions.push(`${columnName} CONTAINS ${this.formatSurrealValue(ops.contains)}`);
1243
- }
1244
- } else {
1245
- // Simple equality
1246
- conditions.push(`${columnName} = ${this.formatSurrealValue(condition)}`);
1247
- }
1248
- } else {
1249
- // Handle regular properties via graph traversal
1250
- const propMeta = metadata.properties[propertyName];
1251
- if (!propMeta) continue; // Skip if property not found in metadata
1252
-
1253
- const predicate = escapeSurrealString(propMeta.predicate);
1254
- // Use fn::parse_literal() for properties with resolveLanguage
1255
- const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(out.uri)' : 'out.uri';
1256
-
1257
- if (Array.isArray(condition)) {
1258
- // Array values (IN clause)
1259
- const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
1260
- conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
1261
- } else if (typeof condition === 'object' && condition !== null) {
1262
- // Operator object
1263
- const ops = condition as any;
1264
- if (ops.not !== undefined) {
1265
- if (Array.isArray(ops.not)) {
1266
- // For NOT IN with array: must NOT have a link with value in the array
1267
- const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1268
- conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
1269
- } else {
1270
- // For NOT with single value: must NOT have this value
1271
- conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(ops.not)}]) = 0`);
1272
- }
1273
- }
1274
- // Note: gt, gte, lt, lte, between, contains operators are filtered in JavaScript
1275
- // post-query because fn::parse_literal() comparisons in SurrealDB
1276
- // don't work reliably with numeric comparisons.
1277
- // These are handled in instancesFromSurrealResult along with author/timestamp filtering.
1278
- // However, we still need to ensure the property exists
1279
- const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
1280
- ops.lt !== undefined || ops.lte !== undefined ||
1281
- ops.between !== undefined || ops.contains !== undefined;
1282
- if (hasComparisonOps) {
1283
- // Ensure we only get nodes that have this property
1284
- conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}']) > 0`);
1285
- }
1286
- } else {
1287
- // Simple equality
1288
- conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(condition)}]) > 0`);
1289
- }
1290
- }
1291
- }
1292
-
1293
- return conditions.join(' AND ');
1294
- }
1295
-
1296
- /**
1297
- * Builds the WHERE clause for SurrealQL queries.
1298
- *
1299
- * @description
1300
- * Translates the where conditions from the Query object into SurrealQL WHERE clause fragments.
1301
- * For each property filter, generates a subquery that checks for links with the appropriate
1302
- * predicate and target value.
1303
- *
1304
- * Handles several condition types:
1305
- * - Simple equality: `{ name: "Pasta" }` → subquery checking for predicate and target match
1306
- * - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → target IN [...]
1307
- * - Operators: `{ rating: { gt: 4 } }` → target > '4'
1308
- * - gt, gte, lt, lte: comparison operators
1309
- * - not: negation (single value or array)
1310
- * - between: range check
1311
- * - contains: substring/element check (uses SurrealQL CONTAINS)
1312
- * - Special fields: base, author, timestamp are accessed directly, not via subqueries
1313
- *
1314
- * All conditions are joined with AND.
1315
- *
1316
- * @param metadata - Model metadata containing property predicates
1317
- * @param where - Where conditions from the query
1318
- * @returns WHERE clause string (without the "WHERE" keyword), or empty string if no conditions
1319
- *
1320
- * @private
1321
- */
1322
- private static buildSurrealWhereClause(metadata: ModelMetadata, where?: Where): string {
1323
- if (!where) return '';
1324
-
1325
- const conditions: string[] = [];
1326
-
1327
- for (const [propertyName, condition] of Object.entries(where)) {
1328
- // Check if this is a special field (base, author, timestamp)
1329
- // Note: author and timestamp filtering is done in JavaScript after GROUP BY
1330
- // because they need to be computed from the grouped links first
1331
- const isSpecial = ['base', 'author', 'timestamp'].includes(propertyName);
1332
-
1333
- if (isSpecial) {
1334
- // Skip author and timestamp - they'll be filtered in JavaScript
1335
- // Only handle 'base' (which maps to 'source') here
1336
- if (propertyName === 'author' || propertyName === 'timestamp') {
1337
- continue; // Skip - will be filtered post-query
1338
- }
1339
-
1340
- const columnName = 'source'; // base maps to source
1341
-
1342
- // Handle base/source field directly
1343
- if (Array.isArray(condition)) {
1344
- // Array values (IN clause)
1345
- const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
1346
- conditions.push(`${columnName} IN [${formattedValues}]`);
1347
- } else if (typeof condition === 'object' && condition !== null) {
1348
- // Operator object
1349
- const ops = condition as any;
1350
- if (ops.not !== undefined) {
1351
- if (Array.isArray(ops.not)) {
1352
- const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1353
- conditions.push(`${columnName} NOT IN [${formattedValues}]`);
1354
- } else {
1355
- conditions.push(`${columnName} != ${this.formatSurrealValue(ops.not)}`);
1356
- }
1357
- }
1358
- if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
1359
- conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.between[0])} AND ${columnName} <= ${this.formatSurrealValue(ops.between[1])}`);
1360
- }
1361
- if (ops.gt !== undefined) {
1362
- conditions.push(`${columnName} > ${this.formatSurrealValue(ops.gt)}`);
1363
- }
1364
- if (ops.gte !== undefined) {
1365
- conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.gte)}`);
1366
- }
1367
- if (ops.lt !== undefined) {
1368
- conditions.push(`${columnName} < ${this.formatSurrealValue(ops.lt)}`);
1369
- }
1370
- if (ops.lte !== undefined) {
1371
- conditions.push(`${columnName} <= ${this.formatSurrealValue(ops.lte)}`);
1372
- }
1373
- if (ops.contains !== undefined) {
1374
- conditions.push(`${columnName} CONTAINS ${this.formatSurrealValue(ops.contains)}`);
1375
- }
1376
- } else {
1377
- // Simple equality
1378
- conditions.push(`${columnName} = ${this.formatSurrealValue(condition)}`);
1379
- }
1380
- } else {
1381
- // Handle regular properties via subqueries
1382
- const propMeta = metadata.properties[propertyName];
1383
- if (!propMeta) continue; // Skip if property not found in metadata
1384
-
1385
- const predicate = escapeSurrealString(propMeta.predicate);
1386
- // Use fn::parse_literal() for properties with resolveLanguage
1387
- const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(target)' : 'target';
1388
-
1389
- if (Array.isArray(condition)) {
1390
- // Array values (IN clause)
1391
- const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
1392
- conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}])`);
1393
- } else if (typeof condition === 'object' && condition !== null) {
1394
- // Operator object
1395
- const ops = condition as any;
1396
- if (ops.not !== undefined) {
1397
- if (Array.isArray(ops.not)) {
1398
- // For NOT IN with array: exclude sources that HAVE a value in the array
1399
- const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1400
- conditions.push(`source NOT IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}])`);
1401
- } else {
1402
- // For NOT with single value: exclude sources that HAVE this value
1403
- conditions.push(`source NOT IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(ops.not)})`);
1404
- }
1405
- }
1406
- // Note: gt, gte, lt, lte, between, contains operators are filtered in JavaScript
1407
- // post-query because fn::parse_literal() comparisons in SurrealDB subqueries
1408
- // don't work reliably with numeric comparisons.
1409
- // These are handled in instancesFromSurrealResult along with author/timestamp filtering.
1410
- // However, we still need to ensure the property exists by filtering on the predicate
1411
- const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
1412
- ops.lt !== undefined || ops.lte !== undefined ||
1413
- ops.between !== undefined || ops.contains !== undefined;
1414
- if (hasComparisonOps) {
1415
- // Ensure we only get instances that have this property
1416
- conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}')`);
1417
- }
1418
- } else {
1419
- // Simple equality
1420
- conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(condition)})`);
1421
- }
1422
- }
1423
- }
1424
-
1425
- return conditions.join(' AND ');
1426
- }
1427
-
1428
- /**
1429
- * Builds the SELECT fields for SurrealQL queries.
1430
- *
1431
- * @description
1432
- * Generates the field list for the SELECT clause, resolving properties and collections
1433
- * via subqueries. Each property is fetched with a subquery that finds the link with the
1434
- * appropriate predicate and returns its target. Collections are similar but don't use LIMIT 1.
1435
- *
1436
- * Field types:
1437
- * - Properties: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X' LIMIT 1) AS propName`
1438
- * - Collections: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X') AS collName`
1439
- * - Author/Timestamp: Always included to provide metadata about each instance
1440
- *
1441
- * If properties or collections arrays are provided, only those fields are included.
1442
- * Otherwise, all properties/collections from metadata are included.
1443
- *
1444
- * @param metadata - Model metadata containing property and collection predicates
1445
- * @param properties - Optional array of property names to include (default: all)
1446
- * @param collections - Optional array of collection names to include (default: all)
1447
- * @returns Comma-separated SELECT field list
1448
- *
1449
- * @private
1450
- */
1451
- private static buildSurrealSelectFields(metadata: ModelMetadata, properties?: string[], collections?: string[]): string {
1452
- const fields: string[] = [];
1453
-
1454
- // Determine properties to fetch
1455
- const propsToFetch = properties || Object.keys(metadata.properties);
1456
- for (const propName of propsToFetch) {
1457
- const propMeta = metadata.properties[propName];
1458
- if (!propMeta) continue; // Skip if not found
1459
-
1460
- // Reference source directly since we're selecting from link table
1461
- const escapedPredicate = escapeSurrealString(propMeta.predicate);
1462
- fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}' LIMIT 1) AS ${propName}`);
1463
- }
1464
-
1465
- // Determine collections to fetch
1466
- const collsToFetch = collections || Object.keys(metadata.collections);
1467
- for (const collName of collsToFetch) {
1468
- const collMeta = metadata.collections[collName];
1469
- if (!collMeta) continue; // Skip if not found
1470
-
1471
- // Reference source directly since we're selecting from link table
1472
- const escapedPredicate = escapeSurrealString(collMeta.predicate);
1473
- fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}') AS ${collName}`);
1474
- }
1475
-
1476
- // Always add author and timestamp fields
1477
- fields.push(`(SELECT VALUE author FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS author`);
1478
- fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS createdAt`);
1479
- fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp DESC LIMIT 1) AS updatedAt`);
1480
-
1481
- return fields.join(',\n ');
1482
- }
1483
-
1484
- /**
1485
- * Builds the SELECT fields for SurrealQL queries using aggregation functions.
1486
- * Compatible with GROUP BY source queries.
1487
- *
1488
- * @private
1489
- */
1490
- private static buildSurrealSelectFieldsWithAggregation(metadata: ModelMetadata, properties?: string[], collections?: string[]): string {
1491
- const fields: string[] = [];
1492
-
1493
- // Determine properties to fetch
1494
- const propsToFetch = properties || Object.keys(metadata.properties);
1495
- for (const propName of propsToFetch) {
1496
- const propMeta = metadata.properties[propName];
1497
- if (!propMeta) continue; // Skip if not found
1498
-
1499
- // Use array::first to get the first target value for this predicate
1500
- const escapedPredicate = escapeSurrealString(propMeta.predicate);
1501
- fields.push(`array::first(target[WHERE predicate = '${escapedPredicate}']) AS ${propName}`);
1502
- }
1503
-
1504
- // Determine collections to fetch
1505
- const collsToFetch = collections || Object.keys(metadata.collections);
1506
- for (const collName of collsToFetch) {
1507
- const collMeta = metadata.collections[collName];
1508
- if (!collMeta) continue; // Skip if not found
1509
-
1510
- // Use array filtering to get all target values for this predicate
1511
- const escapedPredicate = escapeSurrealString(collMeta.predicate);
1512
- fields.push(`target[WHERE predicate = '${escapedPredicate}'] AS ${collName}`);
1513
- }
1514
-
1515
- // Always add author and timestamp fields
1516
- fields.push(`array::first(author) AS author`);
1517
- fields.push(`array::first(timestamp) AS createdAt`);
1518
- fields.push(`array::last(timestamp) AS updatedAt`);
1519
-
1520
- return fields.join(',\n ');
1521
- }
1522
-
1523
-
1524
- /**
1525
- * Formats a value for use in SurrealQL queries.
1526
- *
1527
- * @description
1528
- * Handles different value types:
1529
- * - Strings: Wrapped in single quotes with backslash-escaped special characters
1530
- * - Numbers/booleans: Converted to string
1531
- * - Arrays: Recursively formatted and wrapped in brackets
1532
- *
1533
- * @param value - The value to format
1534
- * @returns Formatted value string ready for SurrealQL
1535
- *
1536
- * @private
1537
- */
1538
- private static formatSurrealValue(value: any): string {
1539
- if (typeof value === 'string') {
1540
- // Escape backslashes first, then single quotes and other special characters
1541
- const escaped = value
1542
- .replace(/\\/g, '\\\\') // Backslash -> \\
1543
- .replace(/'/g, "\\'") // Single quote -> \'
1544
- .replace(/"/g, '\\"') // Double quote -> \"
1545
- .replace(/\n/g, '\\n') // Newline -> \n
1546
- .replace(/\r/g, '\\r') // Carriage return -> \r
1547
- .replace(/\t/g, '\\t'); // Tab -> \t
1548
- return `'${escaped}'`;
1549
- } else if (typeof value === 'number' || typeof value === 'boolean') {
1550
- return String(value);
1551
- } else if (Array.isArray(value)) {
1552
- return `[${value.map(v => this.formatSurrealValue(v)).join(', ')}]`;
1553
- } else {
1554
- return String(value);
1555
- }
1556
- }
1557
-
1558
- public static async instancesFromPrologResult<T extends Ad4mModel>(
1559
- this: typeof Ad4mModel & (new (...args: any[]) => T),
1560
- perspective: PerspectiveProxy,
1561
- query: Query,
1562
- result: AllInstancesResult
1563
- ): Promise<ResultsWithTotalCount<T>> {
1564
- if (!result?.[0]?.AllInstances) return { results: [], totalCount: 0 };
1565
- // Map results to instances
1566
- const requestedAttribtes = [...(query?.properties || []), ...(query?.collections || [])];
1567
- const allInstances = await Promise.all(
1568
- result[0].AllInstances.map(async ([Base, Properties, Collections, Timestamp, Author]) => {
1569
- try {
1570
- const instance = new this(perspective, Base) as any;
1571
- // Remove unrequested attributes from instance
1572
- if (requestedAttribtes.length) {
1573
- Object.keys(instance).forEach((key) => {
1574
- if (!requestedAttribtes.includes(key)) delete instance[key];
1575
- });
1576
- }
1577
- // Collect values to assign to instance
1578
- const values = [...Properties, ...Collections, ["createdAt", Timestamp], ["author", Author]];
1579
- await Ad4mModel.assignValuesToInstance(perspective, instance, values);
1580
-
1581
- return instance;
1582
- } catch (error) {
1583
- console.error(`Failed to process instance ${Base}:`, error);
1584
- // Return null for failed instances - we'll filter these out below
1585
- return null;
1586
- }
1587
- })
1588
- );
1589
- return { results: allInstances.filter((instance) => instance !== null), totalCount: result[0].TotalCount };
1590
- }
1591
-
1592
- /**
1593
- * Converts SurrealDB query results to Ad4mModel instances.
1594
- *
1595
- * @param perspective - The perspective context
1596
- * @param query - The query parameters used
1597
- * @param result - Array of result objects from SurrealDB
1598
- * @returns Promise resolving to results with total count
1599
- *
1600
- * @internal
1601
- */
1602
- public static async instancesFromSurrealResult<T extends Ad4mModel>(
1603
- this: typeof Ad4mModel & (new (...args: any[]) => T),
1604
- perspective: PerspectiveProxy,
1605
- query: Query,
1606
- result: any[]
1607
- ): Promise<ResultsWithTotalCount<T>> {
1608
- if (!result || result.length === 0) return { results: [], totalCount: 0 };
1609
-
1610
- const metadata = this.getModelMetadata();
1611
- const requestedProperties = query?.properties || [];
1612
- const requestedCollections = query?.collections || [];
1613
-
1614
- // The query used GROUP BY with graph traversal, so each row has:
1615
- // - source: the node ID (e.g., "node:abc123")
1616
- // - source_uri: the actual URI (the base expression)
1617
- // - links: array of link objects with {predicate, target, author, timestamp}
1618
-
1619
- const instances: T[] = [];
1620
- for (const row of result) {
1621
- let base;
1622
- try {
1623
- // Use source_uri as the base (the actual URI), not the node ID
1624
- base = row.source_uri;
1625
-
1626
- // Skip rows without a source_uri field
1627
- if (!base) {
1628
- continue;
1629
- }
1630
-
1631
- const links = row.links || [];
1632
-
1633
- const instance = new this(perspective, base) as any;
1634
-
1635
- // Track both earliest (createdAt) and most recent (updatedAt) timestamps
1636
- let minTimestamp = null;
1637
- let maxTimestamp = null;
1638
- let originalAuthor = null;
1639
- let latestAuthor = null;
1640
-
1641
- // Process each link (track index for collection ordering)
1642
- for (let linkIndex = 0; linkIndex < links.length; linkIndex++) {
1643
- const link = links[linkIndex];
1644
- const predicate = link.predicate;
1645
- const target = link.target;
1646
-
1647
- // Skip 'None' values
1648
- if (target === 'None') continue;
1649
-
1650
- // Track both earliest (createdAt) and latest (updatedAt) timestamps with their authors
1651
- if (link.timestamp) {
1652
- if (!minTimestamp || link.timestamp < minTimestamp) {
1653
- minTimestamp = link.timestamp;
1654
- originalAuthor = link.author;
1655
- }
1656
- if (!maxTimestamp || link.timestamp > maxTimestamp) {
1657
- maxTimestamp = link.timestamp;
1658
- latestAuthor = link.author;
1659
- }
1660
- }
1661
-
1662
- // Find matching property (skip those with getter)
1663
- let foundProperty = false;
1664
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
1665
- if (propMeta.getter) continue; // Handle via getter evaluation
1666
- if (propMeta.predicate === predicate) {
1667
- // For properties, take the first value (or we could use timestamp to get latest)
1668
- // Note: Empty objects {} are truthy, so we need to check for them explicitly
1669
- const currentValue = instance[propName];
1670
- const isEmptyObject = typeof currentValue === 'object' && currentValue !== null && !Array.isArray(currentValue) && Object.keys(currentValue).length === 0;
1671
- if (!currentValue || currentValue === "" || currentValue === 0 || isEmptyObject) {
1672
- let convertedValue = target;
1673
-
1674
- // Only process if target has a value
1675
- if (target !== undefined && target !== null && target !== '') {
1676
- // Check if we need to resolve a non-literal language expression.
1677
- // resolveLanguage must be defined and not 'literal' to trigger expression resolution.
1678
- // Also skip if the target itself is a literal:// URI — those are handled by the
1679
- // literal-parsing branch below (avoids calling getExpression on empty literals like
1680
- // "literal://string:" which would cause a deserialization error).
1681
- if (propMeta.resolveLanguage != undefined && propMeta.resolveLanguage !== 'literal' && typeof target === 'string' && !target.startsWith('literal://')) {
1682
- // For non-literal languages, resolve the expression via perspective.getExpression()
1683
- // Note: Literals are already parsed by SurrealDB's fn::parse_literal()
1684
- try {
1685
- const expression = await perspective.getExpression(target);
1686
- if (expression) {
1687
- // Parse the expression data if it's a JSON string
1688
- try {
1689
- convertedValue = JSON.parse(expression.data);
1690
- } catch {
1691
- // If parsing fails, use the data as-is
1692
- convertedValue = expression.data;
1693
- }
1694
- }
1695
- } catch (e) {
1696
- console.warn(`Failed to resolve expression for ${propName} with target "${target}":`, e);
1697
- console.warn("Falling back to raw value");
1698
- convertedValue = target; // Fall back to raw value
1699
- }
1700
- } else if (propMeta.resolveLanguage === 'literal' && typeof target === 'string' && target.startsWith('literal://')) {
1701
- // Only parse literal URIs when resolveLanguage is explicitly set to 'literal'.
1702
- // Without this check, properties pointing to baseExpressions of other models
1703
- // (which may be literal:// strings) would get unwrapped, breaking link URI validation.
1704
- try {
1705
- const parsed = Literal.fromUrl(target).get();
1706
- if(parsed.data !== undefined) {
1707
- convertedValue = parsed.data;
1708
- } else {
1709
- convertedValue = parsed;
1710
- }
1711
- } catch (e) {
1712
- // If literal parsing fails, just use the value as-is (don't bail)
1713
- convertedValue = target;
1714
- }
1715
- } else if (typeof target === 'string') {
1716
- // Type conversion: check the instance property's current type
1717
- const expectedType = typeof instance[propName];
1718
- if (expectedType === 'number') {
1719
- convertedValue = Number(target);
1720
- } else if (expectedType === 'boolean') {
1721
- convertedValue = target === 'true' || target === '1';
1722
- }
1723
- }
1724
- }
1725
-
1726
- // Apply transform function if it exists
1727
- if (propMeta.transform && typeof propMeta.transform === 'function') {
1728
- convertedValue = propMeta.transform(convertedValue);
1729
- }
1730
-
1731
- instance[propName] = convertedValue;
1732
- }
1733
- foundProperty = true;
1734
- break;
1735
- }
1736
- }
1737
-
1738
- // If not a property, check if it's a collection (skip those with getter)
1739
- if (!foundProperty) {
1740
- for (const [collName, collMeta] of Object.entries(metadata.collections)) {
1741
- if (collMeta.getter) continue; // Handle via getter evaluation
1742
- if (collMeta.predicate === predicate) {
1743
- // For collections, accumulate all values with their timestamps and indices for sorting
1744
- if (!instance[collName]) {
1745
- instance[collName] = [];
1746
- }
1747
- // Initialize timestamp tracking array if not already done
1748
- const timestampsKey = `__${collName}_timestamps`;
1749
- const indicesKey = `__${collName}_indices`;
1750
- if (!instance[timestampsKey]) {
1751
- instance[timestampsKey] = [];
1752
- }
1753
- if (!instance[indicesKey]) {
1754
- instance[indicesKey] = [];
1755
- }
1756
- if (!instance[collName].includes(target)) {
1757
- instance[collName].push(target);
1758
- instance[timestampsKey].push(link.timestamp || '');
1759
- // Track original position in the links array for stable sorting
1760
- instance[indicesKey].push(linkIndex);
1761
- }
1762
- break;
1763
- }
1764
- }
1765
- }
1766
- }
1767
-
1768
- // Set author and timestamps
1769
- if (originalAuthor) {
1770
- instance.author = originalAuthor;
1771
- }
1772
-
1773
- // Set createdAt from earliest timestamp
1774
- if (minTimestamp) {
1775
- if (typeof minTimestamp === 'string' && minTimestamp.includes('T')) {
1776
- instance.createdAt = new Date(minTimestamp).getTime();
1777
- } else if (typeof minTimestamp === 'string') {
1778
- const parsed = parseInt(minTimestamp, 10);
1779
- instance.createdAt = isNaN(parsed) ? minTimestamp : parsed;
1780
- } else {
1781
- instance.createdAt = minTimestamp;
1782
- }
1783
- }
1784
-
1785
- // Set updatedAt from most recent timestamp
1786
- if (maxTimestamp) {
1787
- if (typeof maxTimestamp === 'string' && maxTimestamp.includes('T')) {
1788
- instance.updatedAt = new Date(maxTimestamp).getTime();
1789
- } else if (typeof maxTimestamp === 'string') {
1790
- const parsed = parseInt(maxTimestamp, 10);
1791
- instance.updatedAt = isNaN(parsed) ? maxTimestamp : parsed;
1792
- } else {
1793
- instance.updatedAt = maxTimestamp;
1794
- }
1795
- }
1796
-
1797
- // Sort collections by timestamp to maintain insertion order
1798
- for (const [collName, collMeta] of Object.entries(metadata.collections)) {
1799
- const timestampsKey = `__${collName}_timestamps`;
1800
- const indicesKey = `__${collName}_indices`;
1801
- if (instance[collName] && instance[timestampsKey]) {
1802
- // Create array of [value, timestamp, index] tuples
1803
- const pairs = instance[collName].map((value: any, index: number) => ({
1804
- value,
1805
- timestamp: instance[timestampsKey][index] || '',
1806
- originalIndex: instance[indicesKey]?.[index] ?? index
1807
- }));
1808
- // Sort by timestamp first, then by original index for stable sorting
1809
- pairs.sort((a, b) => {
1810
- const tsA = String(a.timestamp || '');
1811
- const tsB = String(b.timestamp || '');
1812
- const tsCompare = tsA.localeCompare(tsB);
1813
- if (tsCompare !== 0) return tsCompare;
1814
- // Use original index as tiebreaker for stable sorting
1815
- return a.originalIndex - b.originalIndex;
1816
- });
1817
- // Replace collection with sorted values, filtering out empty strings and None
1818
- instance[collName] = pairs
1819
- .map(p => p.value)
1820
- .filter((v: any) => v !== undefined && v !== null && v !== '' && v !== 'None');
1821
- // Clean up temporary arrays
1822
- delete instance[timestampsKey];
1823
- delete instance[indicesKey];
1824
- }
1825
- }
1826
-
1827
- // Filter by requested attributes if specified
1828
- if (requestedProperties.length > 0 || requestedCollections.length > 0) {
1829
- const requestedAttributes = [...requestedProperties, ...requestedCollections];
1830
- Object.keys(instance).forEach((key) => {
1831
- // Keep only requested attributes, plus always keep createdAt, updatedAt, author, and baseExpression
1832
- // Note: timestamp is a getter alias for createdAt, so we preserve createdAt instead
1833
- if (!requestedAttributes.includes(key) && key !== 'createdAt' && key !== 'updatedAt' && key !== 'author' && key !== 'baseExpression') {
1834
- delete instance[key];
1835
- }
1836
- });
1837
- }
1838
-
1839
- instances.push(instance);
1840
- } catch (error) {
1841
- console.error(`Failed to process SurrealDB instance ${base}:`, error);
1842
- }
1843
- }
1844
-
1845
- // Evaluate custom getters for all instances (single pass)
1846
- // This populates collection values needed for where.isInstance filtering
1847
- for (const instance of instances) {
1848
- await this.evaluateCustomGettersForInstance(instance, perspective, metadata);
1849
- }
1850
-
1851
- // Filter collections by where.isInstance if specified
1852
- // Do this after initial evaluation so collection values exist for filtering
1853
- for (const instance of instances) {
1854
- for (const [collName, collMeta] of Object.entries(metadata.collections)) {
1855
- if (collMeta.where?.isInstance && instance[collName]?.length > 0) {
1856
- try {
1857
- const targetClass = collMeta.where.isInstance;
1858
- const subjects = instance[collName];
1859
-
1860
- // Get the class metadata from SDNA to pass to batchCheckSubjectInstances
1861
- const targetClassName = typeof targetClass === 'string'
1862
- ? targetClass
1863
- : (targetClass as any).prototype?.className || targetClass.name;
1864
- const classMetadata = await perspective.getSubjectClassMetadataFromSDNA(targetClassName);
1865
-
1866
- if (!classMetadata) {
1867
- continue;
1868
- }
1869
-
1870
- // Check which subjects are instances of the target class
1871
- const validSubjects = await perspective.batchCheckSubjectInstances(subjects, classMetadata);
1872
-
1873
- // Update the collection with filtered instances
1874
- instance[collName] = validSubjects;
1875
- } catch (error) {
1876
- // On error, leave the collection unfiltered rather than breaking everything
1877
- }
1878
- }
1879
- }
1880
- }
1881
-
1882
- // Filter by where conditions that couldn't be filtered in SQL
1883
- // This includes:
1884
- // - author/timestamp (computed from grouped links)
1885
- // - Properties with comparison operators (gt, gte, lt, lte, between, contains)
1886
- // because fn::parse_literal() comparisons in SurrealDB subqueries don't work reliably
1887
- let filteredInstances = instances;
1888
- if (query.where) {
1889
- filteredInstances = instances.filter(instance => {
1890
- for (const [propertyName, condition] of Object.entries(query.where!)) {
1891
- // Skip 'base' as it's filtered in SQL
1892
- if (propertyName === 'base') continue;
1893
-
1894
- // For author and timestamp, always filter in JS
1895
- if (propertyName === 'author' || propertyName === 'timestamp') {
1896
- if (!this.matchesCondition(instance[propertyName], condition)) {
1897
- return false;
1898
- }
1899
- continue;
1900
- }
1901
-
1902
- // For regular properties, only filter comparison operators in JS
1903
- // Simple equality and NOT are handled in SQL, but gt/gte/lt/lte/between/contains need JS
1904
- if (typeof condition === 'object' && condition !== null && !Array.isArray(condition)) {
1905
- const ops = condition as any;
1906
- // Check if any comparison operators are present
1907
- const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
1908
- ops.lt !== undefined || ops.lte !== undefined ||
1909
- ops.between !== undefined || ops.contains !== undefined;
1910
- if (hasComparisonOps) {
1911
- if (!this.matchesCondition(instance[propertyName], condition)) {
1912
- return false;
1913
- }
1914
- }
1915
- }
1916
- }
1917
- return true;
1918
- });
1919
- }
1920
-
1921
- // Apply ordering in JavaScript
1922
- // If limit/offset is used but no explicit order, default to ordering by timestamp (ASC)
1923
- // This ensures consistent pagination behavior
1924
- const effectiveOrder = query.order ||
1925
- (query.limit !== undefined || query.offset !== undefined ? { timestamp: 'ASC' as 'ASC' } : null);
1926
-
1927
- if (effectiveOrder) {
1928
- const orderPropName = Object.keys(effectiveOrder)[0];
1929
- const orderDirection = Object.values(effectiveOrder)[0];
1930
-
1931
- filteredInstances.sort((a: any, b: any) => {
1932
- let aVal = a[orderPropName];
1933
- let bVal = b[orderPropName];
1934
-
1935
- // Handle undefined values - push them to the end
1936
- if (aVal === undefined && bVal === undefined) return 0;
1937
- if (aVal === undefined) return orderDirection === 'ASC' ? 1 : -1;
1938
- if (bVal === undefined) return orderDirection === 'ASC' ? -1 : 1;
1939
-
1940
- // Compare values
1941
- let comparison = 0;
1942
- if (typeof aVal === 'number' && typeof bVal === 'number') {
1943
- comparison = aVal - bVal;
1944
- } else if (typeof aVal === 'string' && typeof bVal === 'string') {
1945
- comparison = aVal.localeCompare(bVal);
1946
- } else {
1947
- // Convert to strings for comparison
1948
- comparison = String(aVal).localeCompare(String(bVal));
1949
- }
1950
-
1951
- return orderDirection === 'DESC' ? -comparison : comparison;
1952
- });
1953
- }
1954
-
1955
- // Calculate totalCount BEFORE applying limit/offset
1956
- const totalCount = filteredInstances.length;
1957
-
1958
- // Apply offset and limit in JavaScript
1959
- let paginatedInstances = filteredInstances;
1960
- if (query.offset !== undefined || query.limit !== undefined) {
1961
- const start = query.offset || 0;
1962
- const end = query.limit ? start + query.limit : undefined;
1963
- paginatedInstances = filteredInstances.slice(start, end);
1964
- }
1965
-
1966
- return {
1967
- results: paginatedInstances,
1968
- totalCount
1969
- };
1970
- }
1971
-
1972
- /**
1973
- * Checks if a value matches a condition (for post-query filtering).
1974
- * @private
1975
- */
1976
- private static matchesCondition(value: any, condition: WhereCondition): boolean {
1977
- // Handle array values (IN clause)
1978
- if (Array.isArray(condition)) {
1979
- return (condition as any[]).includes(value);
1980
- }
1981
-
1982
- // Handle operator object
1983
- if (typeof condition === 'object' && condition !== null) {
1984
- const ops = condition as any;
1985
-
1986
- // Special case: 'not' operator (exclusive with other operators)
1987
- if (ops.not !== undefined) {
1988
- if (Array.isArray(ops.not)) {
1989
- return !(ops.not as any[]).includes(value);
1990
- } else {
1991
- return value !== ops.not;
1992
- }
1993
- }
1994
-
1995
- // Special case: 'between' operator (inclusive range, exclusive with gt/gte/lt/lte)
1996
- if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
1997
- return value >= ops.between[0] && value <= ops.between[1];
1998
- }
1999
-
2000
- // For all other operators (gt, gte, lt, lte, contains), we need to check ALL of them
2001
- // and return true only if ALL conditions are satisfied
2002
- let allConditionsMet = true;
2003
-
2004
- if (ops.gt !== undefined) {
2005
- allConditionsMet = allConditionsMet && (value > ops.gt);
2006
- }
2007
-
2008
- if (ops.gte !== undefined) {
2009
- allConditionsMet = allConditionsMet && (value >= ops.gte);
2010
- }
2011
-
2012
- if (ops.lt !== undefined) {
2013
- allConditionsMet = allConditionsMet && (value < ops.lt);
2014
- }
2015
-
2016
- if (ops.lte !== undefined) {
2017
- allConditionsMet = allConditionsMet && (value <= ops.lte);
2018
- }
2019
-
2020
- if (ops.contains !== undefined) {
2021
- if (typeof value === 'string') {
2022
- allConditionsMet = allConditionsMet && value.includes(String(ops.contains));
2023
- } else if (Array.isArray(value)) {
2024
- allConditionsMet = allConditionsMet && value.includes(ops.contains);
2025
- } else {
2026
- allConditionsMet = false;
2027
- }
2028
- }
2029
-
2030
- return allConditionsMet;
2031
- }
2032
-
2033
- // Simple equality
2034
- return value === condition;
2035
- }
2036
-
2037
- /**
2038
- * Gets all instances of the model in the perspective that match the query params.
2039
- *
2040
- * @param perspective - The perspective to search in
2041
- * @param query - Optional query parameters to filter results
2042
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
2043
- * @returns Array of matching models
2044
- *
2045
- * @example
2046
- * ```typescript
2047
- * // Get all recipes (uses SurrealDB by default)
2048
- * const allRecipes = await Recipe.findAll(perspective);
2049
- *
2050
- * // Get recipes with specific criteria (uses SurrealDB)
2051
- * const recipes = await Recipe.findAll(perspective, {
2052
- * where: {
2053
- * name: "Pasta",
2054
- * rating: { gt: 4 }
2055
- * },
2056
- * order: { createdAt: "DESC" },
2057
- * limit: 10
2058
- * });
2059
- *
2060
- * // Explicitly use Prolog (legacy, for backward compatibility)
2061
- * const recipesProlog = await Recipe.findAll(perspective, {}, false);
2062
- * ```
2063
- */
2064
- static async findAll<T extends Ad4mModel>(
2065
- this: typeof Ad4mModel & (new (...args: any[]) => T),
2066
- perspective: PerspectiveProxy,
2067
- query: Query = {},
2068
- useSurrealDB: boolean = true
2069
- ): Promise<T[]> {
2070
- if (useSurrealDB) {
2071
- const surrealQuery = await this.queryToSurrealQL(perspective, query);
2072
- const result = await perspective.querySurrealDB(surrealQuery);
2073
- const { results } = await this.instancesFromSurrealResult(perspective, query, result);
2074
- return results;
2075
- } else {
2076
- const prologQuery = await this.queryToProlog(perspective, query);
2077
- const result = await perspective.infer(prologQuery);
2078
- const { results } = await this.instancesFromPrologResult(perspective, query, result);
2079
- return results;
2080
- }
2081
- }
2082
-
2083
- /**
2084
- * Gets all instances with count of total matches without offset & limit applied.
2085
- *
2086
- * @param perspective - The perspective to search in
2087
- * @param query - Optional query parameters to filter results
2088
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
2089
- * @returns Object containing results array and total count
2090
- *
2091
- * @example
2092
- * ```typescript
2093
- * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {
2094
- * where: { category: "Dessert" },
2095
- * limit: 10
2096
- * });
2097
- * console.log(`Showing 10 of ${totalCount} dessert recipes`);
2098
- *
2099
- * // Use Prolog explicitly (legacy)
2100
- * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
2101
- * ```
2102
- */
2103
- static async findAllAndCount<T extends Ad4mModel>(
2104
- this: typeof Ad4mModel & (new (...args: any[]) => T),
2105
- perspective: PerspectiveProxy,
2106
- query: Query = {},
2107
- useSurrealDB: boolean = true
2108
- ): Promise<ResultsWithTotalCount<T>> {
2109
- if (useSurrealDB) {
2110
- const surrealQuery = await this.queryToSurrealQL(perspective, query);
2111
- const result = await perspective.querySurrealDB(surrealQuery);
2112
- return await this.instancesFromSurrealResult(perspective, query, result);
2113
- } else {
2114
- const prologQuery = await this.queryToProlog(perspective, query);
2115
- const result = await perspective.infer(prologQuery);
2116
- return await this.instancesFromPrologResult(perspective, query, result);
2117
- }
2118
- }
2119
-
2120
- /**
2121
- * Helper function for pagination with explicit page size and number.
2122
- *
2123
- * @param perspective - The perspective to search in
2124
- * @param pageSize - Number of items per page
2125
- * @param pageNumber - Which page to retrieve (1-based)
2126
- * @param query - Optional additional query parameters
2127
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
2128
- * @returns Paginated results with metadata
2129
- *
2130
- * @example
2131
- * ```typescript
2132
- * const page = await Recipe.paginate(perspective, 10, 1, {
2133
- * where: { category: "Main Course" }
2134
- * });
2135
- * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
2136
- *
2137
- * // Use Prolog explicitly (legacy)
2138
- * const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
2139
- * ```
2140
- */
2141
- static async paginate<T extends Ad4mModel>(
2142
- this: typeof Ad4mModel & (new (...args: any[]) => T),
2143
- perspective: PerspectiveProxy,
2144
- pageSize: number,
2145
- pageNumber: number,
2146
- query?: Query,
2147
- useSurrealDB: boolean = true
2148
- ): Promise<PaginationResult<T>> {
2149
- const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
2150
- if (useSurrealDB) {
2151
- const surrealQuery = await this.queryToSurrealQL(perspective, paginationQuery);
2152
- const result = await perspective.querySurrealDB(surrealQuery);
2153
- const { results, totalCount } = await this.instancesFromSurrealResult(perspective, paginationQuery, result);
2154
- return { results, totalCount, pageSize, pageNumber };
2155
- } else {
2156
- const prologQuery = await this.queryToProlog(perspective, paginationQuery);
2157
- const result = await perspective.infer(prologQuery);
2158
- const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
2159
- return { results, totalCount, pageSize, pageNumber };
2160
- }
2161
- }
2162
-
2163
- static async countQueryToProlog(perspective: PerspectiveProxy, query: Query = {}, modelClassName?: string | null) {
2164
- const { source, where } = query;
2165
- const className = modelClassName || (await this.getClassName(perspective));
2166
- const instanceQueries = [buildAuthorAndTimestampQuery(), buildSourceQuery(source), buildWhereQuery(where)];
2167
- const resultSetQueries = [buildCountQuery(true), buildOrderQuery(), buildOffsetQuery(), buildLimitQuery()];
2168
-
2169
- const fullQuery = `
2170
- findall([Base, Properties, Collections, Timestamp, Author], (
2171
- subject_class("${className}", SubjectClass),
2172
- instance(SubjectClass, Base),
2173
- ${instanceQueries.filter((q) => q).join(", ")}
2174
- ), UnsortedInstances),
2175
- ${resultSetQueries.filter((q) => q).join(", ")}
2176
- `;
2177
-
2178
- return fullQuery;
2179
- }
2180
-
2181
- /**
2182
- * Generates a SurrealQL COUNT query for the model.
2183
- *
2184
- * @param perspective - The perspective context
2185
- * @param query - Query parameters to filter the count
2186
- * @returns SurrealQL COUNT query string
2187
- *
2188
- * @private
2189
- */
2190
- public static async countQueryToSurrealQL(perspective: PerspectiveProxy, query: Query): Promise<string> {
2191
- // Use the same query as the main query (with GROUP BY), just without LIMIT/OFFSET
2192
- // We'll count the number of rows returned (one row per source)
2193
- const countQuery = { ...query };
2194
- delete countQuery.limit;
2195
- delete countQuery.offset;
2196
- return await this.queryToSurrealQL(perspective, countQuery);
2197
- }
2198
-
2199
- /**
2200
- * Gets a count of all matching instances.
2201
- *
2202
- * @param perspective - The perspective to search in
2203
- * @param query - Optional query parameters to filter results
2204
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
2205
- * @returns Total count of matching entities
2206
- *
2207
- * @example
2208
- * ```typescript
2209
- * const totalRecipes = await Recipe.count(perspective);
2210
- * const activeRecipes = await Recipe.count(perspective, {
2211
- * where: { status: "active" }
2212
- * });
2213
- *
2214
- * // Use Prolog explicitly (legacy)
2215
- * const countProlog = await Recipe.count(perspective, {}, false);
2216
- * ```
2217
- */
2218
- static async count(perspective: PerspectiveProxy, query: Query = {}, useSurrealDB: boolean = true) {
2219
- if (useSurrealDB) {
2220
- const surrealQuery = await this.queryToSurrealQL(perspective, query);
2221
- const result = await perspective.querySurrealDB(surrealQuery);
2222
- // Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
2223
- // (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
2224
- // This ensures count() returns the same number as findAll().length
2225
- const { totalCount } = await this.instancesFromSurrealResult(perspective, query, result);
2226
- return totalCount;
2227
- } else {
2228
- const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
2229
- return result?.[0]?.TotalCount || 0;
2230
- }
2231
- }
2232
-
2233
- private async setProperty(key: string, value: any, batchId?: string) {
2234
- // Phase 1: Use metadata instead of Prolog queries
2235
- const metadata = this.getPropertyMetadata(key);
2236
- if (!metadata) {
2237
- console.warn(`Property "${key}" has no metadata, skipping`);
2238
- return;
2239
- }
2240
-
2241
- // Generate actions from metadata (replaces Prolog query)
2242
- const actions = this.generatePropertySetterAction(key, metadata);
2243
-
2244
- // Get resolve language from metadata (replaces Prolog query)
2245
- let resolveLanguage = metadata.resolveLanguage;
2246
-
2247
- // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal://string:)
2248
- if (value === undefined || value === null || value === "") {
2249
- return;
2250
- }
2251
-
2252
- if (resolveLanguage) {
2253
- value = await this.#perspective.createExpression(value, resolveLanguage);
2254
- }
2255
-
2256
- await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }], batchId);
2257
- }
2258
-
2259
- private async setCollectionSetter(key: string, value: any, batchId?: string) {
2260
- // Phase 1: Use metadata instead of Prolog queries
2261
- const metadata = this.getCollectionMetadata(key);
2262
- if (!metadata) {
2263
- console.warn(`Collection "${key}" has no metadata, skipping`);
2264
- return;
2265
- }
2266
-
2267
- // Generate actions from metadata (replaces Prolog query)
2268
- const actions = this.generateCollectionAction(key, 'setter');
2269
-
2270
- if (value != null) {
2271
- if (Array.isArray(value)) {
2272
- await this.#perspective.executeAction(
2273
- actions,
2274
- this.#baseExpression,
2275
- value.map((v) => ({ name: "value", value: v })),
2276
- batchId
2277
- );
2278
- } else {
2279
- await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }], batchId);
2280
- }
2281
- }
2282
- }
2283
-
2284
- private async setCollectionAdder(key: string, value: any, batchId?: string) {
2285
- // Phase 1: Use metadata instead of Prolog queries
2286
- const metadata = this.getCollectionMetadata(key);
2287
- if (!metadata) {
2288
- console.warn(`Collection "${key}" has no metadata, skipping`);
2289
- return;
2290
- }
2291
-
2292
- // Generate actions from metadata (replaces Prolog query)
2293
- const actions = this.generateCollectionAction(key, 'adder');
2294
-
2295
- if (value != null) {
2296
- if (Array.isArray(value)) {
2297
- await Promise.all(
2298
- value.map((v) =>
2299
- this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value: v }], batchId)
2300
- )
2301
- );
2302
- } else {
2303
- await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }], batchId);
2304
- }
2305
- }
2306
- }
2307
-
2308
- private async setCollectionRemover(key: string, value: any, batchId?: string) {
2309
- // Phase 1: Use metadata instead of Prolog queries
2310
- const metadata = this.getCollectionMetadata(key);
2311
- if (!metadata) {
2312
- console.warn(`Collection "${key}" has no metadata, skipping`);
2313
- return;
2314
- }
2315
-
2316
- // Generate actions from metadata (replaces Prolog query)
2317
- const actions = this.generateCollectionAction(key, 'remover');
2318
-
2319
- if (value != null) {
2320
- if (Array.isArray(value)) {
2321
- await Promise.all(
2322
- value.map((v) =>
2323
- this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value: v }], batchId)
2324
- )
2325
- );
2326
- } else {
2327
- await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }], batchId);
2328
- }
2329
- }
2330
- }
2331
-
44
+ export type ParentOptions = {
45
+ /** The parent model class (must have a `@HasMany` pointing to this child type). */
46
+ model: typeof Ad4mModel;
47
+ /** The ID of the parent instance. */
48
+ id: string;
2332
49
  /**
2333
- * Saves the model instance to the perspective.
2334
- * Creates a new instance with the base expression and links it to the source.
2335
- *
2336
- * @param batchId - Optional batch ID for batch operations
2337
- * @throws Will throw if instance creation, linking, or updating fails
2338
- *
2339
- * @example
2340
- * ```typescript
2341
- * const recipe = new Recipe(perspective);
2342
- * recipe.name = "Spaghetti";
2343
- * recipe.ingredients = ["pasta", "tomato sauce"];
2344
- * await recipe.save();
2345
- *
2346
- * // Or with batch operations:
2347
- * const batchId = await perspective.createBatch();
2348
- * await recipe.save(batchId);
2349
- * await perspective.commitBatch(batchId);
2350
- * ```
50
+ * The `@HasMany` field on the parent whose predicate is used for the link.
51
+ * Optional when exactly one `@HasMany` on the parent points to this child type.
2351
52
  */
2352
- async save(batchId?: string) {
2353
- // We use createSubject's initialValues to set properties (but not collections)
2354
- // We then later use innerUpdate to set collections
2355
-
2356
- let batchCreatedHere = false;
2357
- if(!batchId) {
2358
- batchId = await this.perspective.createBatch()
2359
- batchCreatedHere = true;
2360
- }
2361
-
2362
-
2363
- // First filter out the properties that are not collections (arrays)
2364
- const initialValues = {};
2365
- for (const [key, value] of Object.entries(this)) {
2366
- if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {
2367
- initialValues[key] = value;
2368
- }
2369
- }
2370
-
2371
- // Get the class name instead of passing the instance to avoid Prolog query generation
2372
- const className = await this.perspective.stringOrTemplateObjectToSubjectClassName(this);
2373
-
2374
- // Create the subject with the initial values
2375
- await this.perspective.createSubject(
2376
- className,
2377
- this.#baseExpression,
2378
- initialValues,
2379
- batchId
2380
- );
53
+ field?: string;
54
+ };
55
+ import type {
56
+ Query,
57
+ ResultsWithTotalCount,
58
+ PaginationResult,
59
+ ModelMetadata,
60
+ IncludeMap,
61
+ SubscribeOptions,
62
+ Subscription,
63
+ } from "./types";
64
+
65
+ // ── JSON Schema factory ────────────────────────────────────────────────────
66
+ import { createModelFromJSONSchema } from "./schema/fromJSONSchema";
67
+ import type {
68
+ JSONSchema,
69
+ JSONSchemaToModelOptions,
70
+ } from "./schema/fromJSONSchema";
71
+ export type {
72
+ JSONSchema,
73
+ JSONSchemaToModelOptions,
74
+ JSONSchemaProperty, // keep re-exporting for external consumers
75
+ } from "./schema/fromJSONSchema";
76
+
77
+ // ── Fluent query builder (re-exported for consumers) ──────────────────────
78
+ import { ModelQueryBuilder } from "./query/ModelQueryBuilder";
79
+ export { ModelQueryBuilder };
80
+
81
+ // ── SurrealDB query helpers (used internally, also re-exported) ────────────
82
+ export {
83
+ buildSurrealQuery,
84
+ buildSurrealCountQuery,
85
+ formatSurrealValue,
86
+ matchesCondition,
87
+ buildGraphTraversalWhereClause,
88
+ } from "./query/surrealCompiler";
89
+
90
+ // ── Hydration utilities (re-exported for advanced consumers) ──────────────
91
+ export {
92
+ hydrateInstanceFromLinks,
93
+ evaluateCustomGetters,
94
+ normalizeTimestamp,
95
+ } from "./query/hydration";
96
+ export type { RawLink } from "./query/hydration";
97
+
98
+ // ── Static query operations (each static method below delegates here) ─────────
99
+ import * as ops from "./query/operations";
100
+ import { fetchInstanceData } from "./query/fetchInstance";
101
+
102
+ // ── Metadata helpers ────────────────────────────────────────────────────────
103
+ import { getModelMetadata as _getModelMetadata } from "./schema/metadata";
104
+
105
+ // ── Transaction API ──────────────────────────────────────────────────────────
106
+ import { runTransaction } from "./transaction";
107
+ export type { TransactionContext } from "./transaction";
108
+ // ── Subscription API ───────────────────────────────────────────────────────────────
109
+ import { createSubscription } from "./subscription";
110
+ /**
111
+ * Base class for all AD4M data models.
112
+ *
113
+ * Instances are subgraphs in a {@link PerspectiveProxy}; properties and relations
114
+ * map to typed links. Decorators (`@Property`, `@HasMany`, etc.) declare the schema;
115
+ * query helpers (`findAll`, `query`, `subscribe`) run SurrealQL against the
116
+ * perspective's local graph engine.
117
+ *
118
+ * See [README.md](./README.md) for a full worked example and decorator reference.
119
+ */
120
+ export class Ad4mModel {
121
+ // NOTE: Using TypeScript `private` (not JS `#`) so these properties work through Vue reactive Proxies.
122
+ private _id: string;
123
+ private _perspective: PerspectiveProxy;
124
+ /** Tracks whether save() has ever been called on this instance (even in an uncommitted batch). */
125
+ private _savedOnce: boolean = false;
126
+ author: string;
127
+ createdAt: any;
128
+ updatedAt: any;
2381
129
 
2382
- // Link the subject to the source
2383
- await this.#perspective.add(
2384
- new Link({ source: this.#source, predicate: "ad4m://has_child", target: this.baseExpression }),
2385
- 'shared',
2386
- batchId
2387
- );
130
+ private static classNamesByClass = new WeakMap<
131
+ typeof Ad4mModel,
132
+ { [perspectiveId: string]: string }
133
+ >();
2388
134
 
2389
- // Set collections
2390
- await this.innerUpdate(false, batchId)
135
+ static async getClassName(perspective: PerspectiveProxy) {
136
+ // Check if this is the Ad4mModel class itself or a subclass
137
+ const isBaseClass = this === Ad4mModel;
2391
138
 
2392
- // If we got a batchId passed in, we let the caller decide when to commit.
2393
- // But then we can call getData() since the instance won't exist in the perspective
2394
- // until the bacht is committedl
2395
- if (batchCreatedHere) {
2396
- await this.perspective.commitBatch(batchId)
2397
- await this.getData();
139
+ // For the base Ad4mModel class, we can't use the cache
140
+ if (isBaseClass) {
141
+ return await perspective.stringOrTemplateObjectToSubjectClassName(this);
2398
142
  }
2399
- }
2400
143
 
2401
- private cleanCopy() {
2402
- const cleanCopy = {};
2403
- const props = Object.entries(this);
2404
- for (const [key, value] of props) {
2405
- if (value !== undefined && value !== null && key !== "author" && key !== "timestamp") {
2406
- cleanCopy[key] = value;
2407
- }
144
+ // Get or create the cache for this class
145
+ let classCache = this.classNamesByClass.get(this);
146
+ if (!classCache) {
147
+ classCache = {};
148
+ this.classNamesByClass.set(this, classCache);
2408
149
  }
2409
- return cleanCopy;
2410
- }
2411
-
2412
- private async innerUpdate(setProperties: boolean = true, batchId?: string) {
2413
- this.#subjectClassName = await this.#perspective.stringOrTemplateObjectToSubjectClassName(this.cleanCopy());
2414
150
 
2415
- const entries = Object.entries(this);
2416
- for (const [key, value] of entries) {
2417
- if (value !== undefined && value !== null) {
2418
- if (value?.action) {
2419
- switch (value.action) {
2420
- case "setter":
2421
- await this.setCollectionSetter(key, value.value, batchId);
2422
- break;
2423
- case "adder":
2424
- await this.setCollectionAdder(key, value.value, batchId);
2425
- break;
2426
- case "remover":
2427
- await this.setCollectionRemover(key, value.value, batchId);
2428
- break;
2429
- default:
2430
- await this.setCollectionSetter(key, value.value, batchId);
2431
- break;
2432
- }
2433
- } else if (Array.isArray(value)) {
2434
- // Handle all arrays as collections, including empty ones (which clears the collection)
2435
- await this.setCollectionSetter(key, value, batchId);
2436
- } else if (value !== undefined && value !== null && value !== "") {
2437
- if (setProperties) {
2438
- // Check if this is a collection property (has collection metadata)
2439
- const collMetadata = this.getCollectionMetadata(key);
2440
- if (collMetadata) {
2441
- // Skip - it's a collection, not a regular property
2442
- continue;
2443
- }
2444
- await this.setProperty(key, value, batchId);
2445
- }
2446
- }
2447
- }
151
+ // Get or create the cached name for this perspective
152
+ const perspectiveID = perspective.uuid;
153
+ if (!classCache[perspectiveID]) {
154
+ classCache[perspectiveID] =
155
+ await perspective.stringOrTemplateObjectToSubjectClassName(this);
2448
156
  }
157
+
158
+ return classCache[perspectiveID];
2449
159
  }
2450
160
 
2451
161
  /**
2452
- * Updates the model instance's properties and collections.
2453
- *
2454
- * @param batchId - Optional batch ID for batch operations
2455
- * @throws Will throw if property setting or collection updates fail
2456
- *
2457
- * @example
2458
- * ```typescript
2459
- * const recipe = await Recipe.findAll(perspective)[0];
2460
- * recipe.rating = 5;
2461
- * recipe.ingredients.push("garlic");
2462
- * await recipe.update();
2463
- *
2464
- * // Or with batch operations:
2465
- * const batchId = await perspective.createBatch();
2466
- * await recipe.update(batchId);
2467
- * await perspective.commitBatch(batchId);
2468
- * ```
162
+ * Backwards compatibility alias for createdAt.
163
+ * @deprecated Use createdAt instead. This will be removed in a future version.
2469
164
  */
2470
- async update(batchId?: string) {
2471
- await this.innerUpdate(true, batchId);
2472
- await this.getData();
165
+ get timestamp(): any {
166
+ return (this as any).createdAt;
167
+ }
168
+
169
+ /** Returns the class name, property predicates, and relation predicates from decorators. */
170
+ public static getModelMetadata(): ModelMetadata {
171
+ return _getModelMetadata(this);
2473
172
  }
2474
173
 
2475
174
  /**
2476
- * Gets the model instance with all properties and collections populated.
2477
- *
2478
- * @returns The populated model instance
2479
- * @throws Will throw if data retrieval fails
2480
- *
2481
- * @example
2482
- * ```typescript
2483
- * const recipe = new Recipe(perspective, existingId);
2484
- * await recipe.get();
2485
- * console.log(recipe.name, recipe.ingredients);
2486
- * ```
175
+ * Installs the SHACL/SDNA subject class in `perspective` (idempotent).
176
+ *
177
+ * @example `await Promise.all([Post, Comment, Tag].map(M => M.register(perspective)));`
2487
178
  */
2488
- async get() {
2489
- this.#subjectClassName = await this.#perspective.stringOrTemplateObjectToSubjectClassName(this.cleanCopy());
2490
-
2491
- return await this.getData();
179
+ static async register(perspective: PerspectiveProxy): Promise<void> {
180
+ await perspective.ensureSDNASubjectClass(this);
2492
181
  }
2493
182
 
2494
183
  /**
2495
- * Deletes the model instance from the perspective.
2496
- *
2497
- * @param batchId - Optional batch ID for batch operations
2498
- * @throws Will throw if removal fails
2499
- *
184
+ * One-shot factory: constructs, assigns `data`, saves, and returns the new instance.
185
+ *
2500
186
  * @example
2501
187
  * ```typescript
2502
- * const recipe = await Recipe.findAll(perspective)[0];
2503
- * await recipe.delete();
2504
- *
2505
- * // Or with batch operations:
2506
- * const batchId = await perspective.createBatch();
2507
- * await recipe.delete(batchId);
2508
- * await perspective.commitBatch(batchId);
188
+ * const post = await Post.create(perspective, { title: 'Hello', body: 'World' });
2509
189
  * ```
2510
190
  */
2511
- async delete(batchId?: string) {
2512
- await this.#perspective.removeSubject(this, this.#baseExpression, batchId);
191
+ static async create<T extends Ad4mModel>(
192
+ this: new (perspective: PerspectiveProxy) => T,
193
+ perspective: PerspectiveProxy,
194
+ data: Partial<Omit<T, keyof Ad4mModel>>,
195
+ options?: { parent?: ParentOptions; batchId?: string },
196
+ ): Promise<T> {
197
+ const instance = new this(perspective);
198
+ Object.assign(instance, data);
199
+ await instance.save(options?.batchId);
200
+ if (options?.parent) {
201
+ const { model, id, field } = options.parent;
202
+ const predicate = resolveParentPredicate(
203
+ model.getModelMetadata(),
204
+ this as unknown as new (...args: any[]) => any,
205
+ field,
206
+ );
207
+ await perspective.addLinks(
208
+ [new Link({ source: id, predicate, target: instance.id })],
209
+ "shared",
210
+ options?.batchId,
211
+ );
212
+ }
213
+ return instance;
2513
214
  }
2514
215
 
2515
216
  /**
2516
- * Creates a query builder for fluent query construction.
2517
- *
2518
- * @param perspective - The perspective to query
2519
- * @param query - Optional initial query parameters
2520
- * @returns A new query builder instance
2521
- *
2522
- * @example
217
+ * Fetches the instance, merges `data` into it, then saves.
218
+ *
219
+ * This is a convenience alternative to the three-step pattern:
2523
220
  * ```typescript
2524
- * const recipes = await Recipe.query(perspective)
2525
- * .where({ category: "Dessert" })
2526
- * .order({ rating: "DESC" })
2527
- * .limit(5)
2528
- * .run();
2529
- *
2530
- * // With real-time updates
2531
- * await Recipe.query(perspective)
2532
- * .where({ status: "cooking" })
2533
- * .subscribe(recipes => {
2534
- * console.log("Currently cooking:", recipes);
2535
- * });
221
+ * // Before
222
+ * const instance = new Vote(perspective, id);
223
+ * instance.score = newScore;
224
+ * await instance.save();
225
+ *
226
+ * // After
227
+ * await Vote.update(perspective, id, { score: newScore });
2536
228
  * ```
229
+ *
230
+ * @param data - Partial set of properties to merge into the stored instance.
231
+ * @param batchId - Optional batch identifier for grouping writes.
232
+ * @returns The updated instance with all fields populated.
2537
233
  */
2538
- static query<T extends Ad4mModel>(
2539
- this: typeof Ad4mModel & (new (...args: any[]) => T),
2540
- perspective: PerspectiveProxy,
2541
- query?: Query
2542
- ): ModelQueryBuilder<T> {
2543
- return new ModelQueryBuilder<T>(perspective, this as any, query);
234
+ static async update<T extends Ad4mModel>(
235
+ this: (new (perspective: PerspectiveProxy, id: string) => T) &
236
+ typeof Ad4mModel,
237
+ perspective: PerspectiveProxy,
238
+ id: string,
239
+ data: Partial<Omit<T, keyof Ad4mModel>>,
240
+ batchId?: string,
241
+ ): Promise<T> {
242
+ const instance = new this(perspective, id);
243
+ await instance.get();
244
+ Object.assign(instance, data);
245
+ await instance.save(batchId);
246
+ return instance;
2544
247
  }
2545
248
 
2546
249
  /**
2547
- * Creates an Ad4mModel class from a JSON Schema definition.
2548
- *
2549
- * @description
2550
- * This method dynamically generates an Ad4mModel subclass from a JSON Schema,
2551
- * enabling integration with systems that use JSON Schema for type definitions.
2552
- *
2553
- * The method follows a cascading approach for determining predicates:
2554
- * 1. Explicit configuration in options parameter (highest precedence)
2555
- * 2. x-ad4m metadata in the JSON Schema
2556
- * 3. Inference from schema title and property names
2557
- * 4. Error if no namespace can be determined
2558
- *
2559
- * @example
250
+ * Deletes the instance with the given `id` from the perspective.
251
+ *
252
+ * This is a convenience alternative to:
2560
253
  * ```typescript
2561
- * // With explicit configuration
2562
- * const PersonClass = Ad4mModel.fromJSONSchema(schema, {
2563
- * name: "Person",
2564
- * namespace: "person://",
2565
- * resolveLanguage: "literal"
2566
- * });
2567
- *
2568
- * // With property mapping
2569
- * const ContactClass = Ad4mModel.fromJSONSchema(schema, {
2570
- * name: "Contact",
2571
- * namespace: "contact://",
2572
- * propertyMapping: {
2573
- * "name": "foaf://name",
2574
- * "email": "foaf://mbox"
2575
- * }
2576
- * });
2577
- *
2578
- * // With x-ad4m metadata in schema
2579
- * const schema = {
2580
- * "title": "Product",
2581
- * "x-ad4m": { "namespace": "product://" },
2582
- * "properties": {
2583
- * "name": {
2584
- * "type": "string",
2585
- * "x-ad4m": { "through": "product://title" }
2586
- * }
2587
- * }
2588
- * };
2589
- * const ProductClass = Ad4mModel.fromJSONSchema(schema, { name: "Product" });
254
+ * // Before
255
+ * const instance = new Poll(perspective, id);
256
+ * await instance.delete();
257
+ *
258
+ * // After
259
+ * await Poll.delete(perspective, id);
2590
260
  * ```
2591
- *
2592
- * @param schema - JSON Schema definition
2593
- * @param options - Configuration options
2594
- * @returns Generated Ad4mModel subclass
2595
- * @throws Error when namespace cannot be inferred
261
+ *
262
+ * @param batchId - Optional batch identifier for grouping removals.
2596
263
  */
2597
- static fromJSONSchema(
2598
- schema: JSONSchema,
2599
- options: JSONSchemaToModelOptions
2600
- ): typeof Ad4mModel {
2601
- // Disallow top-level "author" property since Ad4mModel provides it implicitly via link authorship
2602
- if (schema?.properties && Object.prototype.hasOwnProperty.call(schema.properties, "author")) {
2603
- throw new Error('JSON Schema must not define a top-level "author" property because Ad4mModel already exposes it. Please rename the property (e.g., "writer").');
2604
- }
2605
- // Determine namespace with cascading precedence
2606
- const namespace = this.determineNamespace(schema, options);
2607
-
2608
- // Create the dynamic class
2609
- const DynamicModelClass = class extends Ad4mModel {};
2610
-
2611
- // Set up class metadata
2612
- if (!options.name || options.name.trim() === '') {
2613
- throw new Error("options.name is required and cannot be empty");
2614
- }
2615
- (DynamicModelClass as any).className = options.name;
2616
- (DynamicModelClass.prototype as any).className = options.name;
2617
-
2618
- // Generate properties and collections metadata
2619
- const properties: any = {};
2620
- const collections: any = {};
2621
-
2622
- if (schema.properties) {
2623
- for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
2624
- const predicate = this.determinePredicate(schema, propertyName, propertySchema, namespace, options);
2625
- const isRequired = schema.required?.includes(propertyName) || false;
2626
- const propertyType = normalizeSchemaType(propertySchema.type);
2627
- const isArray = isArrayType(propertySchema);
2628
-
2629
- if (isArray) {
2630
- // Handle arrays as collections
2631
- // Store the singular form as the collection key since SDNA generation expects singular
2632
- collections[propertyName] = {
2633
- through: predicate,
2634
- local: this.getPropertyOption(propertyName, propertySchema, options, 'local')
2635
- };
2636
-
2637
- // Define the property on prototype
2638
- Object.defineProperty(DynamicModelClass.prototype, propertyName, {
2639
- configurable: true,
2640
- writable: true,
2641
- value: []
2642
- });
2643
-
2644
- // Add collection methods
2645
- const adderName = `add${capitalize(propertyName)}`;
2646
- const removerName = `remove${capitalize(propertyName)}`;
2647
- const setterName = `setCollection${capitalize(propertyName)}`;
2648
-
2649
- (DynamicModelClass.prototype as any)[adderName] = function() {
2650
- // Placeholder function for SDNA generation
2651
- };
2652
- (DynamicModelClass.prototype as any)[removerName] = function() {
2653
- // Placeholder function for SDNA generation
2654
- };
2655
- (DynamicModelClass.prototype as any)[setterName] = function() {
2656
- // Placeholder function for SDNA generation
2657
- };
2658
-
2659
- } else {
2660
- // Handle regular properties
2661
- let resolveLanguage = this.getPropertyOption(propertyName, propertySchema, options, 'resolveLanguage');
2662
- // If no specific resolveLanguage for this property, use the global one
2663
- if (!resolveLanguage && options.resolveLanguage) {
2664
- resolveLanguage = options.resolveLanguage;
2665
- }
2666
- const local = this.getPropertyOption(propertyName, propertySchema, options, 'local');
2667
- const writable = this.getPropertyOption(propertyName, propertySchema, options, 'writable', true);
2668
- let initial = this.getPropertyOption(propertyName, propertySchema, options, 'initial');
2669
-
2670
- // Handle nested objects by serializing to JSON
2671
- if (isObjectType(propertySchema) && !resolveLanguage) {
2672
- resolveLanguage = 'literal';
2673
- console.warn(`Property "${propertyName}" is an object type. It will be stored as JSON. Consider flattening complex objects for better semantic querying.`);
2674
- }
2675
-
2676
- // Ensure numeric properties use literal language for correct typing
2677
- if ((resolveLanguage === undefined || resolveLanguage === null) && isNumericType(propertySchema)) {
2678
- resolveLanguage = 'literal';
2679
- }
2680
-
2681
- // If property is required, ensure it has an initial value
2682
- if (isRequired && !initial) {
2683
- if (isObjectType(propertySchema)) {
2684
- initial = 'literal://json:{}';
2685
- } else {
2686
- initial = "ad4m://undefined";
2687
- }
2688
- }
2689
-
2690
- properties[propertyName] = {
2691
- through: predicate,
2692
- required: isRequired,
2693
- writable: writable,
2694
- ...(resolveLanguage && { resolveLanguage }),
2695
- ...(local !== undefined && { local }),
2696
- ...(initial && { initial })
2697
- };
2698
-
2699
- // Define the property on prototype
2700
- Object.defineProperty(DynamicModelClass.prototype, propertyName, {
2701
- configurable: true,
2702
- writable: true,
2703
- value: this.getDefaultValueForType(propertyType)
2704
- });
2705
-
2706
- // Add setter function if writable
2707
- if (writable) {
2708
- const setterName = propertyNameToSetterName(propertyName);
2709
- (DynamicModelClass.prototype as any)[setterName] = function() {
2710
- // This is a placeholder function that the SDNA generation looks for
2711
- // The actual setter logic is handled by the Ad4mModel base class
2712
- };
2713
- }
2714
- }
2715
- }
2716
- }
2717
-
2718
- // Validate that at least one property has an initial value (needed for valid SDNA constructor)
2719
- // Collections don't create constructor actions, only properties with initial values do
2720
- const hasPropertyWithInitial = Object.values(properties).some((prop: any) => prop.initial);
2721
-
2722
- if (!hasPropertyWithInitial) {
2723
- // If no properties have initial values, add a type identifier automatically
2724
- const typeProperty = `ad4m://type`;
2725
- let typeValue: string;
2726
- if (namespace.includes('://')) {
2727
- const [scheme, rest] = namespace.split('://');
2728
- const path = (rest || '').replace(/\/+$/,'');
2729
- if (path) {
2730
- typeValue = `${scheme}://${path}/instance`;
2731
- } else {
2732
- typeValue = `${scheme}://instance`;
2733
- }
2734
- } else {
2735
- const path = namespace.replace(/\/+$/,'');
2736
- typeValue = `${path}/instance`;
2737
- }
2738
-
2739
- properties['__ad4m_type'] = {
2740
- through: typeProperty,
2741
- required: true,
2742
- writable: false,
2743
- initial: typeValue,
2744
- flag: true
2745
- };
2746
-
2747
- // Add the type property to the prototype
2748
- Object.defineProperty(DynamicModelClass.prototype, '__ad4m_type', {
2749
- configurable: true,
2750
- writable: false,
2751
- value: typeValue
2752
- });
2753
-
2754
- console.warn(`No properties with initial values found. Added automatic type flag: ${typeProperty} = ${typeValue}`);
2755
- }
2756
-
2757
- // Attach metadata to prototype
2758
- (DynamicModelClass.prototype as any).__properties = properties;
2759
- (DynamicModelClass.prototype as any).__collections = collections;
2760
-
2761
- // Store the JSON schema and options on the prototype for potential fallback use by getModelMetadata()
2762
- (DynamicModelClass.prototype as any).__jsonSchema = schema;
2763
- (DynamicModelClass.prototype as any).__jsonSchemaOptions = options;
2764
-
2765
- // Apply the ModelOptions decorator to set up the generateSDNA method
2766
- const ModelOptionsDecorator = ModelOptions({ name: options.name });
2767
- ModelOptionsDecorator(DynamicModelClass);
2768
-
2769
- return DynamicModelClass as typeof Ad4mModel;
264
+ static async delete(
265
+ perspective: PerspectiveProxy,
266
+ id: string,
267
+ batchId?: string,
268
+ ): Promise<void> {
269
+ const instance = new this(perspective, id);
270
+ await instance.delete(batchId);
2770
271
  }
2771
-
272
+
2772
273
  /**
2773
- * Determines the namespace for predicates using cascading precedence
274
+ * Generates the SHACL shape for this model class.
275
+ * Attached dynamically by the `@Model` decorator.
2774
276
  */
2775
- private static determineNamespace(schema: JSONSchema, options: JSONSchemaToModelOptions): string {
2776
- // 1. Explicit namespace in options (highest precedence)
2777
- if (options.namespace) {
2778
- return options.namespace;
2779
- }
2780
-
2781
- // 2. x-ad4m metadata in schema
2782
- if (schema["x-ad4m"]?.namespace) {
2783
- return schema["x-ad4m"].namespace;
2784
- }
2785
-
2786
- // 3. Infer from schema title
2787
- if (schema.title) {
2788
- return `${schema.title.toLowerCase()}://`;
2789
- }
2790
-
2791
- // 4. Try to extract from $id if it's a URL
2792
- if (schema.$id) {
2793
- try {
2794
- const url = new URL(schema.$id);
2795
- const pathParts = url.pathname.split('/').filter(p => p);
2796
- if (pathParts.length > 0) {
2797
- const lastPart = pathParts[pathParts.length - 1];
2798
- const baseName = lastPart.replace(/\.schema\.json$/, '').replace(/\.json$/, '');
2799
- return `${baseName.toLowerCase()}://`;
2800
- }
2801
- } catch {
2802
- // If $id is not a valid URL, continue to error
2803
- }
2804
- }
2805
-
2806
- // 5. Error if no namespace can be determined
277
+ static generateSHACL(): { shape: SHACLShape; name: string } {
2807
278
  throw new Error(
2808
- `Cannot infer namespace for JSON Schema. Please provide one of:
2809
- - options.namespace
2810
- - schema["x-ad4m"].namespace
2811
- - schema.title
2812
- - valid schema.$id`
279
+ "generateSHACL() is only available on classes decorated with @Model",
2813
280
  );
2814
281
  }
2815
-
2816
- /**
2817
- * Determines the predicate for a specific property using cascading precedence
2818
- */
2819
- private static determinePredicate(
2820
- schema: JSONSchema,
2821
- propertyName: string,
2822
- propertySchema: JSONSchemaProperty,
2823
- namespace: string,
2824
- options: JSONSchemaToModelOptions
2825
- ): string {
2826
- // 1. Explicit property mapping (highest precedence)
2827
- if (options.propertyMapping?.[propertyName]) {
2828
- return options.propertyMapping[propertyName];
2829
- }
2830
-
2831
- // 2. x-ad4m metadata in property schema
2832
- if (propertySchema["x-ad4m"]?.through) {
2833
- return propertySchema["x-ad4m"].through;
2834
- }
2835
-
2836
- // 3. Generate from namespace + property name
2837
- if (options.predicateTemplate) {
2838
- const normalizedNs = normalizeNamespaceString(namespace);
2839
- const [scheme, rest] = normalizedNs.includes('://') ? normalizedNs.split('://') : ['', normalizedNs];
2840
- const nsNoScheme = rest || '';
2841
- return options.predicateTemplate
2842
- .replace('${namespace}', nsNoScheme)
2843
- .replace('${scheme}', scheme)
2844
- .replace('${ns}', nsNoScheme)
2845
- .replace('${title}', schema.title || '')
2846
- .replace('${property}', propertyName);
2847
- }
2848
-
2849
- // 4. Custom predicate generator
2850
- if (options.predicateGenerator) {
2851
- return options.predicateGenerator(schema.title || '', propertyName);
2852
- }
2853
-
2854
- // 5. Default: namespace + property name
2855
- const normalizedNs = normalizeNamespaceString(namespace);
2856
- if (normalizedNs.includes('://')) {
2857
- // For namespaces like "product://", append property directly
2858
- return `${normalizedNs}${propertyName}`;
2859
- } else {
2860
- return `${normalizedNs}://${propertyName}`;
2861
- }
2862
- }
2863
-
2864
- /**
2865
- * Gets property-specific options using cascading precedence
2866
- */
2867
- private static getPropertyOption(
2868
- propertyName: string,
2869
- propertySchema: JSONSchemaProperty,
2870
- options: JSONSchemaToModelOptions,
2871
- optionName: keyof PropertyOptions,
2872
- defaultValue?: any
2873
- ): any {
2874
- // 1. Property-specific options
2875
- if (options.propertyOptions?.[propertyName]?.[optionName] !== undefined) {
2876
- return options.propertyOptions[propertyName][optionName];
2877
- }
2878
-
2879
- // 2. x-ad4m metadata in property
2880
- if (propertySchema["x-ad4m"]?.[optionName as keyof JSONSchemaProperty["x-ad4m"]] !== undefined) {
2881
- return propertySchema["x-ad4m"][optionName as keyof JSONSchemaProperty["x-ad4m"]];
2882
- }
2883
-
2884
- // 3. Global option
2885
- if (options[optionName as keyof JSONSchemaToModelOptions] !== undefined) {
2886
- return options[optionName as keyof JSONSchemaToModelOptions];
282
+
283
+ /** @param id - Auto-generated from a random literal if omitted. */
284
+ constructor(perspective: PerspectiveProxy, id?: string) {
285
+ this._id = id ? id : Literal.from(makeRandomId(24)).toUrl();
286
+ this._perspective = perspective;
287
+
288
+ // Wire up real relation adder/remover/setter methods for decorator-based classes.
289
+ // The @HasMany / @HasOne decorators place empty stubs on the prototype at class-definition
290
+ // time (e.g. `addLocations = () => {}`). Here, at instance-creation time, we replace each
291
+ // stub with a closure that actually calls the private implementation so that callers like
292
+ // `instance.addLocations(value)` persist the link in the perspective.
293
+ const proto = Object.getPrototypeOf(this);
294
+ const relations: Record<string, any> = getRelationsMetadata(
295
+ proto.constructor,
296
+ );
297
+ for (const key of Object.keys(relations)) {
298
+ // Reverse relations (@BelongsToOne / @BelongsToMany) are read-only traversals —
299
+ // the link is owned by the other side, so no mutator methods should exist here.
300
+ if (relations[key].direction === "reverse") continue;
301
+
302
+ const cap = capitalize(key);
303
+ this[`add${cap}`] = (value: any, batchId?: string) =>
304
+ mutation.setRelationAdder(this._mutationContext(), key, value, batchId);
305
+ this[`remove${cap}`] = (value: any, batchId?: string) =>
306
+ mutation.setRelationRemover(
307
+ this._mutationContext(),
308
+ key,
309
+ value,
310
+ batchId,
311
+ );
312
+ this[`set${cap}`] = (value: any, batchId?: string) =>
313
+ mutation.setRelationSetter(
314
+ this._mutationContext(),
315
+ key,
316
+ value,
317
+ batchId,
318
+ );
2887
319
  }
2888
-
2889
- // 4. Default value
2890
- return defaultValue;
2891
320
  }
2892
-
321
+
2893
322
  /**
2894
- * Gets default value for a JSON Schema type
323
+ * The unique identifier (base expression URI) of this instance.
2895
324
  */
2896
- private static getDefaultValueForType(type?: string): any {
2897
- switch (type) {
2898
- case 'string': return '';
2899
- case 'number': return 0;
2900
- case 'integer': return 0;
2901
- case 'boolean': return false;
2902
- case 'array': return [];
2903
- case 'object': return {};
2904
- default: return '';
2905
- }
325
+ get id() {
326
+ return this._id;
2906
327
  }
2907
- }
2908
328
 
2909
- /** Query builder for Ad4mModel queries.
2910
- * Allows building queries with a fluent interface and either running them once
2911
- * or subscribing to updates.
2912
- *
2913
- * @example
2914
- * ```typescript
2915
- * const builder = Recipe.query(perspective)
2916
- * .where({ category: "Dessert" })
2917
- * .order({ rating: "DESC" })
2918
- * .limit(10);
2919
- *
2920
- * // Run once
2921
- * const recipes = await builder.run();
2922
- *
2923
- * // Or subscribe to updates
2924
- * await builder.subscribe(recipes => {
2925
- * console.log("Updated recipes:", recipes);
2926
- * });
2927
- * ```
2928
- */
2929
- export class ModelQueryBuilder<T extends Ad4mModel> {
2930
- private perspective: PerspectiveProxy;
2931
- private queryParams: Query = {};
2932
- private modelClassName: string | null = null;
2933
- private ctor: typeof Ad4mModel;
2934
- private currentSubscription?: any;
2935
- private useSurrealDBFlag: boolean = true;
329
+ /** Read-only perspective access for subclasses. */
330
+ protected get perspective(): PerspectiveProxy {
331
+ return this._perspective;
332
+ }
2936
333
 
2937
- constructor(perspective: PerspectiveProxy, ctor: typeof Ad4mModel, query?: Query) {
2938
- this.perspective = perspective;
2939
- this.ctor = ctor;
2940
- if (query) this.queryParams = query;
334
+ /** Builds the context object for all mutation functions. */
335
+ private _mutationContext(): mutation.MutationContext {
336
+ return {
337
+ perspective: this._perspective,
338
+ id: this._id,
339
+ instance: this,
340
+ };
2941
341
  }
2942
342
 
2943
343
  /**
2944
- * Disposes of the current subscription if one exists.
2945
- *
2946
- * This method:
2947
- * 1. Stops the keepalive signals to the subscription
2948
- * 2. Unsubscribes from GraphQL subscription updates
2949
- * 3. Notifies the backend to clean up subscription resources
2950
- * 4. Clears the subscription reference
2951
- *
2952
- * You should call this method when you're done with a subscription
2953
- * to prevent memory leaks and ensure proper cleanup.
344
+ * Generates a SurrealQL query string for this model.
345
+ *
346
+ * @param perspective - The perspective context
347
+ * @param query - Query parameters (where, order, limit, offset, properties, relations)
348
+ * @returns Complete SurrealQL query string ready for execution
2954
349
  */
2955
- dispose() {
2956
- if (this.currentSubscription) {
2957
- this.currentSubscription.dispose();
2958
- this.currentSubscription = undefined;
2959
- }
350
+ public static async queryToSurrealQL(
351
+ perspective: PerspectiveProxy,
352
+ query: Query,
353
+ ): Promise<string> {
354
+ return ops.queryToSurrealQL(this as any, perspective, query);
2960
355
  }
2961
356
 
2962
- /**
2963
- * Adds where conditions to the query.
2964
- *
2965
- * @param conditions - The conditions to filter by
2966
- * @returns The query builder for chaining
2967
- *
2968
- * @example
2969
- * ```typescript
2970
- * .where({
2971
- * category: "Dessert",
2972
- * rating: { gt: 4 },
2973
- * tags: ["vegan", "quick"],
2974
- * published: true
2975
- * })
2976
- * ```
2977
- */
2978
- where(conditions: Where): ModelQueryBuilder<T> {
2979
- this.queryParams.where = conditions;
2980
- return this;
357
+ /** @internal */
358
+ public static async instancesFromSurrealResult<T extends Ad4mModel>(
359
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
360
+ perspective: PerspectiveProxy,
361
+ query: Query,
362
+ result: any[],
363
+ _hydrateRelations = true,
364
+ ): Promise<ResultsWithTotalCount<T>> {
365
+ return ops.instancesFromSurrealResult(
366
+ this as any,
367
+ perspective,
368
+ query,
369
+ result,
370
+ _hydrateRelations,
371
+ );
2981
372
  }
2982
373
 
2983
374
  /**
2984
- * Sets the order for the query results.
2985
- *
2986
- * @param orderBy - The ordering criteria
2987
- * @returns The query builder for chaining
2988
- *
2989
- * @example
2990
- * ```typescript
2991
- * .order({ createdAt: "DESC" })
2992
- * ```
375
+ * Internal implementation used by findAll and eager relation hydration.
376
+ * Pass `_hydrateRelations = false` to prevent recursive model hydration (depth guard).
2993
377
  */
2994
- order(orderBy: Order): ModelQueryBuilder<T> {
2995
- this.queryParams.order = orderBy;
2996
- return this;
378
+ static async _findAllInternal<T extends Ad4mModel>(
379
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
380
+ perspective: PerspectiveProxy,
381
+ query: Query = {},
382
+ _hydrateRelations = true,
383
+ ): Promise<T[]> {
384
+ return ops._findAllInternal(
385
+ this as any,
386
+ perspective,
387
+ query,
388
+ _hydrateRelations,
389
+ );
2997
390
  }
2998
391
 
2999
392
  /**
3000
- * Sets the maximum number of results to return.
3001
- *
3002
- * @param limit - Maximum number of results
3003
- * @returns The query builder for chaining
3004
- *
393
+ * Returns all instances matching `query`.
394
+ *
3005
395
  * @example
3006
396
  * ```typescript
3007
- * .limit(10)
397
+ * const recipes = await Recipe.findAll(perspective, {
398
+ * where: { rating: { gt: 4 } }, order: { createdAt: "DESC" }, limit: 10,
399
+ * });
3008
400
  * ```
3009
401
  */
3010
- limit(limit: number): ModelQueryBuilder<T> {
3011
- this.queryParams.limit = limit;
3012
- return this;
402
+ static async findAll<T extends Ad4mModel>(
403
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
404
+ perspective: PerspectiveProxy,
405
+ query: Query = {},
406
+ ): Promise<T[]> {
407
+ return ops.findAll(this as any, perspective, query);
3013
408
  }
3014
409
 
3015
410
  /**
3016
- * Sets the number of results to skip.
3017
- *
3018
- * @param offset - Number of results to skip
3019
- * @returns The query builder for chaining
3020
- *
411
+ * Returns the first matching instance, or `null` if none found.
412
+ *
3021
413
  * @example
3022
414
  * ```typescript
3023
- * .offset(20) // Skip first 20 results
415
+ * const post = await TestPost.findOne(perspective, { where: { id: someId } });
3024
416
  * ```
3025
417
  */
3026
- offset(offset: number): ModelQueryBuilder<T> {
3027
- this.queryParams.offset = offset;
3028
- return this;
418
+ static async findOne<T extends Ad4mModel>(
419
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
420
+ perspective: PerspectiveProxy,
421
+ query: Query = {},
422
+ ): Promise<T | null> {
423
+ return ops.findOne(this as any, perspective, query);
3029
424
  }
3030
425
 
3031
426
  /**
3032
- * Sets the source filter for the query.
3033
- *
3034
- * @param source - The source to filter by
3035
- * @returns The query builder for chaining
3036
- *
427
+ * Like `findAll` but also returns the unfiltered total count (useful for pagination UI).
428
+ *
3037
429
  * @example
3038
430
  * ```typescript
3039
- * .source("ad4m://self")
431
+ * const { results, totalCount } = await Recipe.findAllAndCount(perspective, { limit: 10 });
432
+ * console.log(`Showing ${results.length} of ${totalCount}`);
3040
433
  * ```
3041
434
  */
3042
- source(source: string): ModelQueryBuilder<T> {
3043
- this.queryParams.source = source;
3044
- return this;
435
+ static async findAllAndCount<T extends Ad4mModel>(
436
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
437
+ perspective: PerspectiveProxy,
438
+ query: Query = {},
439
+ ): Promise<ResultsWithTotalCount<T>> {
440
+ return ops.findAllAndCount(this as any, perspective, query);
3045
441
  }
3046
442
 
3047
443
  /**
3048
- * Specifies which properties to include in the results.
3049
- *
3050
- * @param properties - Array of property names to include
3051
- * @returns The query builder for chaining
3052
- *
444
+ * Fetches a single page of results (`pageNumber` is 1-based).
445
+ *
3053
446
  * @example
3054
447
  * ```typescript
3055
- * .properties(["name", "description", "rating"])
448
+ * const page = await Recipe.paginate(perspective, 10, 1);
449
+ * console.log(`Page ${page.pageNumber}, ${page.results.length} items`);
3056
450
  * ```
3057
451
  */
3058
- properties(properties: string[]): ModelQueryBuilder<T> {
3059
- this.queryParams.properties = properties;
3060
- return this;
452
+ static async paginate<T extends Ad4mModel>(
453
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
454
+ perspective: PerspectiveProxy,
455
+ pageSize: number,
456
+ pageNumber: number,
457
+ query?: Query,
458
+ ): Promise<PaginationResult<T>> {
459
+ return ops.paginate(
460
+ this as any,
461
+ perspective,
462
+ pageSize,
463
+ pageNumber,
464
+ query ?? {},
465
+ );
3061
466
  }
3062
467
 
3063
468
  /**
3064
- * Specifies which collections to include in the results.
3065
- *
3066
- * @param collections - Array of collection names to include
3067
- * @returns The query builder for chaining
3068
- *
3069
- * @example
3070
- * ```typescript
3071
- * .collections(["ingredients", "steps"])
3072
- * ```
469
+ * Generates a SurrealQL COUNT query for this model.
470
+ * @private
3073
471
  */
3074
- collections(collections: string[]): ModelQueryBuilder<T> {
3075
- this.queryParams.collections = collections;
3076
- return this;
472
+ public static async countQueryToSurrealQL(
473
+ perspective: PerspectiveProxy,
474
+ query: Query,
475
+ ): Promise<string> {
476
+ return ops.countQueryToSurrealQL(this as any, perspective, query);
3077
477
  }
3078
478
 
3079
- overrideModelClassName(className: string): ModelQueryBuilder<T> {
3080
- this.modelClassName = className;
3081
- return this;
479
+ /** Returns the count of instances matching `query`. */
480
+ static async count(perspective: PerspectiveProxy, query: Query = {}) {
481
+ return ops.count(this as any, perspective, query);
3082
482
  }
3083
483
 
3084
484
  /**
3085
- * Enables or disables SurrealDB query path.
3086
- *
3087
- * @param enabled - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
3088
- * @returns The query builder for chaining
3089
- *
485
+ * Persists the instance (create if new, update if existing).
486
+ *
487
+ * @param batchId - When provided the caller must call `perspective.commitBatch(batchId)`
488
+ *
3090
489
  * @example
3091
490
  * ```typescript
3092
- * // Use SurrealDB (default)
3093
- * const recipes = await Recipe.query(perspective)
3094
- * .where({ category: "Dessert" })
3095
- * .useSurrealDB(true)
3096
- * .get();
3097
- *
3098
- * // Use Prolog (legacy)
3099
- * const recipesProlog = await Recipe.query(perspective)
3100
- * .where({ category: "Dessert" })
3101
- * .useSurrealDB(false)
3102
- * .get();
491
+ * const recipe = new Recipe(perspective);
492
+ * recipe.name = "Spaghetti";
493
+ * await recipe.save(); // create
494
+ * recipe.name = "Bolognese";
495
+ * await recipe.save(); // update (detected automatically)
3103
496
  * ```
3104
- *
3105
- * @remarks
3106
- * Note: Subscriptions (subscribe(), countSubscribe(), paginateSubscribe()) default to SurrealDB live queries
3107
- * if useSurrealDB(true) is set (default).
3108
497
  */
3109
- useSurrealDB(enabled: boolean = true): ModelQueryBuilder<T> {
3110
- this.useSurrealDBFlag = enabled;
3111
- return this;
498
+ async save(batchId?: string) {
499
+ await mutation.saveInstance(
500
+ this._mutationContext(),
501
+ batchId,
502
+ this._savedOnce,
503
+ );
504
+ this._savedOnce = true;
3112
505
  }
3113
506
 
3114
507
  /**
3115
- * Executes the query once and returns the results.
3116
- *
3117
- * @returns Array of matching entities
3118
- *
508
+ * Gets the model instance with all properties and relations populated.
509
+ *
510
+ * @returns The populated model instance
511
+ * @throws Will throw if data retrieval fails
512
+ *
3119
513
  * @example
3120
514
  * ```typescript
3121
- * const recipes = await Recipe.query(perspective)
3122
- * .where({ category: "Dessert" })
3123
- * .get();
515
+ * const recipe = new Recipe(perspective, existingId);
516
+ * await recipe.get();
517
+ * console.log(recipe.name, recipe.ingredients);
3124
518
  * ```
3125
519
  */
3126
- async get(): Promise<T[]> {
3127
- if (this.useSurrealDBFlag) {
3128
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
3129
- const result = await this.perspective.querySurrealDB(surrealQuery);
3130
- const { results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
3131
- return results as T[];
3132
- } else {
3133
- const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
3134
- const result = await this.perspective.infer(query);
3135
- const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
3136
- return results as T[];
3137
- }
520
+ async get(include?: IncludeMap): Promise<this> {
521
+ const metadata = (this.constructor as typeof Ad4mModel).getModelMetadata();
522
+ return fetchInstanceData(
523
+ this,
524
+ this._perspective,
525
+ this._id,
526
+ metadata,
527
+ include,
528
+ );
3138
529
  }
3139
530
 
3140
531
  /**
3141
- * Subscribes to the query and receives updates when results change.
3142
- *
3143
- * This method:
3144
- * 1. Creates and initializes a SurrealDB live query subscription (default)
3145
- * 2. Sets up the callback to process future updates
3146
- * 3. Returns the initial results immediately
3147
- *
3148
- * Remember to call dispose() when you're done with the subscription
3149
- * to clean up resources.
3150
- *
3151
- * @param callback - Function to call with updated results
3152
- * @returns Initial results array
532
+ * Removes this instance from the perspective, including all incoming links
533
+ * that point to it (e.g. parent→child membership links created by
534
+ * `create({ parent: ... })`). This ensures that `findAll({ parent: ... })`
535
+ * will no longer return this instance after deletion.
3153
536
  *
3154
537
  * @example
3155
- * ```typescript
3156
- * const builder = Recipe.query(perspective)
3157
- * .where({ status: "cooking" });
3158
- *
3159
- * const initialRecipes = await builder.subscribe(recipes => {
3160
- * console.log("Updated recipes:", recipes);
3161
- * });
3162
- *
3163
- * // When done with subscription:
3164
- * builder.dispose();
3165
- * ```
538
+ * await vote.delete();
3166
539
  *
3167
- * @remarks
3168
- * By default, this uses SurrealDB live queries for real-time updates.
3169
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
540
+ * @param batchId - Optional batch identifier for grouping removals.
3170
541
  */
3171
- async subscribe(callback: (results: T[]) => void): Promise<T[]> {
3172
- // Clean up any existing subscription
3173
- this.dispose();
3174
-
3175
- if (this.useSurrealDBFlag) {
3176
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
3177
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
3178
-
3179
- const processResults = async (result: any) => {
3180
- // The result from live query subscription update (handled in PerspectiveInstance listener)
3181
- // is the new full set of results (because we re-query in Rust).
3182
- // So we just need to map it to instances.
3183
- const { results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
3184
- callback(results as T[]);
3185
- };
3186
-
3187
- this.currentSubscription.onResult(processResults);
3188
-
3189
- // Process initial result
3190
- const { results } = await this.ctor.instancesFromSurrealResult(
3191
- this.perspective,
3192
- this.queryParams,
3193
- this.currentSubscription.result
3194
- );
3195
- return results as T[];
3196
- } else {
3197
- // Note: Subscriptions currently only work with Prolog
3198
- const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
3199
- this.currentSubscription = await this.perspective.subscribeInfer(query);
3200
-
3201
- const processResults = async (result: AllInstancesResult) => {
3202
- const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
3203
- callback(results as T[]);
3204
- };
3205
-
3206
- this.currentSubscription.onResult(processResults);
3207
- const { results } = await this.ctor.instancesFromPrologResult(
3208
- this.perspective,
3209
- this.queryParams,
3210
- this.currentSubscription.result
3211
- );
3212
- return results as T[];
542
+ async delete(batchId?: string) {
543
+ // Remove all incoming links that point to this instance so that parent
544
+ // collections (parent queries) are kept consistent.
545
+ const incomingLinks = await this._perspective.get(
546
+ new LinkQuery({ target: this._id }),
547
+ );
548
+ for (const link of incomingLinks) {
549
+ await this._perspective.remove(link);
3213
550
  }
551
+
552
+ await this._perspective.removeSubject(this, this._id, batchId);
3214
553
  }
3215
554
 
3216
555
  /**
3217
- * Gets the total count of matching entities.
3218
- *
3219
- * @returns Total count
3220
- *
556
+ * Returns a fluent query builder for this model.
557
+ *
3221
558
  * @example
3222
559
  * ```typescript
3223
- * const totalDesserts = await Recipe.query(perspective)
560
+ * const top5 = await Recipe.query(perspective)
3224
561
  * .where({ category: "Dessert" })
3225
- * .count();
562
+ * .order({ rating: "DESC" })
563
+ * .limit(5)
564
+ * .run();
3226
565
  * ```
3227
566
  */
3228
- async count(): Promise<number> {
3229
- if (this.useSurrealDBFlag) {
3230
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
3231
- const result = await this.perspective.querySurrealDB(surrealQuery);
3232
- // Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
3233
- // (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
3234
- // This ensures count() returns the same number as get().length
3235
- const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
3236
- return totalCount;
3237
- } else {
3238
- const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
3239
- const result = await this.perspective.infer(query);
3240
- return result?.[0]?.TotalCount || 0;
3241
- }
567
+ static query<T extends Ad4mModel>(
568
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
569
+ perspective: PerspectiveProxy,
570
+ query?: Query,
571
+ ): ModelQueryBuilder<T> {
572
+ return new ModelQueryBuilder<T>(perspective, this as any, query);
3242
573
  }
3243
574
 
3244
575
  /**
3245
- * Subscribes to count updates for matching entities.
3246
- *
3247
- * This method:
3248
- * 1. Creates and initializes a SurrealDB live query subscription for the count (default)
3249
- * 2. Sets up the callback to process future count updates
3250
- * 3. Returns the initial count immediately
3251
- *
3252
- * Remember to call dispose() when you're done with the subscription
3253
- * to clean up resources.
3254
- *
3255
- * @param callback - Function to call with updated count
3256
- * @returns Initial count
576
+ * Runs `callback` in an atomic batch; commits on success, aborts + rethrows on failure.
3257
577
  *
3258
578
  * @example
3259
579
  * ```typescript
3260
- * const builder = Recipe.query(perspective)
3261
- * .where({ status: "active" });
3262
- *
3263
- * const initialCount = await builder.countSubscribe(count => {
3264
- * console.log("Active items:", count);
580
+ * await Ad4mModel.transaction(perspective, async (tx) => {
581
+ * await post.save(tx.batchId);
582
+ * await comment.save(tx.batchId);
3265
583
  * });
3266
- *
3267
- * // When done with subscription:
3268
- * builder.dispose();
3269
584
  * ```
3270
- *
3271
- * @remarks
3272
- * By default, this uses SurrealDB live queries for real-time updates.
3273
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
3274
585
  */
3275
- async countSubscribe(callback: (count: number) => void): Promise<number> {
3276
- // Clean up any existing subscription
3277
- this.dispose();
3278
-
3279
- if (this.useSurrealDBFlag) {
3280
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
3281
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
3282
-
3283
- const processResults = async (result: any) => {
3284
- const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
3285
- callback(totalCount);
3286
- };
3287
-
3288
- this.currentSubscription.onResult(processResults);
3289
- const { totalCount } = await this.ctor.instancesFromSurrealResult(
3290
- this.perspective,
3291
- this.queryParams,
3292
- this.currentSubscription.result
3293
- );
3294
- return totalCount;
3295
- } else {
3296
- const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
3297
- this.currentSubscription = await this.perspective.subscribeInfer(query);
3298
-
3299
- const processResults = async (result: any) => {
3300
- const newCount = result?.[0]?.TotalCount || 0;
3301
- callback(newCount);
3302
- };
3303
-
3304
- this.currentSubscription.onResult(processResults);
3305
- return this.currentSubscription.result?.[0]?.TotalCount || 0;
3306
- }
586
+ static async transaction<T>(
587
+ perspective: PerspectiveProxy,
588
+ callback: (tx: import("./transaction").TransactionContext) => Promise<T>,
589
+ ): Promise<T> {
590
+ return runTransaction(perspective, callback);
3307
591
  }
3308
592
 
3309
593
  /**
3310
- * Gets a page of results with pagination metadata.
3311
- *
3312
- * @param pageSize - Number of items per page
3313
- * @param pageNumber - Which page to retrieve (1-based)
3314
- * @returns Paginated results with metadata
3315
- *
594
+ * Fires `callback` immediately with current results, then on every relevant perspective change.
595
+ *
596
+ * @param options - Query params plus optional `debounce` (ms) and `onError` handler
597
+ * @param callback - Receives the fresh result set on each delivery
598
+ * @returns `Subscription` with `unsubscribe()` — call it in cleanup to avoid leaks
599
+ *
3316
600
  * @example
3317
601
  * ```typescript
3318
- * const page = await Recipe.query(perspective)
3319
- * .where({ category: "Main" })
3320
- * .paginate(10, 1);
3321
- * console.log(`Page ${page.pageNumber}, ${page.results.length} of ${page.totalCount}`);
602
+ * const sub = Post.subscribe(
603
+ * perspective,
604
+ * { where: { published: true }, debounce: 300 },
605
+ * (posts) => setPosts(posts),
606
+ * );
607
+ * sub.unsubscribe(); // in cleanup
3322
608
  * ```
3323
609
  */
3324
- async paginate(pageSize: number, pageNumber: number): Promise<PaginationResult<T>> {
3325
- const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
3326
- if (this.useSurrealDBFlag) {
3327
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
3328
- const result = await this.perspective.querySurrealDB(surrealQuery);
3329
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result)) as ResultsWithTotalCount<T>;
3330
- return { results, totalCount, pageSize, pageNumber };
3331
- } else {
3332
- const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
3333
- const result = await this.perspective.infer(prologQuery);
3334
- const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, result)) as ResultsWithTotalCount<T>;
3335
- return { results, totalCount, pageSize, pageNumber };
3336
- }
610
+ static subscribe<T extends Ad4mModel>(
611
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
612
+ perspective: PerspectiveProxy,
613
+ options: SubscribeOptions,
614
+ callback: (results: T[]) => void,
615
+ ): Subscription {
616
+ return createSubscription<T>(
617
+ (p, q) => this.findAll(p, q ?? {}),
618
+ () => this.getModelMetadata(),
619
+ perspective,
620
+ options,
621
+ callback,
622
+ this as any,
623
+ );
3337
624
  }
3338
625
 
3339
626
  /**
3340
- * Subscribes to paginated results updates.
3341
- *
3342
- * This method:
3343
- * 1. Creates and initializes a SurrealDB live query subscription for the paginated results (default)
3344
- * 2. Sets up the callback to process future page updates
3345
- * 3. Returns the initial page immediately
3346
- *
3347
- * Remember to call dispose() when you're done with the subscription
3348
- * to clean up resources.
627
+ * Generates an `Ad4mModel` subclass from a JSON Schema definition.
3349
628
  *
3350
- * @param pageSize - Number of items per page
3351
- * @param pageNumber - Which page to retrieve (1-based)
3352
- * @param callback - Function to call with updated pagination results
3353
- * @returns Initial pagination results
629
+ * Predicate resolution order: explicit options → `x-ad4m` in schema → inferred from title/names.
3354
630
  *
3355
631
  * @example
3356
632
  * ```typescript
3357
- * const builder = Recipe.query(perspective)
3358
- * .where({ category: "Main" });
3359
- *
3360
- * const initialPage = await builder.paginateSubscribe(10, 1, page => {
3361
- * console.log("Updated page:", page.results);
633
+ * const PersonClass = Ad4mModel.fromJSONSchema(schema, {
634
+ * name: "Person", namespace: "person://", resolveLanguage: "literal",
3362
635
  * });
3363
- *
3364
- * // When done with subscription:
3365
- * builder.dispose();
3366
636
  * ```
3367
- *
3368
- * @remarks
3369
- * By default, this uses SurrealDB live queries for real-time updates.
3370
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
3371
637
  */
3372
- async paginateSubscribe(
3373
- pageSize: number,
3374
- pageNumber: number,
3375
- callback: (results: PaginationResult<T>) => void
3376
- ): Promise<PaginationResult<T>> {
3377
- // Clean up any existing subscription
3378
- this.dispose();
3379
-
3380
- const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
3381
-
3382
- if (this.useSurrealDBFlag) {
3383
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
3384
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
3385
-
3386
- const processResults = async (result: any) => {
3387
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result)) as ResultsWithTotalCount<T>;
3388
- callback({ results, totalCount, pageSize, pageNumber });
3389
- };
3390
-
3391
- this.currentSubscription.onResult(processResults);
3392
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, this.currentSubscription.result)) as ResultsWithTotalCount<T>;
3393
- return { results, totalCount, pageSize, pageNumber };
3394
- } else {
3395
- const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
3396
- this.currentSubscription = await this.perspective.subscribeInfer(prologQuery);
3397
-
3398
- const processResults = async (r: AllInstancesResult) => {
3399
- const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, r)) as ResultsWithTotalCount<T>;
3400
- callback({ results, totalCount, pageSize, pageNumber });
3401
- };
3402
-
3403
- this.currentSubscription.onResult(processResults);
3404
- const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, this.currentSubscription.result)) as ResultsWithTotalCount<T>;
3405
- return { results, totalCount, pageSize, pageNumber };
3406
- }
638
+ static fromJSONSchema(
639
+ schema: JSONSchema,
640
+ options: JSONSchemaToModelOptions,
641
+ ): typeof Ad4mModel {
642
+ return createModelFromJSONSchema(this, schema, options) as typeof Ad4mModel;
3407
643
  }
3408
644
  }