@coasys/ad4m 0.12.0-rc1-dev.1 → 0.12.0-rc1-dev.3

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 (124) hide show
  1. package/jest.config.js +8 -1
  2. package/lib/index.cjs +13793 -12854
  3. package/lib/index.js +13782 -12851
  4. package/lib/src/Ad4mClient.test.d.ts +1 -0
  5. package/lib/src/Ad4mClient.test.js +1204 -0
  6. package/lib/src/Literal.test.d.ts +1 -0
  7. package/lib/src/Literal.test.js +41 -0
  8. package/lib/src/model/Ad4mModel.d.ts +528 -101
  9. package/lib/src/model/Ad4mModel.js +1670 -748
  10. package/lib/src/model/Ad4mModel.test.js +140 -156
  11. package/lib/src/model/Subject.d.ts +3 -3
  12. package/lib/src/model/Subject.js +25 -25
  13. package/lib/src/model/decorators.d.ts +259 -247
  14. package/lib/src/model/decorators.js +379 -422
  15. package/lib/src/model/mutation.d.ts +81 -0
  16. package/lib/src/model/mutation.js +317 -0
  17. package/lib/src/model/parentUtils.d.ts +32 -0
  18. package/lib/src/model/parentUtils.js +64 -0
  19. package/lib/src/model/prolog/generatePrologFacts.d.ts +36 -0
  20. package/lib/src/model/prolog/generatePrologFacts.js +139 -0
  21. package/lib/src/model/prolog/index.d.ts +1 -0
  22. package/lib/src/model/prolog/index.js +1 -0
  23. package/lib/src/model/query/ModelQueryBuilder.d.ts +82 -0
  24. package/lib/src/model/query/ModelQueryBuilder.js +115 -0
  25. package/lib/src/model/query/QueryBuilder.d.ts +101 -0
  26. package/lib/src/model/query/QueryBuilder.js +193 -0
  27. package/lib/src/model/query/SurrealQueryBuilder.d.ts +48 -0
  28. package/lib/src/model/query/SurrealQueryBuilder.js +371 -0
  29. package/lib/src/model/query/fetchInstance.d.ts +24 -0
  30. package/lib/src/model/query/fetchInstance.js +144 -0
  31. package/lib/src/model/query/hydration.d.ts +54 -0
  32. package/lib/src/model/query/hydration.js +214 -0
  33. package/lib/src/model/query/operations.d.ts +59 -0
  34. package/lib/src/model/query/operations.js +384 -0
  35. package/lib/src/model/query/snapshot.d.ts +59 -0
  36. package/lib/src/model/query/snapshot.js +106 -0
  37. package/lib/src/model/query/surrealCompiler.d.ts +42 -0
  38. package/lib/src/model/query/surrealCompiler.js +304 -0
  39. package/lib/src/model/schema/fromJSONSchema.d.ts +67 -0
  40. package/lib/src/model/schema/fromJSONSchema.js +264 -0
  41. package/lib/src/model/schema/metadata.d.ts +15 -0
  42. package/lib/src/model/schema/metadata.js +112 -0
  43. package/lib/src/model/subscription.d.ts +47 -0
  44. package/lib/src/model/subscription.js +231 -0
  45. package/lib/src/model/transaction.d.ts +27 -0
  46. package/lib/src/model/transaction.js +32 -0
  47. package/lib/src/model/types.d.ts +195 -0
  48. package/lib/src/model/types.js +8 -0
  49. package/lib/src/model/util.d.ts +6 -6
  50. package/lib/src/model/util.js +22 -22
  51. package/lib/src/neighbourhood/NeighbourhoodClient.js +31 -12
  52. package/lib/src/perspectives/PerspectiveProxy.d.ts +9 -9
  53. package/lib/src/perspectives/PerspectiveProxy.js +63 -51
  54. package/lib/src/shacl/SHACLShape.d.ts +9 -0
  55. package/lib/src/shacl/SHACLShape.js +28 -4
  56. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  57. package/lib/src/shims/type-graphql.d.ts +32 -0
  58. package/lib/src/src/Ad4mClient.d.ts +28 -0
  59. package/lib/src/src/Address.d.ts +1 -0
  60. package/lib/src/src/DID.d.ts +1 -0
  61. package/lib/src/src/Exception.d.ts +7 -0
  62. package/lib/src/src/Literal.d.ts +7 -0
  63. package/lib/src/src/PubSub.d.ts +17 -0
  64. package/lib/src/src/SmartLiteral.d.ts +12 -0
  65. package/lib/src/src/agent/Agent.d.ts +110 -0
  66. package/lib/src/src/agent/AgentClient.d.ts +62 -0
  67. package/lib/src/src/agent/AgentResolver.d.ts +30 -0
  68. package/lib/src/src/agent/AgentStatus.d.ts +8 -0
  69. package/lib/src/src/ai/AIClient.d.ts +32 -0
  70. package/lib/src/src/ai/AIResolver.d.ts +75 -0
  71. package/lib/src/src/ai/Tasks.d.ts +37 -0
  72. package/lib/src/src/buildSchema.d.ts +1 -0
  73. package/lib/src/src/expression/Expression.d.ts +28 -0
  74. package/lib/src/src/expression/ExpressionClient.d.ts +13 -0
  75. package/lib/src/src/expression/ExpressionRef.d.ts +9 -0
  76. package/lib/src/src/expression/ExpressionResolver.d.ts +10 -0
  77. package/lib/src/src/index.d.ts +35 -0
  78. package/lib/src/src/jestSetup.d.ts +1 -0
  79. package/lib/src/src/language/Icon.d.ts +4 -0
  80. package/lib/src/src/language/Language.d.ts +206 -0
  81. package/lib/src/src/language/LanguageClient.d.ts +17 -0
  82. package/lib/src/src/language/LanguageContext.d.ts +37 -0
  83. package/lib/src/src/language/LanguageHandle.d.ts +9 -0
  84. package/lib/src/src/language/LanguageMeta.d.ts +35 -0
  85. package/lib/src/src/language/LanguageRef.d.ts +6 -0
  86. package/lib/src/src/language/LanguageResolver.d.ts +19 -0
  87. package/lib/src/src/links/Links.d.ts +39 -0
  88. package/lib/src/src/links/Links.test.d.ts +1 -0
  89. package/lib/src/src/model/Ad4mModel.d.ts +1438 -0
  90. package/lib/src/src/model/Ad4mModel.test.d.ts +1 -0
  91. package/lib/src/src/model/Subject.d.ts +25 -0
  92. package/lib/src/src/model/decorators.d.ts +545 -0
  93. package/lib/src/src/model/util.d.ts +12 -0
  94. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +10 -0
  95. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +25 -0
  96. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +19 -0
  97. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +1 -0
  98. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +24 -0
  99. package/lib/src/src/perspectives/LinkQuery.d.ts +11 -0
  100. package/lib/src/src/perspectives/Perspective.d.ts +38 -0
  101. package/lib/src/src/perspectives/Perspective.test.d.ts +1 -0
  102. package/lib/src/src/perspectives/PerspectiveClient.d.ts +97 -0
  103. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +9 -0
  104. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +18 -0
  105. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +865 -0
  106. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +57 -0
  107. package/lib/src/src/runtime/RuntimeClient.d.ts +56 -0
  108. package/lib/src/src/runtime/RuntimeResolver.d.ts +132 -0
  109. package/lib/src/src/shacl/SHACLFlow.d.ts +171 -0
  110. package/lib/src/src/shacl/SHACLFlow.test.d.ts +1 -0
  111. package/lib/src/src/shacl/SHACLShape.d.ts +117 -0
  112. package/lib/src/src/shacl/SHACLShape.test.d.ts +1 -0
  113. package/lib/src/src/typeDefs.d.ts +1 -0
  114. package/lib/src/src/unwrapApolloResult.d.ts +2 -0
  115. package/lib/src/src/utils.d.ts +25 -0
  116. package/package.json +20 -24
  117. package/src/model/Ad4mModel.test.ts +132 -149
  118. package/src/model/Ad4mModel.ts +1930 -784
  119. package/src/model/Subject.ts +24 -24
  120. package/src/model/decorators.ts +626 -482
  121. package/src/model/util.ts +22 -22
  122. package/src/neighbourhood/NeighbourhoodClient.ts +32 -16
  123. package/src/perspectives/PerspectiveProxy.ts +69 -55
  124. package/src/shacl/SHACLShape.ts +33 -4
@@ -0,0 +1,214 @@
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
+ }
@@ -0,0 +1,59 @@
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>;
@@ -0,0 +1,384 @@
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
+ }