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