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