@coasys/ad4m 0.10.0 → 0.10.1-multi-user-1

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 (72) hide show
  1. package/lib/index.cjs +3730 -906
  2. package/lib/index.js +3722 -902
  3. package/lib/src/Ad4mClient.js +2 -1
  4. package/lib/src/Literal.js +4 -1
  5. package/lib/src/agent/Agent.d.ts +12 -0
  6. package/lib/src/agent/Agent.js +48 -0
  7. package/lib/src/agent/AgentClient.d.ts +3 -1
  8. package/lib/src/agent/AgentClient.js +23 -0
  9. package/lib/src/ai/AIClient.d.ts +8 -2
  10. package/lib/src/ai/AIClient.js +25 -14
  11. package/lib/src/ai/AIResolver.d.ts +25 -6
  12. package/lib/src/ai/AIResolver.js +102 -18
  13. package/lib/src/index.d.ts +4 -3
  14. package/lib/src/index.js +4 -3
  15. package/lib/src/language/Language.d.ts +12 -1
  16. package/lib/src/model/Ad4mModel.d.ts +622 -0
  17. package/lib/src/model/Ad4mModel.js +1118 -0
  18. package/lib/src/{subject → model}/Subject.d.ts +2 -2
  19. package/lib/src/{subject → model}/Subject.js +18 -18
  20. package/lib/src/model/decorators.d.ts +502 -0
  21. package/lib/src/model/decorators.js +683 -0
  22. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +2 -2
  23. package/lib/src/neighbourhood/NeighbourhoodClient.js +13 -10
  24. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +2 -2
  25. package/lib/src/neighbourhood/NeighbourhoodProxy.js +4 -4
  26. package/lib/src/neighbourhood/NeighbourhoodProxy.test.d.ts +1 -0
  27. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +73 -0
  28. package/lib/src/neighbourhood/NeighbourhoodResolver.d.ts +2 -2
  29. package/lib/src/neighbourhood/NeighbourhoodResolver.js +6 -4
  30. package/lib/src/perspectives/PerspectiveClient.d.ts +23 -11
  31. package/lib/src/perspectives/PerspectiveClient.js +147 -51
  32. package/lib/src/perspectives/PerspectiveProxy.d.ts +494 -54
  33. package/lib/src/perspectives/PerspectiveProxy.js +684 -67
  34. package/lib/src/perspectives/PerspectiveResolver.d.ts +24 -9
  35. package/lib/src/perspectives/PerspectiveResolver.js +151 -46
  36. package/lib/src/runtime/RuntimeClient.d.ts +11 -2
  37. package/lib/src/runtime/RuntimeClient.js +94 -0
  38. package/lib/src/runtime/RuntimeResolver.d.ts +36 -1
  39. package/lib/src/runtime/RuntimeResolver.js +193 -0
  40. package/lib/src/schema.gql +65 -16
  41. package/lib/src/typeDefs.js +65 -16
  42. package/package.json +4 -3
  43. package/src/Ad4mClient.test.ts +51 -19
  44. package/src/Ad4mClient.ts +3 -1
  45. package/src/Literal.ts +4 -1
  46. package/src/agent/Agent.ts +36 -0
  47. package/src/agent/AgentClient.ts +30 -0
  48. package/src/ai/AIClient.ts +35 -14
  49. package/src/ai/AIResolver.ts +78 -16
  50. package/src/index.ts +4 -3
  51. package/src/language/Language.ts +16 -4
  52. package/src/model/Ad4mModel.ts +1279 -0
  53. package/src/{subject → model}/Subject.ts +16 -16
  54. package/src/{subject/SDNADecorators.ts → model/decorators.ts} +384 -50
  55. package/src/neighbourhood/NeighbourhoodClient.ts +13 -10
  56. package/src/neighbourhood/NeighbourhoodProxy.test.ts +100 -0
  57. package/src/neighbourhood/NeighbourhoodProxy.ts +4 -4
  58. package/src/neighbourhood/NeighbourhoodResolver.ts +2 -2
  59. package/src/perspectives/PerspectiveClient.ts +156 -51
  60. package/src/perspectives/PerspectiveProxy.ts +766 -82
  61. package/src/perspectives/PerspectiveResolver.ts +134 -23
  62. package/src/runtime/RuntimeClient.ts +104 -2
  63. package/src/runtime/RuntimeResolver.ts +126 -1
  64. package/lib/src/subject/SDNADecorators.d.ts +0 -188
  65. package/lib/src/subject/SDNADecorators.js +0 -360
  66. package/lib/src/subject/SubjectEntity.d.ts +0 -102
  67. package/lib/src/subject/SubjectEntity.js +0 -267
  68. package/src/subject/SubjectEntity.ts +0 -315
  69. package/yarn-error.log +0 -90
  70. /package/lib/src/{subject → model}/util.d.ts +0 -0
  71. /package/lib/src/{subject → model}/util.js +0 -0
  72. /package/src/{subject → model}/util.ts +0 -0
