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