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