@@ -0,0 +1,1118 @@
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
+ import { Literal } from "../Literal";
14
+ import { Link } from "../links/Links";
15
+ import { makeRandomPrologAtom } from "./decorators";
16
+ import { singularToPlural } from "./util";
17
+ function capitalize(word) {
18
+ return word.charAt(0).toUpperCase() + word.slice(1);
19
+ }
20
+ function buildSourceQuery(source) {
21
+ // Constrains the query to instances that have the provided source
22
+ if (!source)
23
+ return "";
24
+ return `triple("${source}", "ad4m://has_child", Base)`;
25
+ }
26
+ // todo: only return Timestamp & Author from query (Base, AllLinks, and SortLinks not required)
27
+ function buildAuthorAndTimestampQuery() {
28
+ // Gets the author and timestamp of a Ad4mModel instance (based on the first link mentioning the base)
29
+ return `
30
+ findall(
31
+ [T, A],
32
+ link(Base, _, _, T, A),
33
+ AllLinks
34
+ ),
35
+ sort(AllLinks, SortedLinks),
36
+ SortedLinks = [[Timestamp, Author]|_]
37
+ `;
38
+ }
39
+ function buildPropertiesQuery(properties) {
40
+ // Gets the name, value, and resolve boolean for all (or some) properties on a Ad4mModel instance
41
+ // Resolves literals (if property_resolve/2 is true) to their value - either the data field if it is
42
+ // an Expression in JSON literal, or the direct literal value if it is a simple literal
43
+ // If no properties are provided, all are included
44
+ return `
45
+ findall([PropertyName, PropertyValue, Resolve], (
46
+ % Constrain to specified properties if provided
47
+ ${properties ? `member(PropertyName, [${properties.map((name) => `"${name}"`).join(", ")}]),` : ""}
48
+ resolve_property(SubjectClass, Base, PropertyName, PropertyValue, Resolve)
49
+ ), Properties)
50
+ `;
51
+ }
52
+ function buildCollectionsQuery(collections) {
53
+ // Gets the name and array of values for all (or some) collections on a Ad4mModel instance
54
+ // If no collections are provided, all are included
55
+ return `
56
+ findall([CollectionName, CollectionValues], (
57
+ % Constrain to specified collections if provided
58
+ ${collections ? `member(CollectionName, [${collections.map((name) => `"${name}"`).join(", ")}]),` : ""}
59
+
60
+ collection(SubjectClass, CollectionName),
61
+ collection_getter(SubjectClass, Base, CollectionName, CollectionValues)
62
+ ), Collections)
63
+ `;
64
+ }
65
+ function buildWhereQuery(where = {}) {
66
+ // Constrains the query to instances that match the provided where conditions
67
+ function formatValue(value) {
68
+ // Wrap strings in quotes
69
+ return typeof value === "string" ? `"${value}"` : value;
70
+ }
71
+ return Object.entries(where)
72
+ .map(([key, value]) => {
73
+ const isSpecial = ["base", "author", "timestamp"].includes(key);
74
+ const getter = `resolve_property(SubjectClass, Base, "${key}", Value${key}, _)`;
75
+ // const getter = `property_getter(SubjectClass, Base, "${key}", URI), literal_from_url(URI, V, _)`;
76
+ const field = capitalize(key);
77
+ // Handle direct array values (for IN conditions)
78
+ if (Array.isArray(value)) {
79
+ const formattedValues = value.map((v) => formatValue(v)).join(", ");
80
+ if (isSpecial)
81
+ return `member(${field}, [${formattedValues}])`;
82
+ else
83
+ return `${getter}, member(Value${key}, [${formattedValues}])`;
84
+ }
85
+ // Handle operation object
86
+ if (typeof value === "object" && value !== null) {
87
+ const { not, between, lt, lte, gt, gte } = value;
88
+ // Handle NOT operation
89
+ if (not !== undefined) {
90
+ if (Array.isArray(not)) {
91
+ // NOT IN array
92
+ const formattedValues = not.map((v) => formatValue(v)).join(", ");
93
+ if (isSpecial)
94
+ return `\\+ member(${field}, [${formattedValues}])`;
95
+ else
96
+ return `${getter}, \\+ member(Value${key}, [${formattedValues}])`;
97
+ }
98
+ else {
99
+ // NOT EQUAL
100
+ if (isSpecial)
101
+ return `${field} \\= ${formatValue(not)}`;
102
+ else
103
+ return `${getter}, Value${key} \\= ${formatValue(not)}`;
104
+ }
105
+ }
106
+ // Handle BETWEEN
107
+ if (between !== undefined && Array.isArray(between) && between.length === 2) {
108
+ if (isSpecial)
109
+ return `${field} >= ${between[0]}, ${field} =< ${between[1]}`;
110
+ else
111
+ return `${getter}, Value${key} >= ${between[0]}, Value${key} =< ${between[1]}`;
112
+ }
113
+ // Handle lt, lte, gt, & gte operations
114
+ const operators = [
115
+ { value: lt, symbol: "<" },
116
+ { value: lte, symbol: "=<" },
117
+ { value: gt, symbol: ">" },
118
+ { value: gte, symbol: ">=" }, // GREATER THAN OR EQUAL TO
119
+ ];
120
+ for (const { value, symbol } of operators) {
121
+ if (value !== undefined)
122
+ return isSpecial ? `${field} ${symbol} ${value}` : `${getter}, Value${key} ${symbol} ${value}`;
123
+ }
124
+ }
125
+ // Default to direct equality
126
+ if (isSpecial)
127
+ return `${field} = ${formatValue(value)}`;
128
+ else
129
+ return `${getter}, Value${key} = ${formatValue(value)}`;
130
+ })
131
+ .join(", ");
132
+ }
133
+ function buildCountQuery(count) {
134
+ return count ? "length(UnsortedInstances, TotalCount)" : "";
135
+ }
136
+ function buildOrderQuery(order) {
137
+ if (!order)
138
+ return "SortedInstances = UnsortedInstances";
139
+ const [propertyName, direction] = Object.entries(order)[0];
140
+ return `sort_instances(UnsortedInstances, "${propertyName}", "${direction}", SortedInstances)`;
141
+ }
142
+ function buildOffsetQuery(offset) {
143
+ if (!offset || offset < 0)
144
+ return "InstancesWithOffset = SortedInstances";
145
+ return `skipN(SortedInstances, ${offset}, InstancesWithOffset)`;
146
+ }
147
+ function buildLimitQuery(limit) {
148
+ if (!limit || limit < 0)
149
+ return "AllInstances = InstancesWithOffset";
150
+ return `takeN(InstancesWithOffset, ${limit}, AllInstances)`;
151
+ }
152
+ /**
153
+ * Base class for defining data models in AD4M.
154
+ *
155
+ * @description
156
+ * Ad4mModel provides the foundation for creating data models that are stored in AD4M perspectives.
157
+ * Each model instance is represented as a subgraph in the perspective, with properties and collections
158
+ * mapped to links in that graph. The class uses Prolog-based queries to efficiently search and filter
159
+ * instances based on their properties and relationships.
160
+ *
161
+ * Key concepts:
162
+ * - Each model instance has a unique base expression that serves as its identifier
163
+ * - Properties are stored as links with predicates defined by the `through` option
164
+ * - Collections represent one-to-many relationships as sets of links
165
+ * - Queries are translated to Prolog for efficient graph pattern matching
166
+ * - Changes are tracked through the perspective's subscription system
167
+ *
168
+ * @example
169
+ * ```typescript
170
+ * // Define a recipe model
171
+ * @ModelOptions({ name: "Recipe" })
172
+ * class Recipe extends Ad4mModel {
173
+ * // Required property with literal value
174
+ * @Property({
175
+ * through: "recipe://name",
176
+ * resolveLanguage: "literal"
177
+ * })
178
+ * name: string = "";
179
+ *
180
+ * // Optional property with custom initial value
181
+ * @Optional({
182
+ * through: "recipe://status",
183
+ * initial: "recipe://draft"
184
+ * })
185
+ * status: string = "";
186
+ *
187
+ * // Read-only computed property
188
+ * @ReadOnly({
189
+ * through: "recipe://rating",
190
+ * getter: `
191
+ * findall(Rating, triple(Base, "recipe://user_rating", Rating), Ratings),
192
+ * sum_list(Ratings, Sum),
193
+ * length(Ratings, Count),
194
+ * Value is Sum / Count
195
+ * `
196
+ * })
197
+ * averageRating: number = 0;
198
+ *
199
+ * // Collection of ingredients
200
+ * @Collection({ through: "recipe://ingredient" })
201
+ * ingredients: string[] = [];
202
+ *
203
+ * // Collection of comments that are instances of another model
204
+ * @Collection({
205
+ * through: "recipe://comment",
206
+ * where: { isInstance: Comment }
207
+ * })
208
+ * comments: Comment[] = [];
209
+ * }
210
+ *
211
+ * // Create and save a new recipe
212
+ * const recipe = new Recipe(perspective);
213
+ * recipe.name = "Chocolate Cake";
214
+ * recipe.ingredients = ["flour", "sugar", "cocoa"];
215
+ * await recipe.save();
216
+ *
217
+ * // Query recipes in different ways
218
+ * // Get all recipes
219
+ * const allRecipes = await Recipe.findAll(perspective);
220
+ *
221
+ * // Find recipes with specific criteria
222
+ * const desserts = await Recipe.findAll(perspective, {
223
+ * where: {
224
+ * status: "recipe://published",
225
+ * averageRating: { gt: 4 }
226
+ * },
227
+ * order: { name: "ASC" },
228
+ * limit: 10
229
+ * });
230
+ *
231
+ * // Use the fluent query builder
232
+ * const popularRecipes = await Recipe.query(perspective)
233
+ * .where({ averageRating: { gt: 4.5 } })
234
+ * .order({ averageRating: "DESC" })
235
+ * .limit(5)
236
+ * .get();
237
+ *
238
+ * // Subscribe to real-time updates
239
+ * await Recipe.query(perspective)
240
+ * .where({ status: "recipe://cooking" })
241
+ * .subscribe(recipes => {
242
+ * console.log("Currently being cooked:", recipes);
243
+ * });
244
+ *
245
+ * // Paginate results
246
+ * const { results, totalCount, pageNumber } = await Recipe.query(perspective)
247
+ * .where({ status: "recipe://published" })
248
+ * .paginate(10, 1);
249
+ * ```
250
+ */
251
+ export class Ad4mModel {
252
+ static async getClassName(perspective) {
253
+ // Check if this is the Ad4mModel class itself or a subclass
254
+ const isBaseClass = this === Ad4mModel;
255
+ // For the base Ad4mModel class, we can't use the cache
256
+ if (isBaseClass) {
257
+ return await perspective.stringOrTemplateObjectToSubjectClassName(this);
258
+ }
259
+ // Get or create the cache for this class
260
+ let classCache = this.classNamesByClass.get(this);
261
+ if (!classCache) {
262
+ classCache = {};
263
+ this.classNamesByClass.set(this, classCache);
264
+ }
265
+ // Get or create the cached name for this perspective
266
+ const perspectiveID = perspective.uuid;
267
+ if (!classCache[perspectiveID]) {
268
+ classCache[perspectiveID] = await perspective.stringOrTemplateObjectToSubjectClassName(this);
269
+ }
270
+ return classCache[perspectiveID];
271
+ }
272
+ /**
273
+ * Constructs a new model instance.
274
+ *
275
+ * @param perspective - The perspective where this model will be stored
276
+ * @param baseExpression - Optional unique identifier for this instance
277
+ * @param source - Optional source expression this instance is linked to
278
+ *
279
+ * @example
280
+ * ```typescript
281
+ * // Create a new recipe with auto-generated base expression
282
+ * const recipe = new Recipe(perspective);
283
+ *
284
+ * // Create with specific base expression
285
+ * const recipe = new Recipe(perspective, "recipe://chocolate-cake");
286
+ *
287
+ * // Create with source link
288
+ * const recipe = new Recipe(perspective, undefined, "cookbook://desserts");
289
+ * ```
290
+ */
291
+ constructor(perspective, baseExpression, source) {
292
+ _Ad4mModel_baseExpression.set(this, void 0);
293
+ _Ad4mModel_subjectClassName.set(this, void 0);
294
+ _Ad4mModel_source.set(this, void 0);
295
+ _Ad4mModel_perspective.set(this, void 0);
296
+ __classPrivateFieldSet(this, _Ad4mModel_baseExpression, baseExpression ? baseExpression : Literal.from(makeRandomPrologAtom(24)).toUrl(), "f");
297
+ __classPrivateFieldSet(this, _Ad4mModel_perspective, perspective, "f");
298
+ __classPrivateFieldSet(this, _Ad4mModel_source, source || "ad4m://self", "f");
299
+ }
300
+ /**
301
+ * Gets the base expression of the subject.
302
+ */
303
+ get baseExpression() {
304
+ return __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f");
305
+ }
306
+ /**
307
+ * Protected getter for the perspective.
308
+ * Allows subclasses to access the perspective while keeping it private from external code.
309
+ */
310
+ get perspective() {
311
+ return __classPrivateFieldGet(this, _Ad4mModel_perspective, "f");
312
+ }
313
+ static async assignValuesToInstance(perspective, instance, values) {
314
+ // Map properties to object
315
+ const propsObject = Object.fromEntries(await Promise.all(values.map(async ([name, value, resolve]) => {
316
+ let finalValue = value;
317
+ // Handle UTF-8 byte sequences from Prolog URL decoding
318
+ if (!resolve && typeof value === 'string') {
319
+ // Only attempt reconstruction if the string looks like a byte string (all code points <= 0xFF)
320
+ // and contains at least one high byte (>= 0x80). This avoids mangling valid Unicode.
321
+ const codePoints = Array.from(value, ch => ch.codePointAt(0));
322
+ const looksByteString = codePoints.every(cp => cp <= 0xFF);
323
+ const hasHighByte = codePoints.some(cp => cp >= 0x80);
324
+ if (looksByteString && hasHighByte) {
325
+ try {
326
+ const bytes = Uint8Array.from(codePoints);
327
+ const decoded = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
328
+ if (decoded !== value)
329
+ finalValue = decoded;
330
+ }
331
+ catch (error) {
332
+ // If UTF-8 conversion fails, keep the original value
333
+ console.warn(`UTF-8 byte reconstruction failed for property "${name}"`, { value, error });
334
+ }
335
+ }
336
+ }
337
+ // Resolve the value if necessary
338
+ if (resolve) {
339
+ let resolvedExpression = await perspective.getExpression(value);
340
+ if (resolvedExpression) {
341
+ try {
342
+ // Attempt to parse the data as JSON
343
+ finalValue = JSON.parse(resolvedExpression.data);
344
+ }
345
+ catch (error) {
346
+ // If parsing fails, keep the original data
347
+ finalValue = resolvedExpression.data;
348
+ }
349
+ }
350
+ }
351
+ // Apply transform function if it exists
352
+ const transform = instance["__properties"]?.[name]?.transform;
353
+ if (transform && typeof transform === "function") {
354
+ finalValue = transform(finalValue);
355
+ }
356
+ return [name, finalValue];
357
+ })));
358
+ // Assign properties to instance
359
+ Object.assign(instance, propsObject);
360
+ }
361
+ async getData() {
362
+ // Builds an object with the author, timestamp, all properties, & all collections on the Ad4mModel and saves it to the instance
363
+ const subQueries = [buildAuthorAndTimestampQuery(), buildPropertiesQuery(), buildCollectionsQuery()];
364
+ const fullQuery = `
365
+ Base = "${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}",
366
+ subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", SubjectClass),
367
+ ${subQueries.join(", ")}
368
+ `;
369
+ const result = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(fullQuery);
370
+ if (result?.[0]) {
371
+ const { Properties, Collections, Timestamp, Author } = result?.[0];
372
+ const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
373
+ await Ad4mModel.assignValuesToInstance(__classPrivateFieldGet(this, _Ad4mModel_perspective, "f"), this, values);
374
+ }
375
+ return this;
376
+ }
377
+ // Todo: Only return AllInstances (InstancesWithOffset, SortedInstances, & UnsortedInstances not required)
378
+ static async queryToProlog(perspective, query, modelClassName) {
379
+ const { source, properties, collections, where, order, offset, limit, count } = query;
380
+ const className = modelClassName || (await this.getClassName(perspective));
381
+ const instanceQueries = [
382
+ buildAuthorAndTimestampQuery(),
383
+ buildSourceQuery(source),
384
+ buildPropertiesQuery(properties),
385
+ buildCollectionsQuery(collections),
386
+ buildWhereQuery(where),
387
+ ];
388
+ const resultSetQueries = [buildCountQuery(count), buildOrderQuery(order), buildOffsetQuery(offset), buildLimitQuery(limit)];
389
+ const fullQuery = `
390
+ findall([Base, Properties, Collections, Timestamp, Author], (
391
+ subject_class("${className}", SubjectClass),
392
+ instance(SubjectClass, Base),
393
+ ${instanceQueries.filter((q) => q).join(", ")}
394
+ ), UnsortedInstances),
395
+ ${resultSetQueries.filter((q) => q).join(", ")}
396
+ `;
397
+ return fullQuery;
398
+ }
399
+ static async instancesFromPrologResult(perspective, query, result) {
400
+ if (!result?.[0]?.AllInstances)
401
+ return { results: [], totalCount: 0 };
402
+ // Map results to instances
403
+ const requestedAttribtes = [...(query?.properties || []), ...(query?.collections || [])];
404
+ const allInstances = await Promise.all(result[0].AllInstances.map(async ([Base, Properties, Collections, Timestamp, Author]) => {
405
+ try {
406
+ const instance = new this(perspective, Base);
407
+ // Remove unrequested attributes from instance
408
+ if (requestedAttribtes.length) {
409
+ Object.keys(instance).forEach((key) => {
410
+ if (!requestedAttribtes.includes(key))
411
+ delete instance[key];
412
+ });
413
+ }
414
+ // Collect values to assign to instance
415
+ const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
416
+ await Ad4mModel.assignValuesToInstance(perspective, instance, values);
417
+ return instance;
418
+ }
419
+ catch (error) {
420
+ console.error(`Failed to process instance ${Base}:`, error);
421
+ // Return null for failed instances - we'll filter these out below
422
+ return null;
423
+ }
424
+ }));
425
+ return { results: allInstances.filter((instance) => instance !== null), totalCount: result[0].TotalCount };
426
+ }
427
+ /**
428
+ * Gets all instances of the model in the perspective that match the query params.
429
+ *
430
+ * @param perspective - The perspective to search in
431
+ * @param query - Optional query parameters to filter results
432
+ * @returns Array of matching models
433
+ *
434
+ * @example
435
+ * ```typescript
436
+ * // Get all recipes
437
+ * const allRecipes = await Recipe.findAll(perspective);
438
+ *
439
+ * // Get recipes with specific criteria
440
+ * const recipes = await Recipe.findAll(perspective, {
441
+ * where: {
442
+ * name: "Pasta",
443
+ * rating: { gt: 4 }
444
+ * },
445
+ * order: { createdAt: "DESC" },
446
+ * limit: 10
447
+ * });
448
+ * ```
449
+ */
450
+ static async findAll(perspective, query = {}) {
451
+ const prologQuery = await this.queryToProlog(perspective, query);
452
+ const result = await perspective.infer(prologQuery);
453
+ const { results } = await this.instancesFromPrologResult(perspective, query, result);
454
+ return results;
455
+ }
456
+ /**
457
+ * Gets all instances with count of total matches without offset & limit applied.
458
+ *
459
+ * @param perspective - The perspective to search in
460
+ * @param query - Optional query parameters to filter results
461
+ * @returns Object containing results array and total count
462
+ *
463
+ * @example
464
+ * ```typescript
465
+ * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {
466
+ * where: { category: "Dessert" },
467
+ * limit: 10
468
+ * });
469
+ * console.log(`Showing 10 of ${totalCount} dessert recipes`);
470
+ * ```
471
+ */
472
+ static async findAllAndCount(perspective, query = {}) {
473
+ const prologQuery = await this.queryToProlog(perspective, query);
474
+ const result = await perspective.infer(prologQuery);
475
+ return await this.instancesFromPrologResult(perspective, query, result);
476
+ }
477
+ /**
478
+ * Helper function for pagination with explicit page size and number.
479
+ *
480
+ * @param perspective - The perspective to search in
481
+ * @param pageSize - Number of items per page
482
+ * @param pageNumber - Which page to retrieve (1-based)
483
+ * @param query - Optional additional query parameters
484
+ * @returns Paginated results with metadata
485
+ *
486
+ * @example
487
+ * ```typescript
488
+ * const page = await Recipe.paginate(perspective, 10, 1, {
489
+ * where: { category: "Main Course" }
490
+ * });
491
+ * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
492
+ * ```
493
+ */
494
+ static async paginate(perspective, pageSize, pageNumber, query) {
495
+ const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
496
+ const prologQuery = await this.queryToProlog(perspective, paginationQuery);
497
+ const result = await perspective.infer(prologQuery);
498
+ const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
499
+ return { results, totalCount, pageSize, pageNumber };
500
+ }
501
+ static async countQueryToProlog(perspective, query = {}, modelClassName) {
502
+ const { source, where } = query;
503
+ const className = modelClassName || (await this.getClassName(perspective));
504
+ const instanceQueries = [buildAuthorAndTimestampQuery(), buildSourceQuery(source), buildWhereQuery(where)];
505
+ const resultSetQueries = [buildCountQuery(true), buildOrderQuery(), buildOffsetQuery(), buildLimitQuery()];
506
+ const fullQuery = `
507
+ findall([Base, Properties, Collections, Timestamp, Author], (
508
+ subject_class("${className}", SubjectClass),
509
+ instance(SubjectClass, Base),
510
+ ${instanceQueries.filter((q) => q).join(", ")}
511
+ ), UnsortedInstances),
512
+ ${resultSetQueries.filter((q) => q).join(", ")}
513
+ `;
514
+ return fullQuery;
515
+ }
516
+ /**
517
+ * Gets a count of all matching instances.
518
+ *
519
+ * @param perspective - The perspective to search in
520
+ * @param query - Optional query parameters to filter results
521
+ * @returns Total count of matching entities
522
+ *
523
+ * @example
524
+ * ```typescript
525
+ * const totalRecipes = await Recipe.count(perspective);
526
+ * const activeRecipes = await Recipe.count(perspective, {
527
+ * where: { status: "active" }
528
+ * });
529
+ * ```
530
+ */
531
+ static async count(perspective, query = {}) {
532
+ const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
533
+ return result?.[0]?.TotalCount || 0;
534
+ }
535
+ async setProperty(key, value, batchId) {
536
+ const setters = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), property_setter(C, "${key}", Setter)`);
537
+ if (setters && setters.length > 0) {
538
+ const actions = eval(setters[0].Setter);
539
+ const resolveLanguageResults = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), property_resolve_language(C, "${key}", Language)`);
540
+ let resolveLanguage;
541
+ if (resolveLanguageResults && resolveLanguageResults.length > 0) {
542
+ resolveLanguage = resolveLanguageResults[0].Language;
543
+ }
544
+ if (resolveLanguage) {
545
+ value = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").createExpression(value, resolveLanguage);
546
+ }
547
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
548
+ }
549
+ }
550
+ async setCollectionSetter(key, value, batchId) {
551
+ let collectionSetters = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), collection_setter(C, "${singularToPlural(key)}", Setter)`);
552
+ if (!collectionSetters)
553
+ collectionSetters = [];
554
+ if (collectionSetters.length > 0) {
555
+ const actions = eval(collectionSetters[0].Setter);
556
+ if (value) {
557
+ if (Array.isArray(value)) {
558
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), value.map((v) => ({ name: "value", value: v })), batchId);
559
+ }
560
+ else {
561
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
562
+ }
563
+ }
564
+ }
565
+ }
566
+ async setCollectionAdder(key, value, batchId) {
567
+ let adders = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), collection_adder(C, "${singularToPlural(key)}", Adder)`);
568
+ if (!adders)
569
+ adders = [];
570
+ if (adders.length > 0) {
571
+ const actions = eval(adders[0].Adder);
572
+ if (value) {
573
+ if (Array.isArray(value)) {
574
+ await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
575
+ }
576
+ else {
577
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
578
+ }
579
+ }
580
+ }
581
+ }
582
+ async setCollectionRemover(key, value, batchId) {
583
+ let removers = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), collection_remover(C, "${singularToPlural(key)}", Remover)`);
584
+ if (!removers)
585
+ removers = [];
586
+ if (removers.length > 0) {
587
+ const actions = eval(removers[0].Remover);
588
+ if (value) {
589
+ if (Array.isArray(value)) {
590
+ await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
591
+ }
592
+ else {
593
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
594
+ }
595
+ }
596
+ }
597
+ }
598
+ /**
599
+ * Saves the model instance to the perspective.
600
+ * Creates a new instance with the base expression and links it to the source.
601
+ *
602
+ * @param batchId - Optional batch ID for batch operations
603
+ * @throws Will throw if instance creation, linking, or updating fails
604
+ *
605
+ * @example
606
+ * ```typescript
607
+ * const recipe = new Recipe(perspective);
608
+ * recipe.name = "Spaghetti";
609
+ * recipe.ingredients = ["pasta", "tomato sauce"];
610
+ * await recipe.save();
611
+ *
612
+ * // Or with batch operations:
613
+ * const batchId = await perspective.createBatch();
614
+ * await recipe.save(batchId);
615
+ * await perspective.commitBatch(batchId);
616
+ * ```
617
+ */
618
+ async save(batchId) {
619
+ // We use createSubject's initialValues to set properties (but not collections)
620
+ // We then later use innerUpdate to set collections
621
+ let batchCreatedHere = false;
622
+ if (!batchId) {
623
+ batchId = await this.perspective.createBatch();
624
+ batchCreatedHere = true;
625
+ }
626
+ // First filter out the properties that are not collections (arrays)
627
+ const initialValues = {};
628
+ for (const [key, value] of Object.entries(this)) {
629
+ if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {
630
+ initialValues[key] = value;
631
+ }
632
+ }
633
+ // Create the subject with the initial values
634
+ await this.perspective.createSubject(this, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), initialValues, batchId);
635
+ // Link the subject to the source
636
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").add(new Link({ source: __classPrivateFieldGet(this, _Ad4mModel_source, "f"), predicate: "ad4m://has_child", target: this.baseExpression }), 'shared', batchId);
637
+ // Set collections
638
+ await this.innerUpdate(false, batchId);
639
+ // If we got a batchId passed in, we let the caller decide when to commit.
640
+ // But then we can call getData() since the instance won't exist in the perspective
641
+ // until the bacht is committedl
642
+ if (batchCreatedHere) {
643
+ await this.perspective.commitBatch(batchId);
644
+ await this.getData();
645
+ }
646
+ }
647
+ cleanCopy() {
648
+ const cleanCopy = {};
649
+ const props = Object.entries(this);
650
+ for (const [key, value] of props) {
651
+ if (value !== undefined && value !== null && key !== "author" && key !== "timestamp") {
652
+ cleanCopy[key] = value;
653
+ }
654
+ }
655
+ return cleanCopy;
656
+ }
657
+ async innerUpdate(setProperties = true, batchId) {
658
+ __classPrivateFieldSet(this, _Ad4mModel_subjectClassName, await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").stringOrTemplateObjectToSubjectClassName(this.cleanCopy()), "f");
659
+ const entries = Object.entries(this);
660
+ for (const [key, value] of entries) {
661
+ if (value !== undefined && value !== null) {
662
+ if (value?.action) {
663
+ switch (value.action) {
664
+ case "setter":
665
+ await this.setCollectionSetter(key, value.value, batchId);
666
+ break;
667
+ case "adder":
668
+ await this.setCollectionAdder(key, value.value, batchId);
669
+ break;
670
+ case "remover":
671
+ await this.setCollectionRemover(key, value.value, batchId);
672
+ break;
673
+ default:
674
+ await this.setCollectionSetter(key, value.value, batchId);
675
+ break;
676
+ }
677
+ }
678
+ else if (Array.isArray(value) && value.length > 0) {
679
+ await this.setCollectionSetter(key, value, batchId);
680
+ }
681
+ else if (value !== undefined && value !== null && value !== "") {
682
+ if (setProperties) {
683
+ await this.setProperty(key, value, batchId);
684
+ }
685
+ }
686
+ }
687
+ }
688
+ }
689
+ /**
690
+ * Updates the model instance's properties and collections.
691
+ *
692
+ * @param batchId - Optional batch ID for batch operations
693
+ * @throws Will throw if property setting or collection updates fail
694
+ *
695
+ * @example
696
+ * ```typescript
697
+ * const recipe = await Recipe.findAll(perspective)[0];
698
+ * recipe.rating = 5;
699
+ * recipe.ingredients.push("garlic");
700
+ * await recipe.update();
701
+ *
702
+ * // Or with batch operations:
703
+ * const batchId = await perspective.createBatch();
704
+ * await recipe.update(batchId);
705
+ * await perspective.commitBatch(batchId);
706
+ * ```
707
+ */
708
+ async update(batchId) {
709
+ await this.innerUpdate(true, batchId);
710
+ await this.getData();
711
+ }
712
+ /**
713
+ * Gets the model instance with all properties and collections populated.
714
+ *
715
+ * @returns The populated model instance
716
+ * @throws Will throw if data retrieval fails
717
+ *
718
+ * @example
719
+ * ```typescript
720
+ * const recipe = new Recipe(perspective, existingId);
721
+ * await recipe.get();
722
+ * console.log(recipe.name, recipe.ingredients);
723
+ * ```
724
+ */
725
+ async get() {
726
+ __classPrivateFieldSet(this, _Ad4mModel_subjectClassName, await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").stringOrTemplateObjectToSubjectClassName(this.cleanCopy()), "f");
727
+ return await this.getData();
728
+ }
729
+ /**
730
+ * Deletes the model instance from the perspective.
731
+ *
732
+ * @param batchId - Optional batch ID for batch operations
733
+ * @throws Will throw if removal fails
734
+ *
735
+ * @example
736
+ * ```typescript
737
+ * const recipe = await Recipe.findAll(perspective)[0];
738
+ * await recipe.delete();
739
+ *
740
+ * // Or with batch operations:
741
+ * const batchId = await perspective.createBatch();
742
+ * await recipe.delete(batchId);
743
+ * await perspective.commitBatch(batchId);
744
+ * ```
745
+ */
746
+ async delete(batchId) {
747
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").removeSubject(this, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), batchId);
748
+ }
749
+ /**
750
+ * Creates a query builder for fluent query construction.
751
+ *
752
+ * @param perspective - The perspective to query
753
+ * @param query - Optional initial query parameters
754
+ * @returns A new query builder instance
755
+ *
756
+ * @example
757
+ * ```typescript
758
+ * const recipes = await Recipe.query(perspective)
759
+ * .where({ category: "Dessert" })
760
+ * .order({ rating: "DESC" })
761
+ * .limit(5)
762
+ * .run();
763
+ *
764
+ * // With real-time updates
765
+ * await Recipe.query(perspective)
766
+ * .where({ status: "cooking" })
767
+ * .subscribe(recipes => {
768
+ * console.log("Currently cooking:", recipes);
769
+ * });
770
+ * ```
771
+ */
772
+ static query(perspective, query) {
773
+ return new ModelQueryBuilder(perspective, this, query);
774
+ }
775
+ }
776
+ _Ad4mModel_baseExpression = new WeakMap(), _Ad4mModel_subjectClassName = new WeakMap(), _Ad4mModel_source = new WeakMap(), _Ad4mModel_perspective = new WeakMap();
777
+ Ad4mModel.classNamesByClass = new WeakMap();
778
+ /** Query builder for Ad4mModel queries.
779
+ * Allows building queries with a fluent interface and either running them once
780
+ * or subscribing to updates.
781
+ *
782
+ * @example
783
+ * ```typescript
784
+ * const builder = Recipe.query(perspective)
785
+ * .where({ category: "Dessert" })
786
+ * .order({ rating: "DESC" })
787
+ * .limit(10);
788
+ *
789
+ * // Run once
790
+ * const recipes = await builder.run();
791
+ *
792
+ * // Or subscribe to updates
793
+ * await builder.subscribe(recipes => {
794
+ * console.log("Updated recipes:", recipes);
795
+ * });
796
+ * ```
797
+ */
798
+ export class ModelQueryBuilder {
799
+ constructor(perspective, ctor, query) {
800
+ this.queryParams = {};
801
+ this.modelClassName = null;
802
+ this.perspective = perspective;
803
+ this.ctor = ctor;
804
+ if (query)
805
+ this.queryParams = query;
806
+ }
807
+ /**
808
+ * Disposes of the current subscription if one exists.
809
+ *
810
+ * This method:
811
+ * 1. Stops the keepalive signals to the subscription
812
+ * 2. Unsubscribes from GraphQL subscription updates
813
+ * 3. Notifies the backend to clean up subscription resources
814
+ * 4. Clears the subscription reference
815
+ *
816
+ * You should call this method when you're done with a subscription
817
+ * to prevent memory leaks and ensure proper cleanup.
818
+ */
819
+ dispose() {
820
+ if (this.currentSubscription) {
821
+ this.currentSubscription.dispose();
822
+ this.currentSubscription = undefined;
823
+ }
824
+ }
825
+ /**
826
+ * Adds where conditions to the query.
827
+ *
828
+ * @param conditions - The conditions to filter by
829
+ * @returns The query builder for chaining
830
+ *
831
+ * @example
832
+ * ```typescript
833
+ * .where({
834
+ * category: "Dessert",
835
+ * rating: { gt: 4 },
836
+ * tags: ["vegan", "quick"],
837
+ * published: true
838
+ * })
839
+ * ```
840
+ */
841
+ where(conditions) {
842
+ this.queryParams.where = conditions;
843
+ return this;
844
+ }
845
+ /**
846
+ * Sets the order for the query results.
847
+ *
848
+ * @param orderBy - The ordering criteria
849
+ * @returns The query builder for chaining
850
+ *
851
+ * @example
852
+ * ```typescript
853
+ * .order({ createdAt: "DESC" })
854
+ * ```
855
+ */
856
+ order(orderBy) {
857
+ this.queryParams.order = orderBy;
858
+ return this;
859
+ }
860
+ /**
861
+ * Sets the maximum number of results to return.
862
+ *
863
+ * @param limit - Maximum number of results
864
+ * @returns The query builder for chaining
865
+ *
866
+ * @example
867
+ * ```typescript
868
+ * .limit(10)
869
+ * ```
870
+ */
871
+ limit(limit) {
872
+ this.queryParams.limit = limit;
873
+ return this;
874
+ }
875
+ /**
876
+ * Sets the number of results to skip.
877
+ *
878
+ * @param offset - Number of results to skip
879
+ * @returns The query builder for chaining
880
+ *
881
+ * @example
882
+ * ```typescript
883
+ * .offset(20) // Skip first 20 results
884
+ * ```
885
+ */
886
+ offset(offset) {
887
+ this.queryParams.offset = offset;
888
+ return this;
889
+ }
890
+ /**
891
+ * Sets the source filter for the query.
892
+ *
893
+ * @param source - The source to filter by
894
+ * @returns The query builder for chaining
895
+ *
896
+ * @example
897
+ * ```typescript
898
+ * .source("ad4m://self")
899
+ * ```
900
+ */
901
+ source(source) {
902
+ this.queryParams.source = source;
903
+ return this;
904
+ }
905
+ /**
906
+ * Specifies which properties to include in the results.
907
+ *
908
+ * @param properties - Array of property names to include
909
+ * @returns The query builder for chaining
910
+ *
911
+ * @example
912
+ * ```typescript
913
+ * .properties(["name", "description", "rating"])
914
+ * ```
915
+ */
916
+ properties(properties) {
917
+ this.queryParams.properties = properties;
918
+ return this;
919
+ }
920
+ /**
921
+ * Specifies which collections to include in the results.
922
+ *
923
+ * @param collections - Array of collection names to include
924
+ * @returns The query builder for chaining
925
+ *
926
+ * @example
927
+ * ```typescript
928
+ * .collections(["ingredients", "steps"])
929
+ * ```
930
+ */
931
+ collections(collections) {
932
+ this.queryParams.collections = collections;
933
+ return this;
934
+ }
935
+ overrideModelClassName(className) {
936
+ this.modelClassName = className;
937
+ return this;
938
+ }
939
+ /**
940
+ * Executes the query once and returns the results.
941
+ *
942
+ * @returns Array of matching entities
943
+ *
944
+ * @example
945
+ * ```typescript
946
+ * const recipes = await Recipe.query(perspective)
947
+ * .where({ category: "Dessert" })
948
+ * .get();
949
+ * ```
950
+ */
951
+ async get() {
952
+ const query = await this.ctor.queryToProlog(this.perspective, this.queryParams);
953
+ const result = await this.perspective.infer(query);
954
+ const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
955
+ return results;
956
+ }
957
+ /**
958
+ * Subscribes to the query and receives updates when results change.
959
+ *
960
+ * This method:
961
+ * 1. Creates and initializes a Prolog query subscription
962
+ * 2. Sets up the callback to process future updates
963
+ * 3. Returns the initial results immediately
964
+ *
965
+ * Remember to call dispose() when you're done with the subscription
966
+ * to clean up resources.
967
+ *
968
+ * @param callback - Function to call with updated results
969
+ * @returns Initial results array
970
+ *
971
+ * @example
972
+ * ```typescript
973
+ * const builder = Recipe.query(perspective)
974
+ * .where({ status: "cooking" });
975
+ *
976
+ * const initialRecipes = await builder.subscribe(recipes => {
977
+ * console.log("Updated recipes:", recipes);
978
+ * });
979
+ *
980
+ * // When done with subscription:
981
+ * builder.dispose();
982
+ * ```
983
+ */
984
+ async subscribe(callback) {
985
+ // Clean up any existing subscription
986
+ this.dispose();
987
+ const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
988
+ this.currentSubscription = await this.perspective.subscribeInfer(query);
989
+ const processResults = async (result) => {
990
+ const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
991
+ callback(results);
992
+ };
993
+ this.currentSubscription.onResult(processResults);
994
+ const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, this.currentSubscription.result);
995
+ return results;
996
+ }
997
+ /**
998
+ * Gets the total count of matching entities.
999
+ *
1000
+ * @returns Total count
1001
+ *
1002
+ * @example
1003
+ * ```typescript
1004
+ * const totalDesserts = await Recipe.query(perspective)
1005
+ * .where({ category: "Dessert" })
1006
+ * .count();
1007
+ * ```
1008
+ */
1009
+ async count() {
1010
+ const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
1011
+ const result = await this.perspective.infer(query);
1012
+ return result?.[0]?.TotalCount || 0;
1013
+ }
1014
+ /**
1015
+ * Subscribes to count updates for matching entities.
1016
+ *
1017
+ * This method:
1018
+ * 1. Creates and initializes a Prolog query subscription for the count
1019
+ * 2. Sets up the callback to process future count updates
1020
+ * 3. Returns the initial count immediately
1021
+ *
1022
+ * Remember to call dispose() when you're done with the subscription
1023
+ * to clean up resources.
1024
+ *
1025
+ * @param callback - Function to call with updated count
1026
+ * @returns Initial count
1027
+ *
1028
+ * @example
1029
+ * ```typescript
1030
+ * const builder = Recipe.query(perspective)
1031
+ * .where({ status: "active" });
1032
+ *
1033
+ * const initialCount = await builder.countSubscribe(count => {
1034
+ * console.log("Active items:", count);
1035
+ * });
1036
+ *
1037
+ * // When done with subscription:
1038
+ * builder.dispose();
1039
+ * ```
1040
+ */
1041
+ async countSubscribe(callback) {
1042
+ // Clean up any existing subscription
1043
+ this.dispose();
1044
+ const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
1045
+ this.currentSubscription = await this.perspective.subscribeInfer(query);
1046
+ const processResults = async (result) => {
1047
+ const newCount = result?.[0]?.TotalCount || 0;
1048
+ callback(newCount);
1049
+ };
1050
+ this.currentSubscription.onResult(processResults);
1051
+ return this.currentSubscription.result?.[0]?.TotalCount || 0;
1052
+ }
1053
+ /**
1054
+ * Gets a page of results with pagination metadata.
1055
+ *
1056
+ * @param pageSize - Number of items per page
1057
+ * @param pageNumber - Which page to retrieve (1-based)
1058
+ * @returns Paginated results with metadata
1059
+ *
1060
+ * @example
1061
+ * ```typescript
1062
+ * const page = await Recipe.query(perspective)
1063
+ * .where({ category: "Main" })
1064
+ * .paginate(10, 1);
1065
+ * console.log(`Page ${page.pageNumber}, ${page.results.length} of ${page.totalCount}`);
1066
+ * ```
1067
+ */
1068
+ async paginate(pageSize, pageNumber) {
1069
+ const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
1070
+ const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
1071
+ const result = await this.perspective.infer(prologQuery);
1072
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, result));
1073
+ return { results, totalCount, pageSize, pageNumber };
1074
+ }
1075
+ /**
1076
+ * Subscribes to paginated results updates.
1077
+ *
1078
+ * This method:
1079
+ * 1. Creates and initializes a Prolog query subscription for the paginated results
1080
+ * 2. Sets up the callback to process future page updates
1081
+ * 3. Returns the initial page immediately
1082
+ *
1083
+ * Remember to call dispose() when you're done with the subscription
1084
+ * to clean up resources.
1085
+ *
1086
+ * @param pageSize - Number of items per page
1087
+ * @param pageNumber - Which page to retrieve (1-based)
1088
+ * @param callback - Function to call with updated pagination results
1089
+ * @returns Initial pagination results
1090
+ *
1091
+ * @example
1092
+ * ```typescript
1093
+ * const builder = Recipe.query(perspective)
1094
+ * .where({ category: "Main" });
1095
+ *
1096
+ * const initialPage = await builder.paginateSubscribe(10, 1, page => {
1097
+ * console.log("Updated page:", page.results);
1098
+ * });
1099
+ *
1100
+ * // When done with subscription:
1101
+ * builder.dispose();
1102
+ * ```
1103
+ */
1104
+ async paginateSubscribe(pageSize, pageNumber, callback) {
1105
+ // Clean up any existing subscription
1106
+ this.dispose();
1107
+ const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
1108
+ const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
1109
+ this.currentSubscription = await this.perspective.subscribeInfer(prologQuery);
1110
+ const processResults = async (r) => {
1111
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, r));
1112
+ callback({ results, totalCount, pageSize, pageNumber });
1113
+ };
1114
+ this.currentSubscription.onResult(processResults);
1115
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, this.currentSubscription.result));
1116
+ return { results, totalCount, pageSize, pageNumber };
1117
+ }
1118
+ }