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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/lib/index.cjs +5052 -4446
  2. package/lib/index.js +5019 -4442
  3. package/lib/src/agent/AgentClient.d.ts +4 -0
  4. package/lib/src/agent/AgentClient.js +34 -0
  5. package/lib/src/index.d.ts +2 -3
  6. package/lib/src/index.js +2 -3
  7. package/lib/src/model/Ad4mModel.d.ts +8 -782
  8. package/lib/src/model/Ad4mModel.js +160 -2354
  9. package/lib/src/model/ModelQueryBuilder.d.ts +370 -0
  10. package/lib/src/model/ModelQueryBuilder.js +556 -0
  11. package/lib/src/model/decorators.d.ts +71 -23
  12. package/lib/src/model/decorators.js +133 -384
  13. package/lib/src/model/hydration.d.ts +102 -0
  14. package/lib/src/model/hydration.js +709 -0
  15. package/lib/src/model/index.d.ts +20 -0
  16. package/lib/src/model/index.js +20 -0
  17. package/lib/src/model/{schema/fromJSONSchema.d.ts → json-schema.d.ts} +45 -12
  18. package/lib/src/model/json-schema.js +326 -0
  19. package/lib/src/model/prolog-facts.d.ts +37 -0
  20. package/lib/src/model/{prolog/generatePrologFacts.js → prolog-facts.js} +47 -52
  21. package/lib/src/model/query-common.d.ts +14 -0
  22. package/lib/src/model/query-common.js +36 -0
  23. package/lib/src/model/query-prolog.d.ts +15 -0
  24. package/lib/src/model/query-prolog.js +140 -0
  25. package/lib/src/model/query-surreal.d.ts +44 -0
  26. package/lib/src/model/query-surreal.js +249 -0
  27. package/lib/src/model/relation-filtering.test.js +838 -0
  28. package/lib/src/model/sdna.d.ts +14 -0
  29. package/lib/src/model/sdna.js +141 -0
  30. package/lib/src/model/shacl-gen.d.ts +31 -0
  31. package/lib/src/model/shacl-gen.js +246 -0
  32. package/lib/src/model/surreal-utils.d.ts +42 -0
  33. package/lib/src/model/surreal-utils.js +128 -0
  34. package/lib/src/model/types.d.ts +75 -96
  35. package/lib/src/model/types.js +4 -4
  36. package/lib/src/model/util.d.ts +4 -5
  37. package/lib/src/model/util.js +12 -32
  38. package/lib/src/perspectives/PerspectiveClient.d.ts +1 -1
  39. package/lib/src/perspectives/PerspectiveProxy.d.ts +1 -1
  40. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +79 -0
  41. package/lib/src/perspectives/WakerSubscriptionManager.js +196 -0
  42. package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
  43. package/lib/src/runtime/RuntimeResolver.js +73 -0
  44. package/lib/src/schema.gql +14 -0
  45. package/lib/src/shacl/SHACLShape.d.ts +23 -0
  46. package/lib/src/shacl/SHACLShape.js +45 -0
  47. package/lib/src/typeDefs.js +14 -0
  48. package/package.json +13 -8
  49. package/src/agent/AgentClient.ts +45 -0
  50. package/src/index.ts +2 -3
  51. package/src/model/Ad4mModel.ts +1089 -3686
  52. package/src/model/ModelQueryBuilder.ts +617 -0
  53. package/src/model/Subject.ts +1 -1
  54. package/src/model/decorators.ts +218 -453
  55. package/src/model/hydration.ts +796 -0
  56. package/src/model/index.ts +21 -0
  57. package/src/model/json-schema.ts +424 -0
  58. package/src/model/prolog-facts.ts +145 -0
  59. package/src/model/query-common.ts +48 -0
  60. package/src/model/query-prolog.ts +148 -0
  61. package/src/model/query-surreal.ts +280 -0
  62. package/src/model/relation-filtering.test.ts +803 -0
  63. package/src/model/sdna.ts +170 -0
  64. package/src/model/shacl-gen.ts +292 -0
  65. package/src/model/surreal-utils.ts +147 -0
  66. package/src/model/types.ts +182 -0
  67. package/src/model/util.ts +13 -36
  68. package/src/perspectives/PerspectiveClient.ts +1 -1
  69. package/src/perspectives/PerspectiveProxy.ts +1 -1
  70. package/src/perspectives/WakerSubscriptionManager.ts +292 -0
  71. package/src/runtime/RuntimeResolver.ts +53 -0
  72. package/src/shacl/SHACLShape.ts +83 -0
  73. package/lib/src/Ad4mClient.test.js +0 -1204
  74. package/lib/src/Literal.test.d.ts +0 -1
  75. package/lib/src/Literal.test.js +0 -41
  76. package/lib/src/model/mutation.d.ts +0 -81
  77. package/lib/src/model/mutation.js +0 -317
  78. package/lib/src/model/parentUtils.d.ts +0 -32
  79. package/lib/src/model/parentUtils.js +0 -64
  80. package/lib/src/model/prolog/generatePrologFacts.d.ts +0 -36
  81. package/lib/src/model/prolog/index.d.ts +0 -1
  82. package/lib/src/model/prolog/index.js +0 -1
  83. package/lib/src/model/query/ModelQueryBuilder.d.ts +0 -82
  84. package/lib/src/model/query/ModelQueryBuilder.js +0 -115
  85. package/lib/src/model/query/QueryBuilder.d.ts +0 -101
  86. package/lib/src/model/query/QueryBuilder.js +0 -193
  87. package/lib/src/model/query/SurrealQueryBuilder.d.ts +0 -48
  88. package/lib/src/model/query/SurrealQueryBuilder.js +0 -371
  89. package/lib/src/model/query/fetchInstance.d.ts +0 -24
  90. package/lib/src/model/query/fetchInstance.js +0 -144
  91. package/lib/src/model/query/hydration.d.ts +0 -54
  92. package/lib/src/model/query/hydration.js +0 -214
  93. package/lib/src/model/query/operations.d.ts +0 -59
  94. package/lib/src/model/query/operations.js +0 -384
  95. package/lib/src/model/query/snapshot.d.ts +0 -59
  96. package/lib/src/model/query/snapshot.js +0 -106
  97. package/lib/src/model/query/surrealCompiler.d.ts +0 -42
  98. package/lib/src/model/query/surrealCompiler.js +0 -304
  99. package/lib/src/model/schema/fromJSONSchema.js +0 -264
  100. package/lib/src/model/schema/metadata.d.ts +0 -15
  101. package/lib/src/model/schema/metadata.js +0 -112
  102. package/lib/src/model/subscription.d.ts +0 -47
  103. package/lib/src/model/subscription.js +0 -231
  104. package/lib/src/model/transaction.d.ts +0 -27
  105. package/lib/src/model/transaction.js +0 -32
  106. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  107. package/lib/src/shims/type-graphql.d.ts +0 -32
  108. package/lib/src/src/Ad4mClient.d.ts +0 -28
  109. package/lib/src/src/Address.d.ts +0 -1
  110. package/lib/src/src/DID.d.ts +0 -1
  111. package/lib/src/src/Exception.d.ts +0 -7
  112. package/lib/src/src/Literal.d.ts +0 -7
  113. package/lib/src/src/PubSub.d.ts +0 -17
  114. package/lib/src/src/SmartLiteral.d.ts +0 -12
  115. package/lib/src/src/agent/Agent.d.ts +0 -110
  116. package/lib/src/src/agent/AgentClient.d.ts +0 -62
  117. package/lib/src/src/agent/AgentResolver.d.ts +0 -30
  118. package/lib/src/src/agent/AgentStatus.d.ts +0 -8
  119. package/lib/src/src/ai/AIClient.d.ts +0 -32
  120. package/lib/src/src/ai/AIResolver.d.ts +0 -75
  121. package/lib/src/src/ai/Tasks.d.ts +0 -37
  122. package/lib/src/src/buildSchema.d.ts +0 -1
  123. package/lib/src/src/expression/Expression.d.ts +0 -28
  124. package/lib/src/src/expression/ExpressionClient.d.ts +0 -13
  125. package/lib/src/src/expression/ExpressionRef.d.ts +0 -9
  126. package/lib/src/src/expression/ExpressionResolver.d.ts +0 -10
  127. package/lib/src/src/index.d.ts +0 -35
  128. package/lib/src/src/jestSetup.d.ts +0 -1
  129. package/lib/src/src/language/Icon.d.ts +0 -4
  130. package/lib/src/src/language/Language.d.ts +0 -206
  131. package/lib/src/src/language/LanguageClient.d.ts +0 -17
  132. package/lib/src/src/language/LanguageContext.d.ts +0 -37
  133. package/lib/src/src/language/LanguageHandle.d.ts +0 -9
  134. package/lib/src/src/language/LanguageMeta.d.ts +0 -35
  135. package/lib/src/src/language/LanguageRef.d.ts +0 -6
  136. package/lib/src/src/language/LanguageResolver.d.ts +0 -19
  137. package/lib/src/src/links/Links.d.ts +0 -39
  138. package/lib/src/src/links/Links.test.d.ts +0 -1
  139. package/lib/src/src/model/Ad4mModel.d.ts +0 -1438
  140. package/lib/src/src/model/Ad4mModel.test.d.ts +0 -1
  141. package/lib/src/src/model/Subject.d.ts +0 -25
  142. package/lib/src/src/model/decorators.d.ts +0 -545
  143. package/lib/src/src/model/util.d.ts +0 -12
  144. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +0 -10
  145. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +0 -25
  146. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +0 -19
  147. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +0 -1
  148. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +0 -24
  149. package/lib/src/src/perspectives/LinkQuery.d.ts +0 -11
  150. package/lib/src/src/perspectives/Perspective.d.ts +0 -38
  151. package/lib/src/src/perspectives/Perspective.test.d.ts +0 -1
  152. package/lib/src/src/perspectives/PerspectiveClient.d.ts +0 -97
  153. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +0 -9
  154. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +0 -18
  155. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +0 -865
  156. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +0 -57
  157. package/lib/src/src/runtime/RuntimeClient.d.ts +0 -56
  158. package/lib/src/src/runtime/RuntimeResolver.d.ts +0 -132
  159. package/lib/src/src/shacl/SHACLFlow.d.ts +0 -171
  160. package/lib/src/src/shacl/SHACLFlow.test.d.ts +0 -1
  161. package/lib/src/src/shacl/SHACLShape.d.ts +0 -117
  162. package/lib/src/src/shacl/SHACLShape.test.d.ts +0 -1
  163. package/lib/src/src/typeDefs.d.ts +0 -1
  164. package/lib/src/src/unwrapApolloResult.d.ts +0 -2
  165. package/lib/src/src/utils.d.ts +0 -25
  166. /package/lib/src/{Ad4mClient.test.d.ts → model/relation-filtering.test.d.ts} +0 -0
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Prolog query building helpers for the Ad4mModel query pipeline.
3
+ *
4
+ * These pure functions translate the Ad4mModel `Query` DSL into Prolog clause
5
+ * fragments that are assembled by `Ad4mModel.queryToProlog()`.
6
+ */
7
+
8
+ import type { Where, WhereCondition, Order, ParentScope } from "./types";
9
+ import { capitalize } from "./util";
10
+
11
+ // ── Query clause builders ────────────────────────────────────────────────────
12
+
13
+ export function buildParentQuery(
14
+ parent: ParentScope | undefined,
15
+ resolvedPredicate?: string,
16
+ ): string {
17
+ if (!parent || !resolvedPredicate) return '';
18
+ return `triple("${parent.id}", "${resolvedPredicate}", Base)`;
19
+ }
20
+
21
+ export function buildAuthorAndTimestampQuery(): string {
22
+ // Gets the author and timestamp of a Ad4mModel instance (based on the first link mentioning the base)
23
+ return `
24
+ findall(
25
+ [T, A],
26
+ link(Base, _, _, T, A),
27
+ AllLinks
28
+ ),
29
+ sort(AllLinks, SortedLinks),
30
+ SortedLinks = [[Timestamp, Author]|_]
31
+ `;
32
+ }
33
+
34
+ export function buildPropertiesQuery(properties?: string[]): string {
35
+ // Gets the name, value, and resolve boolean for all (or some) properties on a Ad4mModel instance
36
+ // Resolves literals (if property_resolve/2 is true) to their value - either the data field if it is
37
+ // an Expression in JSON literal, or the direct literal value if it is a simple literal
38
+ // If no properties are provided, all are included
39
+ return `
40
+ findall([PropertyName, PropertyValue, Resolve], (
41
+ % Constrain to specified properties if provided
42
+ ${properties ? `member(PropertyName, [${properties.map((name) => `"${name}"`).join(", ")}]),` : ""}
43
+ resolve_property(SubjectClass, Base, PropertyName, PropertyValue, Resolve)
44
+ ), Properties)
45
+ `;
46
+ }
47
+
48
+ export function buildWhereQuery(where: Where = {}): string {
49
+ // Constrains the query to instances that match the provided where conditions
50
+ // 'id' maps to the Prolog 'Base' variable (the base expression of the instance).
51
+
52
+ function formatValue(value) {
53
+ // Wrap strings in quotes
54
+ return typeof value === "string" ? `"${value}"` : value;
55
+ }
56
+
57
+ return (Object.entries(where) as [string, WhereCondition][])
58
+ .map(([key, value]) => {
59
+ const isSpecial = ["id", "author", "timestamp"].includes(key);
60
+ const getter = `resolve_property(SubjectClass, Base, "${key}", Value${key}, _)`;
61
+ // For 'id' the Prolog variable is always 'Base'
62
+ const field = key === "id" ? "Base" : capitalize(key);
63
+
64
+ // Handle direct array values (for IN conditions)
65
+ if (Array.isArray(value)) {
66
+ const formattedValues = value.map((v) => formatValue(v)).join(", ");
67
+ if (isSpecial) return `member(${field}, [${formattedValues}])`;
68
+ else return `${getter}, member(Value${key}, [${formattedValues}])`;
69
+ }
70
+
71
+ // Handle operation object
72
+ if (typeof value === "object" && value !== null) {
73
+ const { not, between, lt, lte, gt, gte } = value;
74
+
75
+ // Handle NOT operation
76
+ if (not !== undefined) {
77
+ if (Array.isArray(not)) {
78
+ // NOT IN array
79
+ const formattedValues = not.map((v) => formatValue(v)).join(", ");
80
+ if (isSpecial) return `\\+ member(${field}, [${formattedValues}])`;
81
+ else return `${getter}, \\+ member(Value${key}, [${formattedValues}])`;
82
+ } else {
83
+ // NOT EQUAL
84
+ if (isSpecial) return `${field} \\= ${formatValue(not)}`;
85
+ else return `${getter}, Value${key} \\= ${formatValue(not)}`;
86
+ }
87
+ }
88
+
89
+ // Handle BETWEEN
90
+ if (between !== undefined && Array.isArray(between) && between.length === 2) {
91
+ if (isSpecial) return `${field} >= ${between[0]}, ${field} =< ${between[1]}`;
92
+ else return `${getter}, Value${key} >= ${between[0]}, Value${key} =< ${between[1]}`;
93
+ }
94
+
95
+ // Handle lt, lte, gt, & gte operations
96
+ const operators = [
97
+ { value: lt, symbol: "<" }, // LESS THAN
98
+ { value: lte, symbol: "=<" }, // LESS THAN OR EQUAL TO
99
+ { value: gt, symbol: ">" }, // GREATER THAN
100
+ { value: gte, symbol: ">=" }, // GREATER THAN OR EQUAL TO
101
+ ];
102
+
103
+ for (const { value, symbol } of operators) {
104
+ if (value !== undefined)
105
+ return isSpecial ? `${field} ${symbol} ${value}` : `${getter}, Value${key} ${symbol} ${value}`;
106
+ }
107
+ }
108
+
109
+ // Default to direct equality
110
+ if (isSpecial) return `${field} = ${formatValue(value)}`;
111
+ else return `${getter}, Value${key} = ${formatValue(value)}`;
112
+ })
113
+ .join(", ");
114
+ }
115
+
116
+ export function buildCountQuery(count?: boolean): string {
117
+ return count ? "length(UnsortedInstances, TotalCount)" : "";
118
+ }
119
+
120
+ export function buildOrderQuery(order?: Order): string {
121
+ if (!order) return "SortedInstances = UnsortedInstances";
122
+ const entries = Object.entries(order);
123
+ if (entries.length === 1) {
124
+ const [propertyName, direction] = entries[0];
125
+ return `sort_instances(UnsortedInstances, "${propertyName}", "${direction}", SortedInstances)`;
126
+ }
127
+ // Multi-field sort: sort from least-significant to most-significant key
128
+ // so that the final (primary) sort preserves secondary-key ordering for equal values.
129
+ // The merge_sort implementation is stable (equal elements keep original order).
130
+ const clauses: string[] = [];
131
+ for (let i = entries.length - 1; i >= 0; i--) {
132
+ const [propertyName, direction] = entries[i];
133
+ const inputVar = i === entries.length - 1 ? "UnsortedInstances" : `MultiSortIntermediate${i + 1}`;
134
+ const outputVar = i === 0 ? "SortedInstances" : `MultiSortIntermediate${i}`;
135
+ clauses.push(`sort_instances(${inputVar}, "${propertyName}", "${direction}", ${outputVar})`);
136
+ }
137
+ return clauses.join(",\n ");
138
+ }
139
+
140
+ export function buildOffsetQuery(offset?: number): string {
141
+ if (!offset || offset < 0) return "InstancesWithOffset = SortedInstances";
142
+ return `skipN(SortedInstances, ${offset}, InstancesWithOffset)`;
143
+ }
144
+
145
+ export function buildLimitQuery(limit?: number): string {
146
+ if (!limit || limit < 0) return "AllInstances = InstancesWithOffset";
147
+ return `takeN(InstancesWithOffset, ${limit}, AllInstances)`;
148
+ }
@@ -0,0 +1,280 @@
1
+ /**
2
+ * SurrealQL query building utilities for Ad4mModel.
3
+ *
4
+ * Contains the graph-traversal WHERE clause builder, legacy
5
+ * subquery-based clause builders, SELECT-field builders, and
6
+ * the main `buildSurrealQLQuery()` function that produces a
7
+ * complete SurrealQL query string from a `Query` object.
8
+ *
9
+ * All functions are stateless — model metadata and relation metadata
10
+ * are passed in as parameters instead of accessed via `this`.
11
+ *
12
+ * @module
13
+ */
14
+
15
+ import { escapeSurrealString } from "../utils";
16
+ import { formatSurrealValue } from "./surreal-utils";
17
+ import { resolveParentPredicate } from "./query-common";
18
+ import type { RelationMetadataEntry } from "./decorators";
19
+ import type {
20
+ Where, Query, ModelMetadata
21
+ } from "./types";
22
+
23
+ // ─── Graph Traversal WHERE Clause ────────────────────────────────────────────
24
+
25
+ /**
26
+ * Builds WHERE clause filters using SurrealDB graph traversal syntax.
27
+ *
28
+ * Translates where conditions into `->link[WHERE ...]` / `<-link[WHERE ...]`
29
+ * filters that SurrealDB can optimize via graph indexes.
30
+ *
31
+ * @param metadata - Model metadata from `getModelMetadata()`
32
+ * @param allRelationsMetadata - Full relation metadata (needed for belongs-to
33
+ * direction detection)
34
+ * @param where - User-supplied where conditions
35
+ * @returns Combined AND-joined condition string, or empty string
36
+ */
37
+ export function buildGraphTraversalWhereClause(
38
+ metadata: ModelMetadata,
39
+ allRelationsMetadata: Record<string, RelationMetadataEntry>,
40
+ where?: Where,
41
+ ): string {
42
+ if (!where) return '';
43
+
44
+ const conditions: string[] = [];
45
+
46
+ for (const [propertyName, condition] of Object.entries(where)) {
47
+ const isSpecial = ['id', 'author', 'timestamp'].includes(propertyName);
48
+
49
+ if (isSpecial) {
50
+ if (propertyName === 'author' || propertyName === 'timestamp') {
51
+ continue; // Filtered post-query in JS
52
+ }
53
+
54
+ const columnName = 'uri';
55
+
56
+ if (Array.isArray(condition)) {
57
+ const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
58
+ conditions.push(`${columnName} IN [${formattedValues}]`);
59
+ } else if (typeof condition === 'object' && condition !== null) {
60
+ const ops = condition as any;
61
+ if (ops.not !== undefined) {
62
+ if (Array.isArray(ops.not)) {
63
+ const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
64
+ conditions.push(`${columnName} NOT IN [${formattedValues}]`);
65
+ } else {
66
+ conditions.push(`${columnName} != ${formatSurrealValue(ops.not)}`);
67
+ }
68
+ }
69
+ if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
70
+ conditions.push(`${columnName} >= ${formatSurrealValue(ops.between[0])} AND ${columnName} <= ${formatSurrealValue(ops.between[1])}`);
71
+ }
72
+ if (ops.gt !== undefined) {
73
+ conditions.push(`${columnName} > ${formatSurrealValue(ops.gt)}`);
74
+ }
75
+ if (ops.gte !== undefined) {
76
+ conditions.push(`${columnName} >= ${formatSurrealValue(ops.gte)}`);
77
+ }
78
+ if (ops.lt !== undefined) {
79
+ conditions.push(`${columnName} < ${formatSurrealValue(ops.lt)}`);
80
+ }
81
+ if (ops.lte !== undefined) {
82
+ conditions.push(`${columnName} <= ${formatSurrealValue(ops.lte)}`);
83
+ }
84
+ if (ops.contains !== undefined) {
85
+ conditions.push(`${columnName} CONTAINS ${formatSurrealValue(ops.contains)}`);
86
+ }
87
+ } else {
88
+ conditions.push(`${columnName} = ${formatSurrealValue(condition)}`);
89
+ }
90
+ } else {
91
+ // Regular properties — check relation metadata first for direction
92
+ const relMeta = allRelationsMetadata[propertyName];
93
+ const isBelongs = relMeta?.kind === 'belongsToOne' || relMeta?.kind === 'belongsToMany';
94
+
95
+ if (relMeta) {
96
+ const predicate = escapeSurrealString(relMeta.predicate);
97
+
98
+ if (Array.isArray(condition)) {
99
+ const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
100
+ if (isBelongs) {
101
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) > 0`);
102
+ } else {
103
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) > 0`);
104
+ }
105
+ } else if (typeof condition === 'object' && condition !== null) {
106
+ const ops = condition as any;
107
+ if (ops.not !== undefined) {
108
+ if (Array.isArray(ops.not)) {
109
+ const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
110
+ if (isBelongs) {
111
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) = 0`);
112
+ } else {
113
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) = 0`);
114
+ }
115
+ } else {
116
+ if (isBelongs) {
117
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${formatSurrealValue(ops.not)}]) = 0`);
118
+ } else {
119
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${formatSurrealValue(ops.not)}]) = 0`);
120
+ }
121
+ }
122
+ }
123
+ } else {
124
+ if (isBelongs) {
125
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${formatSurrealValue(condition)}]) > 0`);
126
+ } else {
127
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${formatSurrealValue(condition)}]) > 0`);
128
+ }
129
+ }
130
+ continue;
131
+ }
132
+
133
+ const propMeta = metadata.properties[propertyName];
134
+ if (!propMeta) continue;
135
+
136
+ const predicate = escapeSurrealString(propMeta.predicate);
137
+ const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(out.uri)' : 'out.uri';
138
+
139
+ if (Array.isArray(condition)) {
140
+ const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
141
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
142
+ } else if (typeof condition === 'object' && condition !== null) {
143
+ const ops = condition as any;
144
+ if (ops.not !== undefined) {
145
+ if (Array.isArray(ops.not)) {
146
+ const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
147
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
148
+ } else {
149
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`);
150
+ }
151
+ }
152
+ const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
153
+ ops.lt !== undefined || ops.lte !== undefined ||
154
+ ops.between !== undefined || ops.contains !== undefined;
155
+ if (hasComparisonOps) {
156
+ conditions.push(`count(->link[WHERE predicate = '${predicate}']) > 0`);
157
+ }
158
+ } else {
159
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(condition)}]) > 0`);
160
+ }
161
+ }
162
+ }
163
+
164
+ return conditions.join(' AND ');
165
+ }
166
+
167
+ // ─── Main Query Builder ─────────────────────────────────────────────────────
168
+
169
+ /**
170
+ * Builds a complete SurrealQL query from a Query object and model metadata.
171
+ *
172
+ * This is the core implementation behind `Ad4mModel.queryToSurrealQL()`.
173
+ * It produces a graph-traversal query that:
174
+ * 1. Filters nodes by required predicates (conformance check)
175
+ * 2. Applies user WHERE conditions
176
+ * 3. Fetches all outgoing links for hydration
177
+ *
178
+ * @param metadata - Model metadata from `getModelMetadata()`
179
+ * @param allRelationsMetadata - Full relation registry (for belongs-to detection)
180
+ * @param query - Query parameters
181
+ * @param modelClass - The model class (for `resolveParentPredicate`)
182
+ * @returns Complete SurrealQL query string
183
+ */
184
+ export function buildSurrealQLQuery(
185
+ metadata: ModelMetadata,
186
+ allRelationsMetadata: Record<string, RelationMetadataEntry>,
187
+ query: Query,
188
+ modelClass: any,
189
+ ): string {
190
+ const { where } = query;
191
+
192
+ // Build graph traversal filters for required predicates
193
+ const graphTraversalFilters: string[] = [];
194
+
195
+ // Parent filter
196
+ if (query.parent) {
197
+ const parentPredicate = resolveParentPredicate(query.parent, modelClass);
198
+ graphTraversalFilters.push(
199
+ `count(<-link[WHERE in.uri = ${formatSurrealValue(query.parent.id)} AND predicate = '${escapeSurrealString(parentPredicate)}']) > 0`
200
+ );
201
+ }
202
+
203
+ // Required property filters
204
+ for (const [, propMeta] of Object.entries(metadata.properties)) {
205
+ if (propMeta.required) {
206
+ if (propMeta.getter) continue;
207
+ if (propMeta.flag && propMeta.initial) {
208
+ graphTraversalFilters.push(
209
+ `count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`
210
+ );
211
+ } else {
212
+ graphTraversalFilters.push(
213
+ `count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`
214
+ );
215
+ }
216
+ }
217
+ }
218
+
219
+ // Fallback: initial-value filters
220
+ if (graphTraversalFilters.length === 0) {
221
+ for (const [, propMeta] of Object.entries(metadata.properties)) {
222
+ if (propMeta.initial) {
223
+ if (propMeta.flag) {
224
+ graphTraversalFilters.push(
225
+ `count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`
226
+ );
227
+ } else {
228
+ graphTraversalFilters.push(
229
+ `count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`
230
+ );
231
+ }
232
+ break;
233
+ }
234
+ }
235
+ }
236
+
237
+ // Fallback: open-world structural matching
238
+ if (graphTraversalFilters.length === 0) {
239
+ const structuralPredicates: string[] = [];
240
+ for (const [, propMeta] of Object.entries(metadata.properties)) {
241
+ if (propMeta.predicate) {
242
+ structuralPredicates.push(`predicate = '${escapeSurrealString(propMeta.predicate)}'`);
243
+ }
244
+ }
245
+ if (metadata.relations) {
246
+ for (const [, relMeta] of Object.entries(metadata.relations)) {
247
+ if (relMeta.predicate) {
248
+ structuralPredicates.push(`predicate = '${escapeSurrealString(relMeta.predicate)}'`);
249
+ }
250
+ }
251
+ }
252
+ if (structuralPredicates.length > 0) {
253
+ graphTraversalFilters.push(
254
+ `count(->link[WHERE (${structuralPredicates.join(' OR ')})]) > 0`
255
+ );
256
+ }
257
+ }
258
+
259
+ // User WHERE clause
260
+ const userWhereClause = buildGraphTraversalWhereClause(metadata, allRelationsMetadata, where);
261
+
262
+ const whereConditions: string[] = [];
263
+ whereConditions.push(...graphTraversalFilters);
264
+ if (userWhereClause) {
265
+ whereConditions.push(userWhereClause);
266
+ }
267
+ whereConditions.push(`count(->link) > 0`);
268
+
269
+ const fullQuery = `
270
+ SELECT
271
+ id AS source,
272
+ uri AS source_uri,
273
+ ->link AS links
274
+ FROM node
275
+ WHERE ${whereConditions.join(' AND ')}
276
+ FETCH links
277
+ `.trim();
278
+
279
+ return fullQuery;
280
+ }