@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,1048 @@
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
+ // Get or create the cache for this class
254
+ let classCache = this.classNamesByClass.get(this);
255
+ if (!classCache) {
256
+ classCache = {};
257
+ this.classNamesByClass.set(this, classCache);
258
+ }
259
+ // Get or create the cached name for this perspective
260
+ const perspectiveID = perspective.uuid;
261
+ if (!classCache[perspectiveID]) {
262
+ classCache[perspectiveID] = await perspective.stringOrTemplateObjectToSubjectClassName(this);
263
+ }
264
+ return classCache[perspectiveID];
265
+ }
266
+ /**
267
+ * Constructs a new model instance.
268
+ *
269
+ * @param perspective - The perspective where this model will be stored
270
+ * @param baseExpression - Optional unique identifier for this instance
271
+ * @param source - Optional source expression this instance is linked to
272
+ *
273
+ * @example
274
+ * ```typescript
275
+ * // Create a new recipe with auto-generated base expression
276
+ * const recipe = new Recipe(perspective);
277
+ *
278
+ * // Create with specific base expression
279
+ * const recipe = new Recipe(perspective, "recipe://chocolate-cake");
280
+ *
281
+ * // Create with source link
282
+ * const recipe = new Recipe(perspective, undefined, "cookbook://desserts");
283
+ * ```
284
+ */
285
+ constructor(perspective, baseExpression, source) {
286
+ _Ad4mModel_baseExpression.set(this, void 0);
287
+ _Ad4mModel_subjectClassName.set(this, void 0);
288
+ _Ad4mModel_source.set(this, void 0);
289
+ _Ad4mModel_perspective.set(this, void 0);
290
+ __classPrivateFieldSet(this, _Ad4mModel_baseExpression, baseExpression ? baseExpression : Literal.from(makeRandomPrologAtom(24)).toUrl(), "f");
291
+ __classPrivateFieldSet(this, _Ad4mModel_perspective, perspective, "f");
292
+ __classPrivateFieldSet(this, _Ad4mModel_source, source || "ad4m://self", "f");
293
+ }
294
+ /**
295
+ * Gets the base expression of the subject.
296
+ */
297
+ get baseExpression() {
298
+ return __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f");
299
+ }
300
+ /**
301
+ * Protected getter for the perspective.
302
+ * Allows subclasses to access the perspective while keeping it private from external code.
303
+ */
304
+ get perspective() {
305
+ return __classPrivateFieldGet(this, _Ad4mModel_perspective, "f");
306
+ }
307
+ static async assignValuesToInstance(perspective, instance, values) {
308
+ // Map properties to object
309
+ const propsObject = Object.fromEntries(await Promise.all(values.map(async ([name, value, resolve]) => {
310
+ let finalValue = value;
311
+ // Resolve the value if necessary
312
+ if (resolve) {
313
+ let resolvedExpression = await perspective.getExpression(value);
314
+ if (resolvedExpression) {
315
+ finalValue = resolvedExpression.data;
316
+ }
317
+ }
318
+ // Apply transform function if it exists
319
+ const transform = instance["__properties"]?.[name]?.transform;
320
+ if (transform && typeof transform === "function") {
321
+ finalValue = transform(finalValue);
322
+ }
323
+ return [name, finalValue];
324
+ })));
325
+ // Assign properties to instance
326
+ Object.assign(instance, propsObject);
327
+ }
328
+ async getData() {
329
+ // Builds an object with the author, timestamp, all properties, & all collections on the Ad4mModel and saves it to the instance
330
+ const subQueries = [buildAuthorAndTimestampQuery(), buildPropertiesQuery(), buildCollectionsQuery()];
331
+ const fullQuery = `
332
+ Base = "${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}",
333
+ subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", SubjectClass),
334
+ ${subQueries.join(", ")}
335
+ `;
336
+ const result = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(fullQuery);
337
+ if (result?.[0]) {
338
+ const { Properties, Collections, Timestamp, Author } = result?.[0];
339
+ const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
340
+ await Ad4mModel.assignValuesToInstance(__classPrivateFieldGet(this, _Ad4mModel_perspective, "f"), this, values);
341
+ }
342
+ return this;
343
+ }
344
+ // Todo: Only return AllInstances (InstancesWithOffset, SortedInstances, & UnsortedInstances not required)
345
+ static async queryToProlog(perspective, query, modelClassName) {
346
+ const { source, properties, collections, where, order, offset, limit, count } = query;
347
+ const className = modelClassName || (await this.getClassName(perspective));
348
+ const instanceQueries = [
349
+ buildAuthorAndTimestampQuery(),
350
+ buildSourceQuery(source),
351
+ buildPropertiesQuery(properties),
352
+ buildCollectionsQuery(collections),
353
+ buildWhereQuery(where),
354
+ ];
355
+ const resultSetQueries = [buildCountQuery(count), buildOrderQuery(order), buildOffsetQuery(offset), buildLimitQuery(limit)];
356
+ const fullQuery = `
357
+ findall([Base, Properties, Collections, Timestamp, Author], (
358
+ subject_class("${className}", SubjectClass),
359
+ instance(SubjectClass, Base),
360
+ ${instanceQueries.filter((q) => q).join(", ")}
361
+ ), UnsortedInstances),
362
+ ${resultSetQueries.filter((q) => q).join(", ")}
363
+ `;
364
+ return fullQuery;
365
+ }
366
+ static async instancesFromPrologResult(perspective, query, result) {
367
+ if (!result?.[0]?.AllInstances)
368
+ return { results: [], totalCount: 0 };
369
+ // Map results to instances
370
+ const requestedAttribtes = [...(query?.properties || []), ...(query?.collections || [])];
371
+ const allInstances = await Promise.all(result[0].AllInstances.map(async ([Base, Properties, Collections, Timestamp, Author]) => {
372
+ try {
373
+ const instance = new this(perspective, Base);
374
+ // Remove unrequested attributes from instance
375
+ if (requestedAttribtes.length) {
376
+ Object.keys(instance).forEach((key) => {
377
+ if (!requestedAttribtes.includes(key))
378
+ delete instance[key];
379
+ });
380
+ }
381
+ // Collect values to assign to instance
382
+ const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
383
+ await Ad4mModel.assignValuesToInstance(perspective, instance, values);
384
+ return instance;
385
+ }
386
+ catch (error) {
387
+ console.error(`Failed to process instance ${Base}:`, error);
388
+ // Return null for failed instances - we'll filter these out below
389
+ return null;
390
+ }
391
+ }));
392
+ return { results: allInstances.filter((instance) => instance !== null), totalCount: result[0].TotalCount };
393
+ }
394
+ /**
395
+ * Gets all instances of the model in the perspective that match the query params.
396
+ *
397
+ * @param perspective - The perspective to search in
398
+ * @param query - Optional query parameters to filter results
399
+ * @returns Array of matching models
400
+ *
401
+ * @example
402
+ * ```typescript
403
+ * // Get all recipes
404
+ * const allRecipes = await Recipe.findAll(perspective);
405
+ *
406
+ * // Get recipes with specific criteria
407
+ * const recipes = await Recipe.findAll(perspective, {
408
+ * where: {
409
+ * name: "Pasta",
410
+ * rating: { gt: 4 }
411
+ * },
412
+ * order: { createdAt: "DESC" },
413
+ * limit: 10
414
+ * });
415
+ * ```
416
+ */
417
+ static async findAll(perspective, query = {}) {
418
+ const prologQuery = await this.queryToProlog(perspective, query);
419
+ const result = await perspective.infer(prologQuery);
420
+ const { results } = await this.instancesFromPrologResult(perspective, query, result);
421
+ return results;
422
+ }
423
+ /**
424
+ * Gets all instances with count of total matches without offset & limit applied.
425
+ *
426
+ * @param perspective - The perspective to search in
427
+ * @param query - Optional query parameters to filter results
428
+ * @returns Object containing results array and total count
429
+ *
430
+ * @example
431
+ * ```typescript
432
+ * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {
433
+ * where: { category: "Dessert" },
434
+ * limit: 10
435
+ * });
436
+ * console.log(`Showing 10 of ${totalCount} dessert recipes`);
437
+ * ```
438
+ */
439
+ static async findAllAndCount(perspective, query = {}) {
440
+ const prologQuery = await this.queryToProlog(perspective, query);
441
+ const result = await perspective.infer(prologQuery);
442
+ return await this.instancesFromPrologResult(perspective, query, result);
443
+ }
444
+ /**
445
+ * Helper function for pagination with explicit page size and number.
446
+ *
447
+ * @param perspective - The perspective to search in
448
+ * @param pageSize - Number of items per page
449
+ * @param pageNumber - Which page to retrieve (1-based)
450
+ * @param query - Optional additional query parameters
451
+ * @returns Paginated results with metadata
452
+ *
453
+ * @example
454
+ * ```typescript
455
+ * const page = await Recipe.paginate(perspective, 10, 1, {
456
+ * where: { category: "Main Course" }
457
+ * });
458
+ * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
459
+ * ```
460
+ */
461
+ static async paginate(perspective, pageSize, pageNumber, query) {
462
+ const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
463
+ const prologQuery = await this.queryToProlog(perspective, paginationQuery);
464
+ const result = await perspective.infer(prologQuery);
465
+ const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
466
+ return { results, totalCount, pageSize, pageNumber };
467
+ }
468
+ static async countQueryToProlog(perspective, query = {}, modelClassName) {
469
+ const { source, where } = query;
470
+ const className = modelClassName || (await this.getClassName(perspective));
471
+ const instanceQueries = [buildAuthorAndTimestampQuery(), buildSourceQuery(source), buildWhereQuery(where)];
472
+ const resultSetQueries = [buildCountQuery(true), buildOrderQuery(), buildOffsetQuery(), buildLimitQuery()];
473
+ const fullQuery = `
474
+ findall([Base, Properties, Collections, Timestamp, Author], (
475
+ subject_class("${className}", SubjectClass),
476
+ instance(SubjectClass, Base),
477
+ ${instanceQueries.filter((q) => q).join(", ")}
478
+ ), UnsortedInstances),
479
+ ${resultSetQueries.filter((q) => q).join(", ")}
480
+ `;
481
+ return fullQuery;
482
+ }
483
+ /**
484
+ * Gets a count of all matching instances.
485
+ *
486
+ * @param perspective - The perspective to search in
487
+ * @param query - Optional query parameters to filter results
488
+ * @returns Total count of matching entities
489
+ *
490
+ * @example
491
+ * ```typescript
492
+ * const totalRecipes = await Recipe.count(perspective);
493
+ * const activeRecipes = await Recipe.count(perspective, {
494
+ * where: { status: "active" }
495
+ * });
496
+ * ```
497
+ */
498
+ static async count(perspective, query = {}) {
499
+ const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
500
+ return result?.[0]?.TotalCount || 0;
501
+ }
502
+ async setProperty(key, value, batchId) {
503
+ const setters = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), property_setter(C, "${key}", Setter)`);
504
+ if (setters && setters.length > 0) {
505
+ const actions = eval(setters[0].Setter);
506
+ const resolveLanguageResults = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), property_resolve_language(C, "${key}", Language)`);
507
+ let resolveLanguage;
508
+ if (resolveLanguageResults && resolveLanguageResults.length > 0) {
509
+ resolveLanguage = resolveLanguageResults[0].Language;
510
+ }
511
+ if (resolveLanguage) {
512
+ value = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").createExpression(value, resolveLanguage);
513
+ }
514
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
515
+ }
516
+ }
517
+ async setCollectionSetter(key, value, batchId) {
518
+ let collectionSetters = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), collection_setter(C, "${singularToPlural(key)}", Setter)`);
519
+ if (!collectionSetters)
520
+ collectionSetters = [];
521
+ if (collectionSetters.length > 0) {
522
+ const actions = eval(collectionSetters[0].Setter);
523
+ if (value) {
524
+ if (Array.isArray(value)) {
525
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), value.map((v) => ({ name: "value", value: v })), batchId);
526
+ }
527
+ else {
528
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
529
+ }
530
+ }
531
+ }
532
+ }
533
+ async setCollectionAdder(key, value, batchId) {
534
+ let adders = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), collection_adder(C, "${singularToPlural(key)}", Adder)`);
535
+ if (!adders)
536
+ adders = [];
537
+ if (adders.length > 0) {
538
+ const actions = eval(adders[0].Adder);
539
+ if (value) {
540
+ if (Array.isArray(value)) {
541
+ await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
542
+ }
543
+ else {
544
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
545
+ }
546
+ }
547
+ }
548
+ }
549
+ async setCollectionRemover(key, value, batchId) {
550
+ let removers = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), collection_remover(C, "${singularToPlural(key)}", Remover)`);
551
+ if (!removers)
552
+ removers = [];
553
+ if (removers.length > 0) {
554
+ const actions = eval(removers[0].Remover);
555
+ if (value) {
556
+ if (Array.isArray(value)) {
557
+ await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
558
+ }
559
+ else {
560
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
561
+ }
562
+ }
563
+ }
564
+ }
565
+ /**
566
+ * Saves the model instance to the perspective.
567
+ * Creates a new instance with the base expression and links it to the source.
568
+ *
569
+ * @param batchId - Optional batch ID for batch operations
570
+ * @throws Will throw if instance creation, linking, or updating fails
571
+ *
572
+ * @example
573
+ * ```typescript
574
+ * const recipe = new Recipe(perspective);
575
+ * recipe.name = "Spaghetti";
576
+ * recipe.ingredients = ["pasta", "tomato sauce"];
577
+ * await recipe.save();
578
+ *
579
+ * // Or with batch operations:
580
+ * const batchId = await perspective.createBatch();
581
+ * await recipe.save(batchId);
582
+ * await perspective.commitBatch(batchId);
583
+ * ```
584
+ */
585
+ async save(batchId) {
586
+ // We use createSubject's initialValues to set properties (but not collections)
587
+ // We then later use innerUpdate to set collections
588
+ // First filter out the properties that are not collections (arrays)
589
+ const initialValues = {};
590
+ for (const [key, value] of Object.entries(this)) {
591
+ if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {
592
+ initialValues[key] = value;
593
+ }
594
+ }
595
+ // Create the subject with the initial values
596
+ await this.perspective.createSubject(this, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), initialValues, batchId);
597
+ // Link the subject to the source
598
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").add(new Link({ source: __classPrivateFieldGet(this, _Ad4mModel_source, "f"), predicate: "ad4m://has_child", target: this.baseExpression }), 'shared', batchId);
599
+ // Set collections
600
+ await this.innerUpdate(false, batchId);
601
+ // If we're in batch mode, we don't need to do anything else
602
+ // since the instance won't exist until batch commit
603
+ if (batchId) {
604
+ return;
605
+ }
606
+ await this.getData();
607
+ }
608
+ async innerUpdate(setProperties = true, batchId) {
609
+ __classPrivateFieldSet(this, _Ad4mModel_subjectClassName, await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").stringOrTemplateObjectToSubjectClassName(this), "f");
610
+ const entries = Object.entries(this);
611
+ for (const [key, value] of entries) {
612
+ if (value !== undefined && value !== null) {
613
+ if (value?.action) {
614
+ switch (value.action) {
615
+ case "setter":
616
+ await this.setCollectionSetter(key, value.value, batchId);
617
+ break;
618
+ case "adder":
619
+ await this.setCollectionAdder(key, value.value, batchId);
620
+ break;
621
+ case "remover":
622
+ await this.setCollectionRemover(key, value.value, batchId);
623
+ break;
624
+ default:
625
+ await this.setCollectionSetter(key, value.value, batchId);
626
+ break;
627
+ }
628
+ }
629
+ else if (Array.isArray(value) && value.length > 0) {
630
+ await this.setCollectionSetter(key, value, batchId);
631
+ }
632
+ else if (value !== undefined && value !== null && value !== "") {
633
+ if (setProperties) {
634
+ await this.setProperty(key, value, batchId);
635
+ }
636
+ }
637
+ }
638
+ }
639
+ }
640
+ /**
641
+ * Updates the model instance's properties and collections.
642
+ *
643
+ * @param batchId - Optional batch ID for batch operations
644
+ * @throws Will throw if property setting or collection updates fail
645
+ *
646
+ * @example
647
+ * ```typescript
648
+ * const recipe = await Recipe.findAll(perspective)[0];
649
+ * recipe.rating = 5;
650
+ * recipe.ingredients.push("garlic");
651
+ * await recipe.update();
652
+ *
653
+ * // Or with batch operations:
654
+ * const batchId = await perspective.createBatch();
655
+ * await recipe.update(batchId);
656
+ * await perspective.commitBatch(batchId);
657
+ * ```
658
+ */
659
+ async update(batchId) {
660
+ await this.innerUpdate(true, batchId);
661
+ await this.getData();
662
+ }
663
+ /**
664
+ * Gets the model instance with all properties and collections populated.
665
+ *
666
+ * @returns The populated model instance
667
+ * @throws Will throw if data retrieval fails
668
+ *
669
+ * @example
670
+ * ```typescript
671
+ * const recipe = new Recipe(perspective, existingId);
672
+ * await recipe.get();
673
+ * console.log(recipe.name, recipe.ingredients);
674
+ * ```
675
+ */
676
+ async get() {
677
+ __classPrivateFieldSet(this, _Ad4mModel_subjectClassName, await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").stringOrTemplateObjectToSubjectClassName(this), "f");
678
+ return await this.getData();
679
+ }
680
+ /**
681
+ * Deletes the model instance from the perspective.
682
+ *
683
+ * @param batchId - Optional batch ID for batch operations
684
+ * @throws Will throw if removal fails
685
+ *
686
+ * @example
687
+ * ```typescript
688
+ * const recipe = await Recipe.findAll(perspective)[0];
689
+ * await recipe.delete();
690
+ *
691
+ * // Or with batch operations:
692
+ * const batchId = await perspective.createBatch();
693
+ * await recipe.delete(batchId);
694
+ * await perspective.commitBatch(batchId);
695
+ * ```
696
+ */
697
+ async delete(batchId) {
698
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").removeSubject(this, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), batchId);
699
+ }
700
+ /**
701
+ * Creates a query builder for fluent query construction.
702
+ *
703
+ * @param perspective - The perspective to query
704
+ * @param query - Optional initial query parameters
705
+ * @returns A new query builder instance
706
+ *
707
+ * @example
708
+ * ```typescript
709
+ * const recipes = await Recipe.query(perspective)
710
+ * .where({ category: "Dessert" })
711
+ * .order({ rating: "DESC" })
712
+ * .limit(5)
713
+ * .run();
714
+ *
715
+ * // With real-time updates
716
+ * await Recipe.query(perspective)
717
+ * .where({ status: "cooking" })
718
+ * .subscribe(recipes => {
719
+ * console.log("Currently cooking:", recipes);
720
+ * });
721
+ * ```
722
+ */
723
+ static query(perspective, query) {
724
+ return new ModelQueryBuilder(perspective, this, query);
725
+ }
726
+ }
727
+ _Ad4mModel_baseExpression = new WeakMap(), _Ad4mModel_subjectClassName = new WeakMap(), _Ad4mModel_source = new WeakMap(), _Ad4mModel_perspective = new WeakMap();
728
+ Ad4mModel.classNamesByClass = new WeakMap();
729
+ /** Query builder for Ad4mModel queries.
730
+ * Allows building queries with a fluent interface and either running them once
731
+ * or subscribing to updates.
732
+ *
733
+ * @example
734
+ * ```typescript
735
+ * const builder = Recipe.query(perspective)
736
+ * .where({ category: "Dessert" })
737
+ * .order({ rating: "DESC" })
738
+ * .limit(10);
739
+ *
740
+ * // Run once
741
+ * const recipes = await builder.run();
742
+ *
743
+ * // Or subscribe to updates
744
+ * await builder.subscribe(recipes => {
745
+ * console.log("Updated recipes:", recipes);
746
+ * });
747
+ * ```
748
+ */
749
+ export class ModelQueryBuilder {
750
+ constructor(perspective, ctor, query) {
751
+ this.queryParams = {};
752
+ this.modelClassName = null;
753
+ this.perspective = perspective;
754
+ this.ctor = ctor;
755
+ if (query)
756
+ this.queryParams = query;
757
+ }
758
+ /**
759
+ * Adds where conditions to the query.
760
+ *
761
+ * @param conditions - The conditions to filter by
762
+ * @returns The query builder for chaining
763
+ *
764
+ * @example
765
+ * ```typescript
766
+ * .where({
767
+ * category: "Dessert",
768
+ * rating: { gt: 4 },
769
+ * tags: ["vegan", "quick"],
770
+ * published: true
771
+ * })
772
+ * ```
773
+ */
774
+ where(conditions) {
775
+ this.queryParams.where = conditions;
776
+ return this;
777
+ }
778
+ /**
779
+ * Sets the order for the query results.
780
+ *
781
+ * @param orderBy - The ordering criteria
782
+ * @returns The query builder for chaining
783
+ *
784
+ * @example
785
+ * ```typescript
786
+ * .order({ createdAt: "DESC" })
787
+ * ```
788
+ */
789
+ order(orderBy) {
790
+ this.queryParams.order = orderBy;
791
+ return this;
792
+ }
793
+ /**
794
+ * Sets the maximum number of results to return.
795
+ *
796
+ * @param limit - Maximum number of results
797
+ * @returns The query builder for chaining
798
+ *
799
+ * @example
800
+ * ```typescript
801
+ * .limit(10)
802
+ * ```
803
+ */
804
+ limit(limit) {
805
+ this.queryParams.limit = limit;
806
+ return this;
807
+ }
808
+ /**
809
+ * Sets the number of results to skip.
810
+ *
811
+ * @param offset - Number of results to skip
812
+ * @returns The query builder for chaining
813
+ *
814
+ * @example
815
+ * ```typescript
816
+ * .offset(20) // Skip first 20 results
817
+ * ```
818
+ */
819
+ offset(offset) {
820
+ this.queryParams.offset = offset;
821
+ return this;
822
+ }
823
+ /**
824
+ * Sets the source filter for the query.
825
+ *
826
+ * @param source - The source to filter by
827
+ * @returns The query builder for chaining
828
+ *
829
+ * @example
830
+ * ```typescript
831
+ * .source("ad4m://self")
832
+ * ```
833
+ */
834
+ source(source) {
835
+ this.queryParams.source = source;
836
+ return this;
837
+ }
838
+ /**
839
+ * Specifies which properties to include in the results.
840
+ *
841
+ * @param properties - Array of property names to include
842
+ * @returns The query builder for chaining
843
+ *
844
+ * @example
845
+ * ```typescript
846
+ * .properties(["name", "description", "rating"])
847
+ * ```
848
+ */
849
+ properties(properties) {
850
+ this.queryParams.properties = properties;
851
+ return this;
852
+ }
853
+ /**
854
+ * Specifies which collections to include in the results.
855
+ *
856
+ * @param collections - Array of collection names to include
857
+ * @returns The query builder for chaining
858
+ *
859
+ * @example
860
+ * ```typescript
861
+ * .collections(["ingredients", "steps"])
862
+ * ```
863
+ */
864
+ collections(collections) {
865
+ this.queryParams.collections = collections;
866
+ return this;
867
+ }
868
+ overrideModelClassName(className) {
869
+ this.modelClassName = className;
870
+ return this;
871
+ }
872
+ /**
873
+ * Executes the query once and returns the results.
874
+ *
875
+ * @returns Array of matching entities
876
+ *
877
+ * @example
878
+ * ```typescript
879
+ * const recipes = await Recipe.query(perspective)
880
+ * .where({ category: "Dessert" })
881
+ * .get();
882
+ * ```
883
+ */
884
+ async get() {
885
+ const query = await this.ctor.queryToProlog(this.perspective, this.queryParams);
886
+ const result = await this.perspective.infer(query);
887
+ const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
888
+ return results;
889
+ }
890
+ /**
891
+ * Subscribes to the query and receives updates when results change.
892
+ *
893
+ * This method:
894
+ * 1. Creates and initializes a Prolog query subscription
895
+ * 2. Sets up the callback to process future updates
896
+ * 3. Returns the initial results immediately
897
+ *
898
+ * The subscription is guaranteed to be ready when this method returns,
899
+ * as it waits for the initialization process to complete.
900
+ *
901
+ * @param callback - Function to call with updated results
902
+ * @returns Initial results array
903
+ *
904
+ * @example
905
+ * ```typescript
906
+ * // Subscribe to cooking recipes
907
+ * const initialRecipes = await Recipe.query(perspective)
908
+ * .where({ status: "cooking" })
909
+ * .subscribe(recipes => {
910
+ * // This callback will be called with future updates
911
+ * console.log("Currently cooking:", recipes);
912
+ * });
913
+ *
914
+ * // initialRecipes contains the current state
915
+ * console.log("Initial recipes:", initialRecipes);
916
+ * ```
917
+ */
918
+ async subscribe(callback) {
919
+ const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
920
+ const subscription = await this.perspective.subscribeInfer(query);
921
+ const processResults = async (result) => {
922
+ const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
923
+ callback(results);
924
+ };
925
+ subscription.onResult(processResults);
926
+ const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, subscription.result);
927
+ return results;
928
+ }
929
+ /**
930
+ * Gets the total count of matching entities.
931
+ *
932
+ * @returns Total count
933
+ *
934
+ * @example
935
+ * ```typescript
936
+ * const totalDesserts = await Recipe.query(perspective)
937
+ * .where({ category: "Dessert" })
938
+ * .count();
939
+ * ```
940
+ */
941
+ async count() {
942
+ const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
943
+ const result = await this.perspective.infer(query);
944
+ return result?.[0]?.TotalCount || 0;
945
+ }
946
+ /**
947
+ * Subscribes to count updates for matching entities.
948
+ *
949
+ * This method:
950
+ * 1. Creates and initializes a Prolog query subscription for the count
951
+ * 2. Sets up the callback to process future count updates
952
+ * 3. Returns the initial count immediately
953
+ *
954
+ * The subscription is guaranteed to be ready when this method returns,
955
+ * as it waits for the initialization process to complete.
956
+ *
957
+ * @param callback - Function to call with updated count
958
+ * @returns Initial count
959
+ *
960
+ * @example
961
+ * ```typescript
962
+ * // Subscribe to active recipe count
963
+ * const initialCount = await Recipe.query(perspective)
964
+ * .where({ status: "active" })
965
+ * .countSubscribe(count => {
966
+ * // This callback will be called when the count changes
967
+ * console.log("Active items:", count);
968
+ * });
969
+ *
970
+ * // initialCount contains the current count
971
+ * console.log("Initial count:", initialCount);
972
+ * ```
973
+ */
974
+ async countSubscribe(callback) {
975
+ const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
976
+ const subscription = await this.perspective.subscribeInfer(query);
977
+ const processResults = async (result) => {
978
+ const newCount = result?.[0]?.TotalCount || 0;
979
+ callback(newCount);
980
+ };
981
+ subscription.onResult(processResults);
982
+ return subscription.result?.[0]?.TotalCount || 0;
983
+ }
984
+ /**
985
+ * Gets a page of results with pagination metadata.
986
+ *
987
+ * @param pageSize - Number of items per page
988
+ * @param pageNumber - Which page to retrieve (1-based)
989
+ * @returns Paginated results with metadata
990
+ *
991
+ * @example
992
+ * ```typescript
993
+ * const page = await Recipe.query(perspective)
994
+ * .where({ category: "Main" })
995
+ * .paginate(10, 1);
996
+ * console.log(`Page ${page.pageNumber}, ${page.results.length} of ${page.totalCount}`);
997
+ * ```
998
+ */
999
+ async paginate(pageSize, pageNumber) {
1000
+ const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
1001
+ const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
1002
+ const result = await this.perspective.infer(prologQuery);
1003
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, result));
1004
+ return { results, totalCount, pageSize, pageNumber };
1005
+ }
1006
+ /**
1007
+ * Subscribes to paginated results updates.
1008
+ *
1009
+ * This method:
1010
+ * 1. Creates and initializes a Prolog query subscription for the paginated results
1011
+ * 2. Sets up the callback to process future page updates
1012
+ * 3. Returns the initial page immediately
1013
+ *
1014
+ * The subscription is guaranteed to be ready when this method returns,
1015
+ * as it waits for the initialization process to complete.
1016
+ *
1017
+ * @param pageSize - Number of items per page
1018
+ * @param pageNumber - Which page to retrieve (1-based)
1019
+ * @param callback - Function to call with updated pagination results
1020
+ * @returns Initial pagination results
1021
+ *
1022
+ * @example
1023
+ * ```typescript
1024
+ * // Subscribe to first page of main recipes
1025
+ * const initialPage = await Recipe.query(perspective)
1026
+ * .where({ category: "Main" })
1027
+ * .paginateSubscribe(10, 1, page => {
1028
+ * // This callback will be called when the page content changes
1029
+ * console.log("Updated page:", page.results);
1030
+ * });
1031
+ *
1032
+ * // initialPage contains the current page state
1033
+ * console.log("Initial page:", initialPage.results);
1034
+ * ```
1035
+ */
1036
+ async paginateSubscribe(pageSize, pageNumber, callback) {
1037
+ const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
1038
+ const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
1039
+ const subscription = await this.perspective.subscribeInfer(prologQuery);
1040
+ const processResults = async (r) => {
1041
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, r));
1042
+ callback({ results, totalCount, pageSize, pageNumber });
1043
+ };
1044
+ subscription.onResult(processResults);
1045
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, subscription.result));
1046
+ return { results, totalCount, pageSize, pageNumber };
1047
+ }
1048
+ }