@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
|
@@ -1,214 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Shared instance hydration utilities for Ad4mModel.
|
|
3
|
-
*
|
|
4
|
-
* Both `getData()` (single-instance path) and `instancesFromSurrealResult()`
|
|
5
|
-
* (bulk path) delegate to `hydrateInstanceFromLinks()` and
|
|
6
|
-
* `evaluateCustomGetters()` here, guaranteeing identical semantics.
|
|
7
|
-
*
|
|
8
|
-
* Previously the two implementations diverged — most notably, `getData()` used
|
|
9
|
-
* "latest-wins" for properties while `instancesFromSurrealResult()` used
|
|
10
|
-
* "first-wins". Both now use latest-wins (last ASC-ordered link per predicate).
|
|
11
|
-
*/
|
|
12
|
-
import { Literal } from "../../Literal";
|
|
13
|
-
import { formatSurrealValue } from "./surrealCompiler";
|
|
14
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
15
|
-
// Helpers
|
|
16
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
17
|
-
/**
|
|
18
|
-
* Normalise a SurrealDB timestamp to epoch-milliseconds.
|
|
19
|
-
*
|
|
20
|
-
* - ISO strings (`"2024-01-01T00:00:00Z"`) → `Date.getTime()`
|
|
21
|
-
* - Numeric strings (`"1700000000000"`) → `parseInt`
|
|
22
|
-
* - Numbers → returned as-is
|
|
23
|
-
* - Anything else → returned as-is (no data loss)
|
|
24
|
-
*/
|
|
25
|
-
export function normalizeTimestamp(ts) {
|
|
26
|
-
if (typeof ts === "number")
|
|
27
|
-
return ts;
|
|
28
|
-
if (typeof ts === "string") {
|
|
29
|
-
if (ts.includes("T")) {
|
|
30
|
-
const ms = new Date(ts).getTime();
|
|
31
|
-
return isNaN(ms) ? ts : ms;
|
|
32
|
-
}
|
|
33
|
-
const parsed = parseInt(ts, 10);
|
|
34
|
-
return isNaN(parsed) ? ts : parsed;
|
|
35
|
-
}
|
|
36
|
-
return ts;
|
|
37
|
-
}
|
|
38
|
-
/**
|
|
39
|
-
* Resolve a raw SurrealDB link target to a typed JavaScript value.
|
|
40
|
-
*
|
|
41
|
-
* Resolution order:
|
|
42
|
-
* 1. Non-literal `resolveLanguage` → `perspective.getExpression(target)`
|
|
43
|
-
* 2. `literal://` URL → `Literal.fromUrl(target).get().data`
|
|
44
|
-
* 3. Otherwise → raw string unchanged
|
|
45
|
-
*/
|
|
46
|
-
async function resolveValue(raw, resolveLanguage, perspective, propName) {
|
|
47
|
-
// Non-literal language: fetch the expression via the perspective
|
|
48
|
-
if (resolveLanguage &&
|
|
49
|
-
resolveLanguage !== "literal" &&
|
|
50
|
-
typeof raw === "string" &&
|
|
51
|
-
!raw.startsWith("literal://")) {
|
|
52
|
-
try {
|
|
53
|
-
const expression = await perspective.getExpression(raw);
|
|
54
|
-
if (expression) {
|
|
55
|
-
try {
|
|
56
|
-
return JSON.parse(expression.data);
|
|
57
|
-
}
|
|
58
|
-
catch {
|
|
59
|
-
return expression.data;
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
catch (e) {
|
|
64
|
-
console.warn(`Failed to resolve expression for ${propName}:`, e);
|
|
65
|
-
}
|
|
66
|
-
return raw;
|
|
67
|
-
}
|
|
68
|
-
// Literal URL: parse inline — only when resolveLanguage is 'literal' or unset.
|
|
69
|
-
// A property with a non-literal resolveLanguage whose stored target happens to
|
|
70
|
-
// start with 'literal://' (e.g. a model baseExpression URI stored as a string
|
|
71
|
-
// property value) must NOT be unwrapped here, or the URI itself is destroyed.
|
|
72
|
-
// Note: unlike the old monolithic Ad4mModel.ts, ALL scalar values in our
|
|
73
|
-
// mutation layer are stored as literal:// (when they have no URI scheme), so
|
|
74
|
-
// resolveLanguage === undefined is the normal case for plain string/number props.
|
|
75
|
-
if ((resolveLanguage === "literal" || resolveLanguage === undefined) &&
|
|
76
|
-
typeof raw === "string" &&
|
|
77
|
-
raw.startsWith("literal://")) {
|
|
78
|
-
try {
|
|
79
|
-
const parsed = Literal.fromUrl(raw).get();
|
|
80
|
-
return parsed.data !== undefined ? parsed.data : parsed;
|
|
81
|
-
}
|
|
82
|
-
catch {
|
|
83
|
-
// fall through to raw
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
return raw;
|
|
87
|
-
}
|
|
88
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
89
|
-
// Public API
|
|
90
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
91
|
-
/**
|
|
92
|
-
* Hydrates a model instance from a flat array of raw SurrealDB link rows.
|
|
93
|
-
*
|
|
94
|
-
* **Guarantees:**
|
|
95
|
-
* - Properties use *"latest-wins"* semantics — links must be ordered
|
|
96
|
-
* `ASC` by `timestamp`; the last matching link per predicate wins.
|
|
97
|
-
* - Forward relations preserve insertion order (links already ASC).
|
|
98
|
-
* - `createdAt` / `updatedAt` / `author` are derived from the global
|
|
99
|
-
* min/max timestamps across **all** links (not just property links).
|
|
100
|
-
*
|
|
101
|
-
* **Does NOT handle** (left to the caller):
|
|
102
|
-
* - Reverse relations — require a separate `WHERE out.uri = $base` query.
|
|
103
|
-
* - Custom getter evaluation — call `evaluateCustomGetters()` afterwards.
|
|
104
|
-
* - `relatedModel` eager hydration — do that in a batch pass afterwards.
|
|
105
|
-
*/
|
|
106
|
-
export async function hydrateInstanceFromLinks(instance, links, metadata, perspective) {
|
|
107
|
-
if (!links || links.length === 0)
|
|
108
|
-
return;
|
|
109
|
-
// ── Global timestamp / author tracking ─────────────────────────────────────
|
|
110
|
-
// Normalise to epoch-ms so numeric and ISO timestamps compare correctly.
|
|
111
|
-
let minTimestamp = null;
|
|
112
|
-
let maxTimestamp = null;
|
|
113
|
-
let originalAuthor = null;
|
|
114
|
-
for (const link of links) {
|
|
115
|
-
const ts = link.timestamp;
|
|
116
|
-
if (ts == null)
|
|
117
|
-
continue;
|
|
118
|
-
const t = Number(normalizeTimestamp(ts));
|
|
119
|
-
if (isNaN(t))
|
|
120
|
-
continue;
|
|
121
|
-
if (minTimestamp === null || t < minTimestamp) {
|
|
122
|
-
minTimestamp = t;
|
|
123
|
-
originalAuthor = link.author ?? null;
|
|
124
|
-
}
|
|
125
|
-
if (maxTimestamp === null || t > maxTimestamp) {
|
|
126
|
-
maxTimestamp = t;
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
// ── Properties ──────────────────────────────────────────────────────────────
|
|
130
|
-
// Links are ordered ASC by timestamp; the LAST match is the most recent value.
|
|
131
|
-
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
132
|
-
if (propMeta.getter)
|
|
133
|
-
continue; // handled separately by evaluateCustomGetters
|
|
134
|
-
const matching = links.filter((l) => l.predicate === propMeta.predicate && l.target !== "None");
|
|
135
|
-
if (matching.length === 0)
|
|
136
|
-
continue;
|
|
137
|
-
const link = matching[matching.length - 1]; // latest wins
|
|
138
|
-
let value = await resolveValue(link.target, propMeta.resolveLanguage, perspective, propName);
|
|
139
|
-
if (propMeta.transform && typeof propMeta.transform === "function") {
|
|
140
|
-
value = propMeta.transform(value);
|
|
141
|
-
}
|
|
142
|
-
instance[propName] = value;
|
|
143
|
-
}
|
|
144
|
-
// ── Forward relations ───────────────────────────────────────────────────────
|
|
145
|
-
// Collect targets in their natural (ASC timestamp) order; filter None/empty.
|
|
146
|
-
const forwardRelations = Object.entries(metadata.relations).filter(([, m]) => !m.getter && m.direction !== "reverse");
|
|
147
|
-
for (const [relationName, relMeta] of forwardRelations) {
|
|
148
|
-
const matching = links.filter((l) => l.predicate === relMeta.predicate);
|
|
149
|
-
const values = matching
|
|
150
|
-
.map((l) => l.target)
|
|
151
|
-
.filter((v) => v !== undefined && v !== null && v !== "" && v !== "None");
|
|
152
|
-
// maxCount === 1: take first value (oldest) — "@HasOne" has only one link
|
|
153
|
-
// in the happy path; "first" vs "last" only differs in error/corrupt state.
|
|
154
|
-
instance[relationName] =
|
|
155
|
-
relMeta.maxCount === 1 ? (values[0] ?? null) : values;
|
|
156
|
-
}
|
|
157
|
-
// ── Author & timestamps ──────────────────────────────────────────────────────
|
|
158
|
-
if (originalAuthor)
|
|
159
|
-
instance.author = originalAuthor;
|
|
160
|
-
if (minTimestamp !== null)
|
|
161
|
-
instance.createdAt = normalizeTimestamp(minTimestamp);
|
|
162
|
-
if (maxTimestamp !== null)
|
|
163
|
-
instance.updatedAt = normalizeTimestamp(maxTimestamp);
|
|
164
|
-
}
|
|
165
|
-
/**
|
|
166
|
-
* Evaluates custom SurrealQL getter expressions for all `getter`-decorated
|
|
167
|
-
* properties and relations on a single model instance.
|
|
168
|
-
*
|
|
169
|
-
* Called by both `getData()` (single-instance path) and
|
|
170
|
-
* `instancesFromSurrealResult()` (bulk path) — single implementation so
|
|
171
|
-
* neither path can diverge.
|
|
172
|
-
*/
|
|
173
|
-
export async function evaluateCustomGetters(instance, perspective, metadata) {
|
|
174
|
-
const safeBase = formatSurrealValue(instance.id);
|
|
175
|
-
// Property getters
|
|
176
|
-
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
177
|
-
if (!propMeta.getter)
|
|
178
|
-
continue;
|
|
179
|
-
try {
|
|
180
|
-
const query = propMeta.getter.replace(/Base/g, safeBase);
|
|
181
|
-
const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBase}`);
|
|
182
|
-
if (result?.length > 0 &&
|
|
183
|
-
result[0].value !== undefined &&
|
|
184
|
-
result[0].value !== null &&
|
|
185
|
-
result[0].value !== "None" &&
|
|
186
|
-
result[0].value !== "") {
|
|
187
|
-
instance[propName] = result[0].value;
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
catch (error) {
|
|
191
|
-
console.warn(`Failed to evaluate getter for ${propName}:`, error);
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
// Relation getters
|
|
195
|
-
for (const [relationName, relMeta] of Object.entries(metadata.relations)) {
|
|
196
|
-
if (!relMeta.getter)
|
|
197
|
-
continue;
|
|
198
|
-
try {
|
|
199
|
-
const query = relMeta.getter.replace(/Base/g, safeBase);
|
|
200
|
-
const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBase}`);
|
|
201
|
-
if (result?.length > 0 &&
|
|
202
|
-
result[0].value !== undefined &&
|
|
203
|
-
result[0].value !== null) {
|
|
204
|
-
const value = result[0].value;
|
|
205
|
-
instance[relationName] = Array.isArray(value)
|
|
206
|
-
? value.filter((v) => v !== undefined && v !== null && v !== "" && v !== "None")
|
|
207
|
-
: value;
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
catch (error) {
|
|
211
|
-
console.warn(`Failed to evaluate getter for ${relationName}:`, error);
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
}
|
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Static query operations for Ad4mModel.
|
|
3
|
-
*
|
|
4
|
-
* Extracted from Ad4mModel.ts (Phase 3a Part 3). Every function here is a
|
|
5
|
-
* pure-static helper that takes a model constructor (`ctor`) as its first
|
|
6
|
-
* argument instead of relying on `this`. Ad4mModel wraps each one with a
|
|
7
|
-
* thin static method so the public API is completely unchanged.
|
|
8
|
-
*
|
|
9
|
-
* The `Ad4mModelCtor<T>` type is imported (type-only) from QueryBuilder so
|
|
10
|
-
* there is no runtime circular dependency.
|
|
11
|
-
*/
|
|
12
|
-
import type { PerspectiveProxy } from "../../perspectives/PerspectiveProxy";
|
|
13
|
-
import type { Query, ResultsWithTotalCount, PaginationResult } from "../types";
|
|
14
|
-
import type { Ad4mModelCtor } from "./ModelQueryBuilder";
|
|
15
|
-
/**
|
|
16
|
-
* Translates a high-level {@link Query} object to a SurrealQL string.
|
|
17
|
-
*
|
|
18
|
-
* @param ctor - The Ad4mModel subclass (provides getModelMetadata)
|
|
19
|
-
* @param perspective - Not used for query building but kept for API symmetry
|
|
20
|
-
* @param query - High-level query parameters
|
|
21
|
-
*/
|
|
22
|
-
export declare function queryToSurrealQL(ctor: Ad4mModelCtor<any>, _perspective: PerspectiveProxy, query: Query): Promise<string>;
|
|
23
|
-
/**
|
|
24
|
-
* Translates a high-level {@link Query} object to a SurrealQL COUNT string.
|
|
25
|
-
*/
|
|
26
|
-
export declare function countQueryToSurrealQL(ctor: Ad4mModelCtor<any>, _perspective: PerspectiveProxy, query: Query): Promise<string>;
|
|
27
|
-
/**
|
|
28
|
-
* Converts raw SurrealDB result rows to hydrated Ad4mModel instances.
|
|
29
|
-
*
|
|
30
|
-
* This is the single-pass pipeline that:
|
|
31
|
-
* 1. Creates a model instance for each `source_uri` row
|
|
32
|
-
* 2. Hydrates properties, forward relations, author and timestamps
|
|
33
|
-
* 3. Fetches reverse-relation links in one batch query
|
|
34
|
-
* 4. Batch-hydrates nested `relatedModel` relations (no N+1)
|
|
35
|
-
* 5. Evaluates custom SurrealQL getters
|
|
36
|
-
* 6. Post-filters and sorts in JS for operators that SurrealDB can't handle
|
|
37
|
-
* 7. Applies offset/limit pagination
|
|
38
|
-
*
|
|
39
|
-
* @internal
|
|
40
|
-
*/
|
|
41
|
-
export declare function instancesFromSurrealResult<T>(ctor: Ad4mModelCtor<T>, perspective: PerspectiveProxy, query: Query, result: any[], _hydrateRelations?: boolean): Promise<ResultsWithTotalCount<T>>;
|
|
42
|
-
/**
|
|
43
|
-
* Internal findAll used by the public static and by eager-hydration depth-guards.
|
|
44
|
-
* Pass `_hydrateRelations = false` to prevent recursive nested-model hydration.
|
|
45
|
-
*/
|
|
46
|
-
export declare function _findAllInternal<T>(ctor: Ad4mModelCtor<T>, perspective: PerspectiveProxy, query?: Query, _hydrateRelations?: boolean): Promise<T[]>;
|
|
47
|
-
/** Returns all matching instances. */
|
|
48
|
-
export declare function findAll<T>(ctor: Ad4mModelCtor<T>, perspective: PerspectiveProxy, query: Query): Promise<T[]>;
|
|
49
|
-
/** Returns the first matching instance, or `null` if none found. */
|
|
50
|
-
export declare function findOne<T>(ctor: Ad4mModelCtor<T>, perspective: PerspectiveProxy, query: Query): Promise<T | null>;
|
|
51
|
-
/** Returns all matching instances together with the total unfilterd count. */
|
|
52
|
-
export declare function findAllAndCount<T>(ctor: Ad4mModelCtor<T>, perspective: PerspectiveProxy, query: Query): Promise<ResultsWithTotalCount<T>>;
|
|
53
|
-
/**
|
|
54
|
-
* Paginates results given an explicit page size and 1-based page number.
|
|
55
|
-
* Returns metadata needed to render pagination controls.
|
|
56
|
-
*/
|
|
57
|
-
export declare function paginate<T>(ctor: Ad4mModelCtor<T>, perspective: PerspectiveProxy, pageSize: number, pageNumber: number, query: Query): Promise<PaginationResult<T>>;
|
|
58
|
-
/** Returns a count of all matching instances. */
|
|
59
|
-
export declare function count(ctor: Ad4mModelCtor<any>, perspective: PerspectiveProxy, query: Query): Promise<number>;
|
|
@@ -1,384 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Static query operations for Ad4mModel.
|
|
3
|
-
*
|
|
4
|
-
* Extracted from Ad4mModel.ts (Phase 3a Part 3). Every function here is a
|
|
5
|
-
* pure-static helper that takes a model constructor (`ctor`) as its first
|
|
6
|
-
* argument instead of relying on `this`. Ad4mModel wraps each one with a
|
|
7
|
-
* thin static method so the public API is completely unchanged.
|
|
8
|
-
*
|
|
9
|
-
* The `Ad4mModelCtor<T>` type is imported (type-only) from QueryBuilder so
|
|
10
|
-
* there is no runtime circular dependency.
|
|
11
|
-
*/
|
|
12
|
-
import { buildSurrealQuery, buildSurrealCountQuery, matchesCondition, } from "./surrealCompiler";
|
|
13
|
-
import { hydrateInstanceFromLinks, evaluateCustomGetters } from "./hydration";
|
|
14
|
-
import { captureSnapshot } from "./snapshot";
|
|
15
|
-
import { escapeSurrealString } from "../../utils";
|
|
16
|
-
import { normalizeParentQuery } from "../parentUtils";
|
|
17
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
18
|
-
// Query-to-SurrealQL helpers
|
|
19
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
20
|
-
/**
|
|
21
|
-
* Translates a high-level {@link Query} object to a SurrealQL string.
|
|
22
|
-
*
|
|
23
|
-
* @param ctor - The Ad4mModel subclass (provides getModelMetadata)
|
|
24
|
-
* @param perspective - Not used for query building but kept for API symmetry
|
|
25
|
-
* @param query - High-level query parameters
|
|
26
|
-
*/
|
|
27
|
-
export async function queryToSurrealQL(ctor, _perspective, query) {
|
|
28
|
-
const normalizedQuery = query.parent
|
|
29
|
-
? { ...query, parent: normalizeParentQuery(query.parent, ctor) }
|
|
30
|
-
: query;
|
|
31
|
-
return buildSurrealQuery(ctor.getModelMetadata(), normalizedQuery);
|
|
32
|
-
}
|
|
33
|
-
/**
|
|
34
|
-
* Translates a high-level {@link Query} object to a SurrealQL COUNT string.
|
|
35
|
-
*/
|
|
36
|
-
export async function countQueryToSurrealQL(ctor, _perspective, query) {
|
|
37
|
-
const normalizedQuery = query.parent
|
|
38
|
-
? { ...query, parent: normalizeParentQuery(query.parent, ctor) }
|
|
39
|
-
: query;
|
|
40
|
-
return buildSurrealCountQuery(ctor.getModelMetadata(), normalizedQuery);
|
|
41
|
-
}
|
|
42
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
43
|
-
// instancesFromSurrealResult — the core hydration/assembly pipeline
|
|
44
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
45
|
-
/**
|
|
46
|
-
* Converts raw SurrealDB result rows to hydrated Ad4mModel instances.
|
|
47
|
-
*
|
|
48
|
-
* This is the single-pass pipeline that:
|
|
49
|
-
* 1. Creates a model instance for each `source_uri` row
|
|
50
|
-
* 2. Hydrates properties, forward relations, author and timestamps
|
|
51
|
-
* 3. Fetches reverse-relation links in one batch query
|
|
52
|
-
* 4. Batch-hydrates nested `relatedModel` relations (no N+1)
|
|
53
|
-
* 5. Evaluates custom SurrealQL getters
|
|
54
|
-
* 6. Post-filters and sorts in JS for operators that SurrealDB can't handle
|
|
55
|
-
* 7. Applies offset/limit pagination
|
|
56
|
-
*
|
|
57
|
-
* @internal
|
|
58
|
-
*/
|
|
59
|
-
export async function instancesFromSurrealResult(ctor, perspective, query, result, _hydrateRelations = true) {
|
|
60
|
-
if (!result || result.length === 0)
|
|
61
|
-
return { results: [], totalCount: 0 };
|
|
62
|
-
const metadata = ctor.getModelMetadata();
|
|
63
|
-
const requestedProperties = query?.properties || [];
|
|
64
|
-
// ── 0. Pre-validate the `properties` option ───────────────────────────────
|
|
65
|
-
//
|
|
66
|
-
// An empty array is disallowed: it almost certainly indicates a bug in the
|
|
67
|
-
// caller (a computed list that produced no entries). Pass `undefined` or
|
|
68
|
-
// omit the field entirely to get all properties.
|
|
69
|
-
//
|
|
70
|
-
// This check is BEFORE the row loop so the error propagates to the caller
|
|
71
|
-
// instead of being swallowed by the per-row try/catch.
|
|
72
|
-
if (query?.properties !== undefined && requestedProperties.length === 0) {
|
|
73
|
-
throw new Error("Ad4mModel: properties[] must not be empty. Omit the field to retrieve all properties.");
|
|
74
|
-
}
|
|
75
|
-
// ── 1. Build instances from rows ──────────────────────────────────────────────────
|
|
76
|
-
const instances = [];
|
|
77
|
-
for (const row of result) {
|
|
78
|
-
try {
|
|
79
|
-
const base = row.source_uri;
|
|
80
|
-
if (!base)
|
|
81
|
-
continue;
|
|
82
|
-
const links = row.links || [];
|
|
83
|
-
const instance = new ctor(perspective, base);
|
|
84
|
-
// Shared hydration: properties + forward relations + author + timestamps
|
|
85
|
-
await hydrateInstanceFromLinks(instance, links, metadata, perspective);
|
|
86
|
-
// If the query asked for specific properties only, strip schema-declared
|
|
87
|
-
// fields that weren't requested. We only touch fields that are declared in
|
|
88
|
-
// the schema (via @Property / relation decorators) plus the well-known
|
|
89
|
-
// metadata fields (author, createdAt, updatedAt). Internal machinery such
|
|
90
|
-
// as _id, _perspective, _savedOnce, and the dynamically-wired addX /
|
|
91
|
-
// removeX / setX methods must never be deleted — they are not enumerated
|
|
92
|
-
// by their public names in Object.keys, but _id and _perspective ARE plain
|
|
93
|
-
// own properties and would be wrongly removed by a naïve Object.keys scan.
|
|
94
|
-
//
|
|
95
|
-
// Note: `id` is always accessible regardless — it is a prototype getter
|
|
96
|
-
// backed by the private _id field and cannot be deleted from an instance.
|
|
97
|
-
if (requestedProperties.length > 0) {
|
|
98
|
-
const schemaKeys = [
|
|
99
|
-
...Object.keys(metadata.properties),
|
|
100
|
-
...Object.keys(metadata.relations),
|
|
101
|
-
"author",
|
|
102
|
-
"createdAt",
|
|
103
|
-
"updatedAt",
|
|
104
|
-
];
|
|
105
|
-
for (const key of schemaKeys) {
|
|
106
|
-
if (!requestedProperties.includes(key)) {
|
|
107
|
-
// Don't delete relation keys that are listed in the include map.
|
|
108
|
-
// The include-hydration step (step 3 below) needs the raw IDs to
|
|
109
|
-
// batch-fetch related models, and the hydrated result should appear
|
|
110
|
-
// in the final output even when the relation is not in `properties`.
|
|
111
|
-
if (query?.include && key in query.include)
|
|
112
|
-
continue;
|
|
113
|
-
delete instance[key];
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
instances.push(instance);
|
|
118
|
-
}
|
|
119
|
-
catch (error) {
|
|
120
|
-
console.error(`Failed to process SurrealDB instance ${error?.base ?? "unknown"}:`, error);
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
// ── 2. Reverse relations (one batch query for all instances) ──────────────
|
|
124
|
-
// Forward links (->link) are in row.links; reverse links (<-link) are not.
|
|
125
|
-
const reverseRelationEntries = Object.entries(metadata.relations).filter(([, m]) => !m.getter && m.direction === "reverse");
|
|
126
|
-
if (reverseRelationEntries.length > 0 && instances.length > 0) {
|
|
127
|
-
try {
|
|
128
|
-
const inList = instances
|
|
129
|
-
.map((i) => `'${escapeSurrealString(i.id)}'`)
|
|
130
|
-
.join(", ");
|
|
131
|
-
const reverseLinksQuery = `
|
|
132
|
-
SELECT in.uri AS source, predicate, out.uri AS target, author, timestamp
|
|
133
|
-
FROM link
|
|
134
|
-
WHERE out.uri IN [${inList}]
|
|
135
|
-
ORDER BY timestamp ASC
|
|
136
|
-
`;
|
|
137
|
-
const reverseLinks = (await perspective.querySurrealDB(reverseLinksQuery)) ?? [];
|
|
138
|
-
for (const instance of instances) {
|
|
139
|
-
for (const [relationName, relationMeta] of reverseRelationEntries) {
|
|
140
|
-
const matching = reverseLinks.filter((l) => l.target === instance.id &&
|
|
141
|
-
l.predicate === relationMeta.predicate);
|
|
142
|
-
const values = matching.map((l) => l.source);
|
|
143
|
-
instance[relationName] =
|
|
144
|
-
relationMeta.maxCount === 1 ? (values[0] ?? null) : values;
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
catch (e) {
|
|
149
|
-
console.warn("Failed to fetch reverse links for instances:", e);
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
// ── 3. Batch-hydrate relations via explicit `include` map ─────────────────
|
|
153
|
-
//
|
|
154
|
-
// No hydration is performed unless `query.include` is set.
|
|
155
|
-
// Each key in the map is a relation field name; the value is either `true`
|
|
156
|
-
// (hydrate all with no filter) or a Query to filter/order/limit the nested set.
|
|
157
|
-
if (_hydrateRelations && query?.include) {
|
|
158
|
-
const includeMap = query.include;
|
|
159
|
-
const hydrateEntries = Object.entries(metadata.relations).filter(([name, m]) => !m.getter && name in includeMap && !!m.relatedModel);
|
|
160
|
-
for (const [relationName, relationMeta] of hydrateEntries) {
|
|
161
|
-
const allIds = Array.from(new Set(instances.flatMap((i) => {
|
|
162
|
-
const val = i[relationName];
|
|
163
|
-
if (!val)
|
|
164
|
-
return [];
|
|
165
|
-
return Array.isArray(val) ? val.filter(Boolean) : [val];
|
|
166
|
-
})));
|
|
167
|
-
if (allIds.length === 0)
|
|
168
|
-
continue;
|
|
169
|
-
try {
|
|
170
|
-
// Resolve the model class from the relatedModel factory.
|
|
171
|
-
const RelatedModel = relationMeta.relatedModel();
|
|
172
|
-
// Merge caller's sub-query with the id pre-filter.
|
|
173
|
-
const entry = includeMap[relationName];
|
|
174
|
-
const subQuery = entry === true
|
|
175
|
-
? { where: { id: allIds } }
|
|
176
|
-
: { ...entry, where: { id: allIds, ...entry.where } };
|
|
177
|
-
// Pass _hydrateRelations=true when the sub-entry itself carries an
|
|
178
|
-
// include map (nested eager loading); otherwise false to stop recursion.
|
|
179
|
-
const nestedHydrate = entry !== true && !!entry.include;
|
|
180
|
-
const allHydrated = await _findAllInternal(RelatedModel, perspective, subQuery, nestedHydrate);
|
|
181
|
-
const hydratedMap = new Map(allHydrated.map((h) => [h.id, h]));
|
|
182
|
-
// When the sub-query specifies an `order`, the sorted order from
|
|
183
|
-
// _findAllInternal must be preserved. We filter allHydrated (which is
|
|
184
|
-
// already sorted) by IDs belonging to this instance, rather than
|
|
185
|
-
// iterating `val` (which is in the original link-insertion order).
|
|
186
|
-
const hasSubOrder = entry !== true && !!entry.order;
|
|
187
|
-
for (const instance of instances) {
|
|
188
|
-
const val = instance[relationName];
|
|
189
|
-
if (!val)
|
|
190
|
-
continue;
|
|
191
|
-
if (Array.isArray(val)) {
|
|
192
|
-
if (hasSubOrder) {
|
|
193
|
-
const valSet = new Set(val);
|
|
194
|
-
instance[relationName] = allHydrated.filter((h) => valSet.has(h.id));
|
|
195
|
-
}
|
|
196
|
-
else {
|
|
197
|
-
instance[relationName] = val
|
|
198
|
-
.map((id) => hydratedMap.get(id))
|
|
199
|
-
.filter((h) => h !== undefined);
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
else if (typeof val === "string") {
|
|
203
|
-
instance[relationName] = hydratedMap.get(val) ?? null;
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
catch (e) {
|
|
208
|
-
console.warn(`Failed to batch-hydrate ${relationName}:`, e);
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
// ── 4. Custom SurrealQL getters (single pass, all instances) ─────────────
|
|
213
|
-
for (const instance of instances) {
|
|
214
|
-
await evaluateCustomGetters(instance, perspective, metadata);
|
|
215
|
-
}
|
|
216
|
-
// ── 5. Snapshot capture — baseline for dirty tracking on next save() ──────
|
|
217
|
-
const schemaKeys = [
|
|
218
|
-
...Object.keys(metadata.properties),
|
|
219
|
-
...Object.keys(metadata.relations),
|
|
220
|
-
];
|
|
221
|
-
for (const instance of instances) {
|
|
222
|
-
captureSnapshot(instance, schemaKeys);
|
|
223
|
-
}
|
|
224
|
-
// ── 6. Post-filter: where conditions that SurrealDB can't handle in SQL ───
|
|
225
|
-
// • author / timestamp (computed from grouped links)
|
|
226
|
-
// • Comparison operators: gt, gte, lt, lte, between, contains
|
|
227
|
-
let filteredInstances = instances;
|
|
228
|
-
if (query.where) {
|
|
229
|
-
filteredInstances = instances.filter((instance) => {
|
|
230
|
-
for (const [propertyName, condition] of Object.entries(query.where)) {
|
|
231
|
-
// base/id filtering is already done in SQL
|
|
232
|
-
if (propertyName === "base" || propertyName === "id")
|
|
233
|
-
continue;
|
|
234
|
-
// author and timestamp: always filter in JS
|
|
235
|
-
if (propertyName === "author" || propertyName === "timestamp") {
|
|
236
|
-
if (!matchesCondition(instance[propertyName], condition)) {
|
|
237
|
-
return false;
|
|
238
|
-
}
|
|
239
|
-
continue;
|
|
240
|
-
}
|
|
241
|
-
// Comparison operators: only these need JS post-filtering
|
|
242
|
-
if (typeof condition === "object" &&
|
|
243
|
-
condition !== null &&
|
|
244
|
-
!Array.isArray(condition)) {
|
|
245
|
-
const cond = condition;
|
|
246
|
-
const hasComparisonOps = cond.gt !== undefined ||
|
|
247
|
-
cond.gte !== undefined ||
|
|
248
|
-
cond.lt !== undefined ||
|
|
249
|
-
cond.lte !== undefined ||
|
|
250
|
-
cond.between !== undefined ||
|
|
251
|
-
cond.contains !== undefined;
|
|
252
|
-
if (hasComparisonOps) {
|
|
253
|
-
if (!matchesCondition(instance[propertyName], condition)) {
|
|
254
|
-
return false;
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
return true;
|
|
260
|
-
});
|
|
261
|
-
}
|
|
262
|
-
// ── 7. Sort in JavaScript ─────────────────────────────────────────────────
|
|
263
|
-
// If limit/offset is used but no explicit order, default to timestamp ASC
|
|
264
|
-
// to guarantee consistent pagination behaviour.
|
|
265
|
-
const effectiveOrder = query.order ||
|
|
266
|
-
(query.limit !== undefined || query.offset !== undefined
|
|
267
|
-
? { timestamp: "ASC" }
|
|
268
|
-
: null);
|
|
269
|
-
if (effectiveOrder) {
|
|
270
|
-
const orderEntries = Object.entries(effectiveOrder);
|
|
271
|
-
filteredInstances.sort((a, b) => {
|
|
272
|
-
for (const [orderPropName, orderDirection] of orderEntries) {
|
|
273
|
-
let aVal = a[orderPropName];
|
|
274
|
-
let bVal = b[orderPropName];
|
|
275
|
-
if (aVal === undefined && bVal === undefined)
|
|
276
|
-
continue;
|
|
277
|
-
if (aVal === undefined)
|
|
278
|
-
return orderDirection === "ASC" ? 1 : -1;
|
|
279
|
-
if (bVal === undefined)
|
|
280
|
-
return orderDirection === "ASC" ? -1 : 1;
|
|
281
|
-
let comparison = 0;
|
|
282
|
-
if (typeof aVal === "number" && typeof bVal === "number") {
|
|
283
|
-
comparison = aVal - bVal;
|
|
284
|
-
}
|
|
285
|
-
else if (typeof aVal === "string" && typeof bVal === "string") {
|
|
286
|
-
comparison = aVal.localeCompare(bVal);
|
|
287
|
-
}
|
|
288
|
-
else {
|
|
289
|
-
comparison = String(aVal).localeCompare(String(bVal));
|
|
290
|
-
}
|
|
291
|
-
if (comparison !== 0)
|
|
292
|
-
return orderDirection === "DESC" ? -comparison : comparison;
|
|
293
|
-
}
|
|
294
|
-
return 0;
|
|
295
|
-
});
|
|
296
|
-
}
|
|
297
|
-
// ── 8. Calculate totalCount BEFORE limit/offset, then paginate ────────────
|
|
298
|
-
const totalCount = filteredInstances.length;
|
|
299
|
-
let paginatedInstances = filteredInstances;
|
|
300
|
-
if (query.offset !== undefined || query.limit !== undefined) {
|
|
301
|
-
const start = query.offset || 0;
|
|
302
|
-
const end = query.limit ? start + query.limit : undefined;
|
|
303
|
-
paginatedInstances = filteredInstances.slice(start, end);
|
|
304
|
-
}
|
|
305
|
-
return { results: paginatedInstances, totalCount };
|
|
306
|
-
}
|
|
307
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
308
|
-
// High-level find/count operations
|
|
309
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
310
|
-
/**
|
|
311
|
-
* Internal findAll used by the public static and by eager-hydration depth-guards.
|
|
312
|
-
* Pass `_hydrateRelations = false` to prevent recursive nested-model hydration.
|
|
313
|
-
*/
|
|
314
|
-
export async function _findAllInternal(ctor, perspective, query = {}, _hydrateRelations = true) {
|
|
315
|
-
const surrealQuery = await queryToSurrealQL(ctor, perspective, query);
|
|
316
|
-
const result = await perspective.querySurrealDB(surrealQuery);
|
|
317
|
-
const { results } = await instancesFromSurrealResult(ctor, perspective, query, result, _hydrateRelations);
|
|
318
|
-
return results;
|
|
319
|
-
}
|
|
320
|
-
/** Returns all matching instances. */
|
|
321
|
-
export async function findAll(ctor, perspective, query) {
|
|
322
|
-
return _findAllInternal(ctor, perspective, query, true);
|
|
323
|
-
}
|
|
324
|
-
/** Returns the first matching instance, or `null` if none found. */
|
|
325
|
-
export async function findOne(ctor, perspective, query) {
|
|
326
|
-
const results = await findAll(ctor, perspective, { ...query, limit: 1 });
|
|
327
|
-
return results[0] ?? null;
|
|
328
|
-
}
|
|
329
|
-
/** Returns all matching instances together with the total unfilterd count. */
|
|
330
|
-
export async function findAllAndCount(ctor, perspective, query) {
|
|
331
|
-
const surrealQuery = await queryToSurrealQL(ctor, perspective, query);
|
|
332
|
-
const result = await perspective.querySurrealDB(surrealQuery);
|
|
333
|
-
return instancesFromSurrealResult(ctor, perspective, query, result);
|
|
334
|
-
}
|
|
335
|
-
/**
|
|
336
|
-
* Paginates results given an explicit page size and 1-based page number.
|
|
337
|
-
* Returns metadata needed to render pagination controls.
|
|
338
|
-
*/
|
|
339
|
-
export async function paginate(ctor, perspective, pageSize, pageNumber, query) {
|
|
340
|
-
const paginationQuery = {
|
|
341
|
-
...query,
|
|
342
|
-
limit: pageSize,
|
|
343
|
-
offset: pageSize * (pageNumber - 1),
|
|
344
|
-
count: true,
|
|
345
|
-
};
|
|
346
|
-
const surrealQuery = await queryToSurrealQL(ctor, perspective, paginationQuery);
|
|
347
|
-
const result = await perspective.querySurrealDB(surrealQuery);
|
|
348
|
-
const { results, totalCount } = await instancesFromSurrealResult(ctor, perspective, paginationQuery, result);
|
|
349
|
-
return { results, totalCount, pageSize, pageNumber };
|
|
350
|
-
}
|
|
351
|
-
/** Returns true when `where` has conditions that require JS post-filtering. */
|
|
352
|
-
function hasJsFilterConditions(where) {
|
|
353
|
-
if (!where)
|
|
354
|
-
return false;
|
|
355
|
-
return Object.entries(where).some(([k, v]) => {
|
|
356
|
-
if (k === "author" || k === "timestamp")
|
|
357
|
-
return true;
|
|
358
|
-
if (typeof v === "object" && v !== null && !Array.isArray(v)) {
|
|
359
|
-
const ops = v;
|
|
360
|
-
return (ops.gt !== undefined ||
|
|
361
|
-
ops.gte !== undefined ||
|
|
362
|
-
ops.lt !== undefined ||
|
|
363
|
-
ops.lte !== undefined ||
|
|
364
|
-
ops.between !== undefined ||
|
|
365
|
-
ops.contains !== undefined);
|
|
366
|
-
}
|
|
367
|
-
return false;
|
|
368
|
-
});
|
|
369
|
-
}
|
|
370
|
-
/** Returns a count of all matching instances. */
|
|
371
|
-
export async function count(ctor, perspective, query) {
|
|
372
|
-
// Strip pagination — count always wants total, not the paginated slice.
|
|
373
|
-
const countQuery = { ...query, limit: undefined, offset: undefined };
|
|
374
|
-
const surrealQuery = await countQueryToSurrealQL(ctor, perspective, countQuery);
|
|
375
|
-
const result = await perspective.querySurrealDB(surrealQuery);
|
|
376
|
-
if (!result || result.length === 0)
|
|
377
|
-
return 0;
|
|
378
|
-
// Fast path: SQL WHERE handles all conditions — skip full instance hydration.
|
|
379
|
-
if (!hasJsFilterConditions(countQuery.where))
|
|
380
|
-
return result.length;
|
|
381
|
-
// Slow path: hydrate so JS post-filters (gt/gte/author/etc.) can run.
|
|
382
|
-
const { totalCount } = await instancesFromSurrealResult(ctor, perspective, countQuery, result);
|
|
383
|
-
return totalCount ?? 0;
|
|
384
|
-
}
|