@coasys/ad4m 0.12.0-rc1-dev.4 → 0.12.0-rc2

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 (166) hide show
  1. package/lib/index.cjs +5052 -4446
  2. package/lib/index.js +5019 -4442
  3. package/lib/src/agent/AgentClient.d.ts +4 -0
  4. package/lib/src/agent/AgentClient.js +34 -0
  5. package/lib/src/index.d.ts +2 -3
  6. package/lib/src/index.js +2 -3
  7. package/lib/src/model/Ad4mModel.d.ts +8 -782
  8. package/lib/src/model/Ad4mModel.js +160 -2354
  9. package/lib/src/model/ModelQueryBuilder.d.ts +370 -0
  10. package/lib/src/model/ModelQueryBuilder.js +556 -0
  11. package/lib/src/model/decorators.d.ts +71 -23
  12. package/lib/src/model/decorators.js +133 -384
  13. package/lib/src/model/hydration.d.ts +102 -0
  14. package/lib/src/model/hydration.js +709 -0
  15. package/lib/src/model/index.d.ts +20 -0
  16. package/lib/src/model/index.js +20 -0
  17. package/lib/src/model/{schema/fromJSONSchema.d.ts → json-schema.d.ts} +45 -12
  18. package/lib/src/model/json-schema.js +326 -0
  19. package/lib/src/model/prolog-facts.d.ts +37 -0
  20. package/lib/src/model/{prolog/generatePrologFacts.js → prolog-facts.js} +47 -52
  21. package/lib/src/model/query-common.d.ts +14 -0
  22. package/lib/src/model/query-common.js +36 -0
  23. package/lib/src/model/query-prolog.d.ts +15 -0
  24. package/lib/src/model/query-prolog.js +140 -0
  25. package/lib/src/model/query-surreal.d.ts +44 -0
  26. package/lib/src/model/query-surreal.js +249 -0
  27. package/lib/src/model/relation-filtering.test.js +838 -0
  28. package/lib/src/model/sdna.d.ts +14 -0
  29. package/lib/src/model/sdna.js +141 -0
  30. package/lib/src/model/shacl-gen.d.ts +31 -0
  31. package/lib/src/model/shacl-gen.js +246 -0
  32. package/lib/src/model/surreal-utils.d.ts +42 -0
  33. package/lib/src/model/surreal-utils.js +128 -0
  34. package/lib/src/model/types.d.ts +75 -96
  35. package/lib/src/model/types.js +4 -4
  36. package/lib/src/model/util.d.ts +4 -5
  37. package/lib/src/model/util.js +12 -32
  38. package/lib/src/perspectives/PerspectiveClient.d.ts +1 -1
  39. package/lib/src/perspectives/PerspectiveProxy.d.ts +1 -1
  40. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +79 -0
  41. package/lib/src/perspectives/WakerSubscriptionManager.js +196 -0
  42. package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
  43. package/lib/src/runtime/RuntimeResolver.js +73 -0
  44. package/lib/src/schema.gql +14 -0
  45. package/lib/src/shacl/SHACLShape.d.ts +23 -0
  46. package/lib/src/shacl/SHACLShape.js +45 -0
  47. package/lib/src/typeDefs.js +14 -0
  48. package/package.json +13 -8
  49. package/src/agent/AgentClient.ts +45 -0
  50. package/src/index.ts +2 -3
  51. package/src/model/Ad4mModel.ts +1089 -3686
  52. package/src/model/ModelQueryBuilder.ts +617 -0
  53. package/src/model/Subject.ts +1 -1
  54. package/src/model/decorators.ts +218 -453
  55. package/src/model/hydration.ts +796 -0
  56. package/src/model/index.ts +21 -0
  57. package/src/model/json-schema.ts +424 -0
  58. package/src/model/prolog-facts.ts +145 -0
  59. package/src/model/query-common.ts +48 -0
  60. package/src/model/query-prolog.ts +148 -0
  61. package/src/model/query-surreal.ts +280 -0
  62. package/src/model/relation-filtering.test.ts +803 -0
  63. package/src/model/sdna.ts +170 -0
  64. package/src/model/shacl-gen.ts +292 -0
  65. package/src/model/surreal-utils.ts +147 -0
  66. package/src/model/types.ts +182 -0
  67. package/src/model/util.ts +13 -36
  68. package/src/perspectives/PerspectiveClient.ts +1 -1
  69. package/src/perspectives/PerspectiveProxy.ts +1 -1
  70. package/src/perspectives/WakerSubscriptionManager.ts +292 -0
  71. package/src/runtime/RuntimeResolver.ts +53 -0
  72. package/src/shacl/SHACLShape.ts +83 -0
  73. package/lib/src/Ad4mClient.test.js +0 -1204
  74. package/lib/src/Literal.test.d.ts +0 -1
  75. package/lib/src/Literal.test.js +0 -41
  76. package/lib/src/model/mutation.d.ts +0 -81
  77. package/lib/src/model/mutation.js +0 -317
  78. package/lib/src/model/parentUtils.d.ts +0 -32
  79. package/lib/src/model/parentUtils.js +0 -64
  80. package/lib/src/model/prolog/generatePrologFacts.d.ts +0 -36
  81. package/lib/src/model/prolog/index.d.ts +0 -1
  82. package/lib/src/model/prolog/index.js +0 -1
  83. package/lib/src/model/query/ModelQueryBuilder.d.ts +0 -82
  84. package/lib/src/model/query/ModelQueryBuilder.js +0 -115
  85. package/lib/src/model/query/QueryBuilder.d.ts +0 -101
  86. package/lib/src/model/query/QueryBuilder.js +0 -193
  87. package/lib/src/model/query/SurrealQueryBuilder.d.ts +0 -48
  88. package/lib/src/model/query/SurrealQueryBuilder.js +0 -371
  89. package/lib/src/model/query/fetchInstance.d.ts +0 -24
  90. package/lib/src/model/query/fetchInstance.js +0 -144
  91. package/lib/src/model/query/hydration.d.ts +0 -54
  92. package/lib/src/model/query/hydration.js +0 -214
  93. package/lib/src/model/query/operations.d.ts +0 -59
  94. package/lib/src/model/query/operations.js +0 -384
  95. package/lib/src/model/query/snapshot.d.ts +0 -59
  96. package/lib/src/model/query/snapshot.js +0 -106
  97. package/lib/src/model/query/surrealCompiler.d.ts +0 -42
  98. package/lib/src/model/query/surrealCompiler.js +0 -304
  99. package/lib/src/model/schema/fromJSONSchema.js +0 -264
  100. package/lib/src/model/schema/metadata.d.ts +0 -15
  101. package/lib/src/model/schema/metadata.js +0 -112
  102. package/lib/src/model/subscription.d.ts +0 -47
  103. package/lib/src/model/subscription.js +0 -231
  104. package/lib/src/model/transaction.d.ts +0 -27
  105. package/lib/src/model/transaction.js +0 -32
  106. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  107. package/lib/src/shims/type-graphql.d.ts +0 -32
  108. package/lib/src/src/Ad4mClient.d.ts +0 -28
  109. package/lib/src/src/Address.d.ts +0 -1
  110. package/lib/src/src/DID.d.ts +0 -1
  111. package/lib/src/src/Exception.d.ts +0 -7
  112. package/lib/src/src/Literal.d.ts +0 -7
  113. package/lib/src/src/PubSub.d.ts +0 -17
  114. package/lib/src/src/SmartLiteral.d.ts +0 -12
  115. package/lib/src/src/agent/Agent.d.ts +0 -110
  116. package/lib/src/src/agent/AgentClient.d.ts +0 -62
  117. package/lib/src/src/agent/AgentResolver.d.ts +0 -30
  118. package/lib/src/src/agent/AgentStatus.d.ts +0 -8
  119. package/lib/src/src/ai/AIClient.d.ts +0 -32
  120. package/lib/src/src/ai/AIResolver.d.ts +0 -75
  121. package/lib/src/src/ai/Tasks.d.ts +0 -37
  122. package/lib/src/src/buildSchema.d.ts +0 -1
  123. package/lib/src/src/expression/Expression.d.ts +0 -28
  124. package/lib/src/src/expression/ExpressionClient.d.ts +0 -13
  125. package/lib/src/src/expression/ExpressionRef.d.ts +0 -9
  126. package/lib/src/src/expression/ExpressionResolver.d.ts +0 -10
  127. package/lib/src/src/index.d.ts +0 -35
  128. package/lib/src/src/jestSetup.d.ts +0 -1
  129. package/lib/src/src/language/Icon.d.ts +0 -4
  130. package/lib/src/src/language/Language.d.ts +0 -206
  131. package/lib/src/src/language/LanguageClient.d.ts +0 -17
  132. package/lib/src/src/language/LanguageContext.d.ts +0 -37
  133. package/lib/src/src/language/LanguageHandle.d.ts +0 -9
  134. package/lib/src/src/language/LanguageMeta.d.ts +0 -35
  135. package/lib/src/src/language/LanguageRef.d.ts +0 -6
  136. package/lib/src/src/language/LanguageResolver.d.ts +0 -19
  137. package/lib/src/src/links/Links.d.ts +0 -39
  138. package/lib/src/src/links/Links.test.d.ts +0 -1
  139. package/lib/src/src/model/Ad4mModel.d.ts +0 -1438
  140. package/lib/src/src/model/Ad4mModel.test.d.ts +0 -1
  141. package/lib/src/src/model/Subject.d.ts +0 -25
  142. package/lib/src/src/model/decorators.d.ts +0 -545
  143. package/lib/src/src/model/util.d.ts +0 -12
  144. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +0 -10
  145. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +0 -25
  146. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +0 -19
  147. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +0 -1
  148. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +0 -24
  149. package/lib/src/src/perspectives/LinkQuery.d.ts +0 -11
  150. package/lib/src/src/perspectives/Perspective.d.ts +0 -38
  151. package/lib/src/src/perspectives/Perspective.test.d.ts +0 -1
  152. package/lib/src/src/perspectives/PerspectiveClient.d.ts +0 -97
  153. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +0 -9
  154. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +0 -18
  155. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +0 -865
  156. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +0 -57
  157. package/lib/src/src/runtime/RuntimeClient.d.ts +0 -56
  158. package/lib/src/src/runtime/RuntimeResolver.d.ts +0 -132
  159. package/lib/src/src/shacl/SHACLFlow.d.ts +0 -171
  160. package/lib/src/src/shacl/SHACLFlow.test.d.ts +0 -1
  161. package/lib/src/src/shacl/SHACLShape.d.ts +0 -117
  162. package/lib/src/src/shacl/SHACLShape.test.d.ts +0 -1
  163. package/lib/src/src/typeDefs.d.ts +0 -1
  164. package/lib/src/src/unwrapApolloResult.d.ts +0 -2
  165. package/lib/src/src/utils.d.ts +0 -25
  166. /package/lib/src/{Ad4mClient.test.d.ts → model/relation-filtering.test.d.ts} +0 -0
@@ -0,0 +1,556 @@
1
+ /**
2
+ * ModelQueryBuilder — fluent query builder for Ad4mModel.
3
+ *
4
+ * Allows building queries with a chainable interface and either
5
+ * running them once or subscribing to real-time updates.
6
+ */
7
+ /** Query builder for Ad4mModel queries.
8
+ * Allows building queries with a fluent interface and either running them once
9
+ * or subscribing to updates.
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * const builder = Recipe.query(perspective)
14
+ * .where({ category: "Dessert" })
15
+ * .order({ rating: "DESC" })
16
+ * .limit(10);
17
+ *
18
+ * // Run once
19
+ * const recipes = await builder.run();
20
+ *
21
+ * // Or subscribe to updates
22
+ * await builder.subscribe(recipes => {
23
+ * console.log("Updated recipes:", recipes);
24
+ * });
25
+ * ```
26
+ */
27
+ export class ModelQueryBuilder {
28
+ constructor(perspective, ctor, query) {
29
+ this.queryParams = {};
30
+ this.modelClassName = null;
31
+ this.useSurrealDBFlag = true;
32
+ this.perspective = perspective;
33
+ this.ctor = ctor;
34
+ if (query)
35
+ this.queryParams = query;
36
+ }
37
+ /**
38
+ * Disposes of the current subscription if one exists.
39
+ *
40
+ * This method:
41
+ * 1. Stops the keepalive signals to the subscription
42
+ * 2. Unsubscribes from GraphQL subscription updates
43
+ * 3. Notifies the backend to clean up subscription resources
44
+ * 4. Clears the subscription reference
45
+ *
46
+ * You should call this method when you're done with a subscription
47
+ * to prevent memory leaks and ensure proper cleanup.
48
+ */
49
+ dispose() {
50
+ if (this.currentSubscription) {
51
+ this.currentSubscription.dispose();
52
+ this.currentSubscription = undefined;
53
+ }
54
+ }
55
+ /**
56
+ * Adds where conditions to the query.
57
+ *
58
+ * @param conditions - The conditions to filter by
59
+ * @returns The query builder for chaining
60
+ *
61
+ * @example
62
+ * ```typescript
63
+ * .where({
64
+ * category: "Dessert",
65
+ * rating: { gt: 4 },
66
+ * tags: ["vegan", "quick"],
67
+ * published: true
68
+ * })
69
+ * ```
70
+ */
71
+ where(conditions) {
72
+ this.queryParams.where = conditions;
73
+ return this;
74
+ }
75
+ /**
76
+ * Sets the order for the query results.
77
+ *
78
+ * @param orderBy - The ordering criteria
79
+ * @returns The query builder for chaining
80
+ *
81
+ * @example
82
+ * ```typescript
83
+ * .order({ createdAt: "DESC" })
84
+ * ```
85
+ */
86
+ order(orderBy) {
87
+ this.queryParams.order = orderBy;
88
+ return this;
89
+ }
90
+ /**
91
+ * Sets the maximum number of results to return.
92
+ *
93
+ * @param limit - Maximum number of results
94
+ * @returns The query builder for chaining
95
+ *
96
+ * @example
97
+ * ```typescript
98
+ * .limit(10)
99
+ * ```
100
+ */
101
+ limit(limit) {
102
+ this.queryParams.limit = limit;
103
+ return this;
104
+ }
105
+ /**
106
+ * Sets the number of results to skip.
107
+ *
108
+ * @param offset - Number of results to skip
109
+ * @returns The query builder for chaining
110
+ *
111
+ * @example
112
+ * ```typescript
113
+ * .offset(20) // Skip first 20 results
114
+ * ```
115
+ */
116
+ offset(offset) {
117
+ this.queryParams.offset = offset;
118
+ return this;
119
+ }
120
+ /**
121
+ * Scopes the query to instances linked from a parent.
122
+ *
123
+ * The predicate is resolved in order of precedence:
124
+ * 1. **Instance only** — the parent's constructor is used as the model
125
+ * class; its relation metadata is scanned for a relation whose
126
+ * `target()` matches the queried model class.
127
+ * 2. **Instance + options with `field`** — direct field-name lookup on
128
+ * the parent model's relation metadata (disambiguates when a parent
129
+ * has multiple relations targeting the same child class).
130
+ * 3. **String id + model class** — same metadata scan (or field lookup if
131
+ * options include `field`).
132
+ * 4. **String id + string predicate** — raw escape hatch, no metadata lookup.
133
+ *
134
+ * Passing a plain string id with no second argument throws because the
135
+ * predicate cannot be resolved without a model class.
136
+ *
137
+ * @param idOrInstance - The parent's expression URI **or** an Ad4mModel instance
138
+ * @param modelOrPredicate - A model class (predicate auto-resolved) **or** a raw predicate string
139
+ * @param options - Optional settings: `field` for direct relation-name lookup
140
+ * @returns The query builder for chaining
141
+ *
142
+ * @example
143
+ * ```typescript
144
+ * // Instance — predicate auto-resolved from Cookbook's @HasMany(() => Recipe)
145
+ * Recipe.query(perspective).parent(cookbook).get();
146
+ *
147
+ * // Instance + field — disambiguate when parent has multiple relations to same child
148
+ * Recipe.query(perspective).parent(cookbook, { field: "recipes" }).get();
149
+ *
150
+ * // String id + model class
151
+ * Recipe.query(perspective).parent(cookbookId, Cookbook).get();
152
+ *
153
+ * // String id + model class + field
154
+ * Recipe.query(perspective).parent(cookbookId, Cookbook, { field: "recipes" }).get();
155
+ *
156
+ * // String id + raw predicate (escape hatch)
157
+ * Recipe.query(perspective).parent(cookbookId, "cookbook://recipe").get();
158
+ * ```
159
+ */
160
+ parent(idOrInstance, modelOrPredicate, options) {
161
+ const id = typeof idOrInstance === 'string' ? idOrInstance : idOrInstance.id;
162
+ // Handle options-object as second arg: parent(instance, { field: "recipes" })
163
+ if (typeof modelOrPredicate === 'object' && modelOrPredicate !== null && !('prototype' in modelOrPredicate)) {
164
+ if (typeof idOrInstance === 'string') {
165
+ throw new Error('parent() called with a string id and options object requires a model class as second argument');
166
+ }
167
+ const model = idOrInstance.constructor;
168
+ this.queryParams.parent = { id, model, field: modelOrPredicate.field };
169
+ return this;
170
+ }
171
+ const field = options?.field;
172
+ if (typeof modelOrPredicate === 'string') {
173
+ // Raw predicate string → raw form of ParentScope
174
+ this.queryParams.parent = { id, predicate: modelOrPredicate };
175
+ }
176
+ else if (typeof modelOrPredicate === 'function') {
177
+ // Model class → model form of ParentScope
178
+ this.queryParams.parent = { id, model: modelOrPredicate, ...(field && { field }) };
179
+ }
180
+ else if (typeof idOrInstance !== 'string') {
181
+ // Ad4mModel instance — derive model class from constructor
182
+ this.queryParams.parent = { id, model: idOrInstance.constructor, ...(field && { field }) };
183
+ }
184
+ else {
185
+ throw new Error('parent() called with a string id requires a second argument: either a model class or a predicate string');
186
+ }
187
+ return this;
188
+ }
189
+ /**
190
+ * Specifies which properties to include in the results.
191
+ *
192
+ * @param properties - Array of property names to include
193
+ * @returns The query builder for chaining
194
+ *
195
+ * @example
196
+ * ```typescript
197
+ * .properties(["name", "description", "rating"])
198
+ * ```
199
+ */
200
+ properties(properties) {
201
+ this.queryParams.properties = properties;
202
+ return this;
203
+ }
204
+ /**
205
+ * Specifies which relations to eager-load (hydrate into model instances).
206
+ *
207
+ * Without `include`, relation fields contain raw expression URIs (strings).
208
+ * With `include`, the URIs are resolved into fully-hydrated model instances
209
+ * using the `target` class declared in the relation decorator.
210
+ *
211
+ * Supports nested includes for multi-level eager loading.
212
+ *
213
+ * @param map - An IncludeMap describing which relations to hydrate
214
+ * @returns The query builder for chaining
215
+ *
216
+ * @example
217
+ * ```typescript
218
+ * // Hydrate comments one level deep
219
+ * const recipes = await Recipe.query(perspective)
220
+ * .include({ comments: true })
221
+ * .run();
222
+ * // recipe.comments is now Comment[] (model instances), not string[]
223
+ *
224
+ * // Nested: hydrate comments AND each comment's author
225
+ * const recipes = await Recipe.query(perspective)
226
+ * .include({ comments: { author: true } })
227
+ * .run();
228
+ * ```
229
+ */
230
+ include(map) {
231
+ this.queryParams.include = map;
232
+ return this;
233
+ }
234
+ overrideModelClassName(className) {
235
+ this.modelClassName = className;
236
+ return this;
237
+ }
238
+ /**
239
+ * Enables or disables SurrealDB query path.
240
+ *
241
+ * @param enabled - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
242
+ * @returns The query builder for chaining
243
+ *
244
+ * @example
245
+ * ```typescript
246
+ * // Use SurrealDB (default)
247
+ * const recipes = await Recipe.query(perspective)
248
+ * .where({ category: "Dessert" })
249
+ * .useSurrealDB(true)
250
+ * .get();
251
+ *
252
+ * // Use Prolog (legacy)
253
+ * const recipesProlog = await Recipe.query(perspective)
254
+ * .where({ category: "Dessert" })
255
+ * .useSurrealDB(false)
256
+ * .get();
257
+ * ```
258
+ *
259
+ * @remarks
260
+ * Note: Subscriptions (subscribe(), countSubscribe(), paginateSubscribe()) default to SurrealDB live queries
261
+ * if useSurrealDB(true) is set (default).
262
+ */
263
+ useSurrealDB(enabled = true) {
264
+ this.useSurrealDBFlag = enabled;
265
+ return this;
266
+ }
267
+ /**
268
+ * Executes the query once and returns the results.
269
+ *
270
+ * @returns Array of matching entities
271
+ *
272
+ * @example
273
+ * ```typescript
274
+ * const recipes = await Recipe.query(perspective)
275
+ * .where({ category: "Dessert" })
276
+ * .get();
277
+ * ```
278
+ */
279
+ async get() {
280
+ let results;
281
+ if (this.useSurrealDBFlag) {
282
+ const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
283
+ const result = await this.perspective.querySurrealDB(surrealQuery);
284
+ ({ results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result));
285
+ }
286
+ else {
287
+ const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
288
+ const result = await this.perspective.infer(query);
289
+ ({ results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result));
290
+ }
291
+ return results;
292
+ }
293
+ /**
294
+ * Returns the first matching instance, or `null` if none match.
295
+ *
296
+ * Internally sets `limit: 1` and delegates to `get()`.
297
+ *
298
+ * @returns The first matching instance, or `null`
299
+ *
300
+ * @example
301
+ * ```typescript
302
+ * const recipe = await Recipe.query(perspective)
303
+ * .where({ name: "Pasta" })
304
+ * .first();
305
+ * ```
306
+ */
307
+ async first() {
308
+ this.queryParams.limit = 1;
309
+ const results = await this.get();
310
+ return results[0] ?? null;
311
+ }
312
+ /**
313
+ * Subscribes to the query and receives updates when results change.
314
+ *
315
+ * This method:
316
+ * 1. Creates and initializes a SurrealDB live query subscription (default)
317
+ * 2. Sets up the callback to process future updates
318
+ * 3. Returns the initial results immediately
319
+ *
320
+ * Remember to call dispose() when you're done with the subscription
321
+ * to clean up resources.
322
+ *
323
+ * @param callback - Function to call with updated results
324
+ * @returns Initial results array
325
+ *
326
+ * @example
327
+ * ```typescript
328
+ * const builder = Recipe.query(perspective)
329
+ * .where({ status: "cooking" });
330
+ *
331
+ * const initialRecipes = await builder.subscribe(recipes => {
332
+ * console.log("Updated recipes:", recipes);
333
+ * });
334
+ *
335
+ * // When done with subscription:
336
+ * builder.dispose();
337
+ * ```
338
+ *
339
+ * @remarks
340
+ * By default, this uses SurrealDB live queries for real-time updates.
341
+ * Prolog subscriptions remain available via `.useSurrealDB(false)`.
342
+ */
343
+ async subscribe(callback) {
344
+ // Clean up any existing subscription
345
+ this.dispose();
346
+ const ctor = this.ctor;
347
+ if (this.useSurrealDBFlag) {
348
+ const surrealQuery = await ctor.queryToSurrealQL(this.perspective, this.queryParams);
349
+ this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
350
+ const processResults = async (result) => {
351
+ const { results } = await ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
352
+ callback(results);
353
+ };
354
+ this.currentSubscription.onResult(processResults);
355
+ // Process initial result
356
+ const { results } = await ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
357
+ // Also invoke callback with initial results so subscribers see them
358
+ callback(results);
359
+ return results;
360
+ }
361
+ else {
362
+ const query = await ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
363
+ this.currentSubscription = await this.perspective.subscribeInfer(query);
364
+ const processResults = async (result) => {
365
+ const { results } = await ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
366
+ callback(results);
367
+ };
368
+ this.currentSubscription.onResult(processResults);
369
+ const { results } = await ctor.instancesFromPrologResult(this.perspective, this.queryParams, this.currentSubscription.result);
370
+ // Also invoke callback with initial results so subscribers see them
371
+ callback(results);
372
+ return results;
373
+ }
374
+ }
375
+ /**
376
+ * Gets the total count of matching entities.
377
+ *
378
+ * @returns Total count
379
+ *
380
+ * @example
381
+ * ```typescript
382
+ * const totalDesserts = await Recipe.query(perspective)
383
+ * .where({ category: "Dessert" })
384
+ * .count();
385
+ * ```
386
+ */
387
+ async count() {
388
+ if (this.useSurrealDBFlag) {
389
+ const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
390
+ const result = await this.perspective.querySurrealDB(surrealQuery);
391
+ // Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
392
+ // (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
393
+ // This ensures count() returns the same number as get().length
394
+ const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
395
+ return totalCount;
396
+ }
397
+ else {
398
+ const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
399
+ const result = await this.perspective.infer(query);
400
+ return result?.[0]?.TotalCount || 0;
401
+ }
402
+ }
403
+ /**
404
+ * Subscribes to count updates for matching entities.
405
+ *
406
+ * This method:
407
+ * 1. Creates and initializes a SurrealDB live query subscription for the count (default)
408
+ * 2. Sets up the callback to process future count updates
409
+ * 3. Returns the initial count immediately
410
+ *
411
+ * Remember to call dispose() when you're done with the subscription
412
+ * to clean up resources.
413
+ *
414
+ * @param callback - Function to call with updated count
415
+ * @returns Initial count
416
+ *
417
+ * @example
418
+ * ```typescript
419
+ * const builder = Recipe.query(perspective)
420
+ * .where({ status: "active" });
421
+ *
422
+ * const initialCount = await builder.countSubscribe(count => {
423
+ * console.log("Active items:", count);
424
+ * });
425
+ *
426
+ * // When done with subscription:
427
+ * builder.dispose();
428
+ * ```
429
+ *
430
+ * @remarks
431
+ * By default, this uses SurrealDB live queries for real-time updates.
432
+ * Prolog subscriptions remain available via `.useSurrealDB(false)`.
433
+ */
434
+ async countSubscribe(callback) {
435
+ // Clean up any existing subscription
436
+ this.dispose();
437
+ if (this.useSurrealDBFlag) {
438
+ const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
439
+ this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
440
+ const processResults = async (result) => {
441
+ const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
442
+ callback(totalCount);
443
+ };
444
+ this.currentSubscription.onResult(processResults);
445
+ const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
446
+ callback(totalCount);
447
+ return totalCount;
448
+ }
449
+ else {
450
+ const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
451
+ this.currentSubscription = await this.perspective.subscribeInfer(query);
452
+ const processResults = async (result) => {
453
+ const newCount = result?.[0]?.TotalCount || 0;
454
+ callback(newCount);
455
+ };
456
+ this.currentSubscription.onResult(processResults);
457
+ const initialCount = this.currentSubscription.result?.[0]?.TotalCount || 0;
458
+ callback(initialCount);
459
+ return initialCount;
460
+ }
461
+ }
462
+ /**
463
+ * Gets a page of results with pagination metadata.
464
+ *
465
+ * @param pageSize - Number of items per page
466
+ * @param pageNumber - Which page to retrieve (1-based)
467
+ * @returns Paginated results with metadata
468
+ *
469
+ * @example
470
+ * ```typescript
471
+ * const page = await Recipe.query(perspective)
472
+ * .where({ category: "Main" })
473
+ * .paginate(10, 1);
474
+ * console.log(`Page ${page.pageNumber}, ${page.results.length} of ${page.totalCount}`);
475
+ * ```
476
+ */
477
+ async paginate(pageSize, pageNumber) {
478
+ const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
479
+ if (this.useSurrealDBFlag) {
480
+ const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
481
+ const result = await this.perspective.querySurrealDB(surrealQuery);
482
+ const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result));
483
+ return { results, totalCount, pageSize, pageNumber };
484
+ }
485
+ else {
486
+ const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
487
+ const result = await this.perspective.infer(prologQuery);
488
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, result));
489
+ return { results, totalCount, pageSize, pageNumber };
490
+ }
491
+ }
492
+ /**
493
+ * Subscribes to paginated results updates.
494
+ *
495
+ * This method:
496
+ * 1. Creates and initializes a SurrealDB live query subscription for the paginated results (default)
497
+ * 2. Sets up the callback to process future page updates
498
+ * 3. Returns the initial page immediately
499
+ *
500
+ * Remember to call dispose() when you're done with the subscription
501
+ * to clean up resources.
502
+ *
503
+ * @param pageSize - Number of items per page
504
+ * @param pageNumber - Which page to retrieve (1-based)
505
+ * @param callback - Function to call with updated pagination results
506
+ * @returns Initial pagination results
507
+ *
508
+ * @example
509
+ * ```typescript
510
+ * const builder = Recipe.query(perspective)
511
+ * .where({ category: "Main" });
512
+ *
513
+ * const initialPage = await builder.paginateSubscribe(10, 1, page => {
514
+ * console.log("Updated page:", page.results);
515
+ * });
516
+ *
517
+ * // When done with subscription:
518
+ * builder.dispose();
519
+ * ```
520
+ *
521
+ * @remarks
522
+ * By default, this uses SurrealDB live queries for real-time updates.
523
+ * Prolog subscriptions remain available via `.useSurrealDB(false)`.
524
+ */
525
+ async paginateSubscribe(pageSize, pageNumber, callback) {
526
+ // Clean up any existing subscription
527
+ this.dispose();
528
+ const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
529
+ if (this.useSurrealDBFlag) {
530
+ const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
531
+ this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
532
+ const processResults = async (result) => {
533
+ const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result));
534
+ callback({ results, totalCount, pageSize, pageNumber });
535
+ };
536
+ this.currentSubscription.onResult(processResults);
537
+ const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, this.currentSubscription.result));
538
+ const initialPage = { results, totalCount, pageSize, pageNumber };
539
+ callback(initialPage);
540
+ return initialPage;
541
+ }
542
+ else {
543
+ const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
544
+ this.currentSubscription = await this.perspective.subscribeInfer(prologQuery);
545
+ const processResults = async (r) => {
546
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, r));
547
+ callback({ results, totalCount, pageSize, pageNumber });
548
+ };
549
+ this.currentSubscription.onResult(processResults);
550
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, this.currentSubscription.result));
551
+ const initialPrologPage = { results, totalCount, pageSize, pageNumber };
552
+ callback(initialPrologPage);
553
+ return initialPrologPage;
554
+ }
555
+ }
556
+ }