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

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 (128) hide show
  1. package/jest.config.js +4 -4
  2. package/lib/index.cjs +5999 -6046
  3. package/lib/index.js +5977 -6040
  4. package/lib/src/Ad4mClient.d.ts +16 -9
  5. package/lib/src/Ad4mClient.js +25 -46
  6. package/lib/src/Ad4mClient.test.d.ts +1 -0
  7. package/lib/src/Ad4mClient.test.js +1204 -0
  8. package/lib/src/Literal.d.ts +2 -1
  9. package/lib/src/Literal.js +35 -38
  10. package/lib/src/Literal.test.d.ts +1 -0
  11. package/lib/src/Literal.test.js +41 -0
  12. package/lib/src/SmartLiteral.d.ts +2 -1
  13. package/lib/src/SmartLiteral.js +15 -30
  14. package/lib/src/agent/AgentClient.d.ts +4 -1
  15. package/lib/src/agent/AgentClient.js +99 -79
  16. package/lib/src/ai/AIClient.d.ts +2 -1
  17. package/lib/src/ai/AIClient.js +220 -224
  18. package/lib/src/expression/ExpressionClient.d.ts +1 -1
  19. package/lib/src/expression/ExpressionClient.js +86 -73
  20. package/lib/src/index.d.ts +1 -1
  21. package/lib/src/index.js +1 -1
  22. package/lib/src/language/LanguageClient.d.ts +1 -1
  23. package/lib/src/language/LanguageClient.js +52 -52
  24. package/lib/src/model/Ad4mModel.d.ts +157 -937
  25. package/lib/src/model/Ad4mModel.js +212 -2799
  26. package/lib/src/model/Ad4mModel.test.js +1002 -561
  27. package/lib/src/model/decorators.d.ts +94 -426
  28. package/lib/src/model/decorators.js +333 -741
  29. package/lib/src/model/mutation.d.ts +81 -0
  30. package/lib/src/model/mutation.js +317 -0
  31. package/lib/src/model/parentUtils.d.ts +32 -0
  32. package/lib/src/model/parentUtils.js +64 -0
  33. package/lib/src/model/prolog/generatePrologFacts.d.ts +36 -0
  34. package/lib/src/model/prolog/generatePrologFacts.js +139 -0
  35. package/lib/src/model/prolog/index.d.ts +1 -0
  36. package/lib/src/model/prolog/index.js +1 -0
  37. package/lib/src/model/query/ModelQueryBuilder.d.ts +82 -0
  38. package/lib/src/model/query/ModelQueryBuilder.js +115 -0
  39. package/lib/src/model/query/QueryBuilder.d.ts +101 -0
  40. package/lib/src/model/query/QueryBuilder.js +193 -0
  41. package/lib/src/model/query/SurrealQueryBuilder.d.ts +48 -0
  42. package/lib/src/model/query/SurrealQueryBuilder.js +371 -0
  43. package/lib/src/model/query/fetchInstance.d.ts +24 -0
  44. package/lib/src/model/query/fetchInstance.js +144 -0
  45. package/lib/src/model/query/hydration.d.ts +54 -0
  46. package/lib/src/model/query/hydration.js +214 -0
  47. package/lib/src/model/query/operations.d.ts +59 -0
  48. package/lib/src/model/query/operations.js +384 -0
  49. package/lib/src/model/query/snapshot.d.ts +59 -0
  50. package/lib/src/model/query/snapshot.js +106 -0
  51. package/lib/src/model/query/surrealCompiler.d.ts +42 -0
  52. package/lib/src/model/query/surrealCompiler.js +304 -0
  53. package/lib/src/model/schema/fromJSONSchema.d.ts +67 -0
  54. package/lib/src/model/schema/fromJSONSchema.js +264 -0
  55. package/lib/src/model/schema/metadata.d.ts +15 -0
  56. package/lib/src/model/schema/metadata.js +112 -0
  57. package/lib/src/model/subscription.d.ts +47 -0
  58. package/lib/src/model/subscription.js +231 -0
  59. package/lib/src/model/transaction.d.ts +27 -0
  60. package/lib/src/model/transaction.js +32 -0
  61. package/lib/src/model/types.d.ts +195 -0
  62. package/lib/src/model/types.js +8 -0
  63. package/lib/src/model/util.js +7 -7
  64. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +5 -1
  65. package/lib/src/neighbourhood/NeighbourhoodClient.js +263 -181
  66. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +2 -1
  67. package/lib/src/neighbourhood/NeighbourhoodProxy.js +13 -28
  68. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +1 -5
  69. package/lib/src/perspectives/PerspectiveClient.d.ts +9 -9
  70. package/lib/src/perspectives/PerspectiveClient.js +316 -240
  71. package/lib/src/perspectives/PerspectiveProxy.d.ts +54 -92
  72. package/lib/src/perspectives/PerspectiveProxy.js +803 -444
  73. package/lib/src/runtime/RuntimeClient.d.ts +5 -1
  74. package/lib/src/runtime/RuntimeClient.js +412 -238
  75. package/lib/src/shacl/SHACLFlow.test.js +164 -105
  76. package/lib/src/shacl/SHACLShape.d.ts +17 -3
  77. package/lib/src/shacl/SHACLShape.js +127 -90
  78. package/lib/src/shacl/SHACLShape.test.js +244 -176
  79. package/lib/src/utils.d.ts +8 -0
  80. package/lib/src/utils.js +21 -7
  81. package/package.json +8 -13
  82. package/src/Ad4mClient.test.ts +1564 -1315
  83. package/src/Ad4mClient.ts +55 -54
  84. package/src/Literal.test.ts +45 -26
  85. package/src/Literal.ts +82 -66
  86. package/src/SmartLiteral.ts +74 -58
  87. package/src/agent/AgentClient.ts +144 -99
  88. package/src/ai/AIClient.ts +409 -359
  89. package/src/expression/ExpressionClient.ts +142 -96
  90. package/src/index.ts +1 -1
  91. package/src/language/LanguageClient.ts +137 -113
  92. package/src/model/Ad4mModel.test.ts +1128 -647
  93. package/src/model/Ad4mModel.ts +485 -3249
  94. package/src/model/IMPROVEMENTS.md +482 -0
  95. package/src/model/PREDICATE_COLLISION_FIX.md +651 -0
  96. package/src/model/README.md +317 -0
  97. package/src/model/SHACL_MUTATION_DECOUPLING.md +356 -0
  98. package/src/model/SUBSCRIPTION_STRATEGY.md +317 -0
  99. package/src/model/TC39_STAGE_3_DECORATORS.md +609 -0
  100. package/src/model/decorators.ts +689 -1046
  101. package/src/model/mutation.ts +461 -0
  102. package/src/model/parentUtils.ts +91 -0
  103. package/src/model/prolog/generatePrologFacts.ts +176 -0
  104. package/src/model/prolog/index.ts +1 -0
  105. package/src/model/query/ModelQueryBuilder.ts +173 -0
  106. package/src/model/query/fetchInstance.ts +181 -0
  107. package/src/model/query/hydration.ts +273 -0
  108. package/src/model/query/operations.ts +510 -0
  109. package/src/model/query/snapshot.ts +126 -0
  110. package/src/model/query/surrealCompiler.ts +376 -0
  111. package/src/model/schema/fromJSONSchema.ts +411 -0
  112. package/src/model/schema/metadata.ts +148 -0
  113. package/src/model/subscription.ts +307 -0
  114. package/src/model/transaction.ts +60 -0
  115. package/src/model/types.ts +207 -0
  116. package/src/model/util.ts +47 -48
  117. package/src/neighbourhood/NeighbourhoodClient.ts +393 -251
  118. package/src/neighbourhood/NeighbourhoodProxy.test.ts +3 -7
  119. package/src/neighbourhood/NeighbourhoodProxy.ts +58 -40
  120. package/src/perspectives/PerspectiveClient.ts +779 -540
  121. package/src/perspectives/PerspectiveProxy.ts +2860 -2053
  122. package/src/runtime/RuntimeClient.ts +775 -476
  123. package/src/shacl/SHACLFlow.test.ts +196 -129
  124. package/src/shacl/SHACLShape.test.ts +284 -190
  125. package/src/shacl/SHACLShape.ts +225 -172
  126. package/src/utils.ts +31 -17
  127. package/tsconfig.json +9 -10
  128. package/src/model/Subject.ts +0 -159
@@ -0,0 +1,376 @@
1
+ /**
2
+ * Pure SurrealQL compiler — translates high-level `Query<T>` objects into
3
+ * raw SurrealQL strings.
4
+ *
5
+ * All functions are stateless — they take `ModelMetadata` (and optionally a
6
+ * `Query`) as plain data and return strings or booleans. No dependency on the
7
+ * `Ad4mModel` class, which means they can be imported by tests and other
8
+ * modules without pulling in the full class graph.
9
+ *
10
+ * `Ad4mModel` keeps thin static wrapper methods with the original signatures so
11
+ * the public API is unchanged.
12
+ */
13
+
14
+ import { escapeSurrealString } from "../../utils";
15
+ import {
16
+ ModelMetadata,
17
+ Query,
18
+ Where,
19
+ WhereCondition,
20
+ ParentQueryByPredicate,
21
+ } from "../types";
22
+
23
+ // ── Value formatting ────────────────────────────────────────────────────────
24
+
25
+ /**
26
+ * Formats a value for use in SurrealQL queries.
27
+ *
28
+ * - Strings: wrapped in single quotes, special characters escaped
29
+ * - Numbers / booleans: converted to string
30
+ * - Arrays: recursively formatted, wrapped in `[...]`
31
+ */
32
+ export function formatSurrealValue(value: any): string {
33
+ if (typeof value === "string") {
34
+ const escaped = value
35
+ .replace(/\\/g, "\\\\")
36
+ .replace(/'/g, "\\'")
37
+ .replace(/"/g, '\\"')
38
+ .replace(/\n/g, "\\n")
39
+ .replace(/\r/g, "\\r")
40
+ .replace(/\t/g, "\\t");
41
+ return `'${escaped}'`;
42
+ } else if (typeof value === "number" || typeof value === "boolean") {
43
+ return String(value);
44
+ } else if (Array.isArray(value)) {
45
+ return `[${value.map(formatSurrealValue).join(", ")}]`;
46
+ } else {
47
+ return String(value);
48
+ }
49
+ }
50
+
51
+ // ── WHERE clause builders ───────────────────────────────────────────────────
52
+
53
+ /**
54
+ * Builds graph-traversal WHERE clause filters (`->link[WHERE ...]`).
55
+ * Used by `buildSurrealQuery` — more efficient than subqueries because
56
+ * SurrealDB can use graph indexes.
57
+ */
58
+ export function buildGraphTraversalWhereClause(
59
+ metadata: ModelMetadata,
60
+ where?: Where,
61
+ ): string {
62
+ if (!where) return "";
63
+
64
+ const conditions: string[] = [];
65
+
66
+ for (const [propertyName, condition] of Object.entries(where)) {
67
+ const isSpecial = ["base", "id", "author", "timestamp"].includes(
68
+ propertyName,
69
+ );
70
+
71
+ if (isSpecial) {
72
+ if (propertyName === "author" || propertyName === "timestamp") {
73
+ continue; // filtered post-query in JavaScript
74
+ }
75
+
76
+ const columnName = "uri"; // base/id → uri in node table
77
+
78
+ if (Array.isArray(condition)) {
79
+ const formattedValues = condition.map(formatSurrealValue).join(", ");
80
+ conditions.push(`${columnName} IN [${formattedValues}]`);
81
+ } else if (typeof condition === "object" && condition !== null) {
82
+ const ops = condition as any;
83
+ if (ops.not !== undefined) {
84
+ if (Array.isArray(ops.not)) {
85
+ const formattedValues = ops.not.map(formatSurrealValue).join(", ");
86
+ conditions.push(`${columnName} NOT IN [${formattedValues}]`);
87
+ } else {
88
+ conditions.push(`${columnName} != ${formatSurrealValue(ops.not)}`);
89
+ }
90
+ }
91
+ if (
92
+ ops.between !== undefined &&
93
+ Array.isArray(ops.between) &&
94
+ ops.between.length === 2
95
+ ) {
96
+ conditions.push(
97
+ `${columnName} >= ${formatSurrealValue(ops.between[0])} AND ${columnName} <= ${formatSurrealValue(ops.between[1])}`,
98
+ );
99
+ }
100
+ if (ops.gt !== undefined)
101
+ conditions.push(`${columnName} > ${formatSurrealValue(ops.gt)}`);
102
+ if (ops.gte !== undefined)
103
+ conditions.push(`${columnName} >= ${formatSurrealValue(ops.gte)}`);
104
+ if (ops.lt !== undefined)
105
+ conditions.push(`${columnName} < ${formatSurrealValue(ops.lt)}`);
106
+ if (ops.lte !== undefined)
107
+ conditions.push(`${columnName} <= ${formatSurrealValue(ops.lte)}`);
108
+ if (ops.contains !== undefined)
109
+ conditions.push(
110
+ `${columnName} CONTAINS ${formatSurrealValue(ops.contains)}`,
111
+ );
112
+ } else {
113
+ conditions.push(`${columnName} = ${formatSurrealValue(condition)}`);
114
+ }
115
+ } else {
116
+ const propMeta = metadata.properties[propertyName];
117
+ if (!propMeta) {
118
+ // ── Relation-based where clause ────────────────────────────────────
119
+ // If the where key is a relation name (e.g. `where: { post: postId }`),
120
+ // generate a graph-traversal filter on the link predicate.
121
+ //
122
+ // • Reverse relations (@BelongsToOne / @BelongsToMany):
123
+ // The link is stored as parentId --predicate--> thisId.
124
+ // From this node we traverse <-link (incoming) and check in.uri.
125
+ //
126
+ // • Forward relations (@HasMany / @HasOne):
127
+ // The link is stored as thisId --predicate--> childId.
128
+ // From this node we traverse ->link (outgoing) and check out.uri.
129
+ const relMeta = metadata.relations[propertyName];
130
+ if (!relMeta) continue;
131
+
132
+ const predicate = escapeSurrealString(relMeta.predicate);
133
+ const isReverse = relMeta.direction === "reverse";
134
+ const arrow = isReverse ? "<-" : "->";
135
+ const uriField = isReverse ? "in.uri" : "out.uri";
136
+
137
+ if (Array.isArray(condition)) {
138
+ const formattedValues = condition.map(formatSurrealValue).join(", ");
139
+ conditions.push(
140
+ `count(${arrow}link[WHERE predicate = '${predicate}' AND ${uriField} IN [${formattedValues}]]) > 0`,
141
+ );
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
147
+ .map(formatSurrealValue)
148
+ .join(", ");
149
+ conditions.push(
150
+ `count(${arrow}link[WHERE predicate = '${predicate}' AND ${uriField} IN [${formattedValues}]]) = 0`,
151
+ );
152
+ } else {
153
+ conditions.push(
154
+ `count(${arrow}link[WHERE predicate = '${predicate}' AND ${uriField} = ${formatSurrealValue(ops.not)}]) = 0`,
155
+ );
156
+ }
157
+ }
158
+ // Comparison operators on relation IDs are unusual but handled:
159
+ // they'll be caught in JS post-filtering (step 6 in operations.ts).
160
+ } else {
161
+ conditions.push(
162
+ `count(${arrow}link[WHERE predicate = '${predicate}' AND ${uriField} = ${formatSurrealValue(condition)}]) > 0`,
163
+ );
164
+ }
165
+
166
+ continue;
167
+ }
168
+
169
+ const predicate = escapeSurrealString(propMeta.predicate);
170
+ // Scalar properties (resolveLanguage === "literal" or unset) store values as
171
+ // literal:// URIs — use fn::parse_literal to unwrap before comparing.
172
+ // Only non-literal custom languages (e.g. IPFS) store raw expression URLs.
173
+ const targetField =
174
+ !propMeta.resolveLanguage || propMeta.resolveLanguage === "literal"
175
+ ? "fn::parse_literal(out.uri)"
176
+ : "out.uri";
177
+
178
+ if (Array.isArray(condition)) {
179
+ const formattedValues = condition.map(formatSurrealValue).join(", ");
180
+ conditions.push(
181
+ `count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`,
182
+ );
183
+ } else if (typeof condition === "object" && condition !== null) {
184
+ const ops = condition as any;
185
+ if (ops.not !== undefined) {
186
+ if (Array.isArray(ops.not)) {
187
+ const formattedValues = ops.not.map(formatSurrealValue).join(", ");
188
+ conditions.push(
189
+ `count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`,
190
+ );
191
+ } else {
192
+ conditions.push(
193
+ `count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`,
194
+ );
195
+ }
196
+ }
197
+ const hasComparisonOps =
198
+ ops.gt !== undefined ||
199
+ ops.gte !== undefined ||
200
+ ops.lt !== undefined ||
201
+ ops.lte !== undefined ||
202
+ ops.between !== undefined ||
203
+ ops.contains !== undefined;
204
+ if (hasComparisonOps) {
205
+ conditions.push(
206
+ `count(->link[WHERE predicate = '${predicate}']) > 0`,
207
+ );
208
+ }
209
+ } else {
210
+ conditions.push(
211
+ `count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(condition)}]) > 0`,
212
+ );
213
+ }
214
+ }
215
+ }
216
+
217
+ return conditions.join(" AND ");
218
+ }
219
+
220
+ // ── Main query builders ─────────────────────────────────────────────────────
221
+
222
+ /**
223
+ * Builds the SurrealQL SELECT query for a given model metadata + query params.
224
+ * This is the extracted, pure-function form of `Ad4mModel.queryToSurrealQL`.
225
+ */
226
+ export function buildSurrealQuery(
227
+ metadata: ModelMetadata,
228
+ query: Query,
229
+ ): string {
230
+ const { where, parent: linkedFrom } = query as Query & {
231
+ parent?: ParentQueryByPredicate;
232
+ };
233
+
234
+ const graphTraversalFilters: string[] = [];
235
+ for (const [, propMeta] of Object.entries(metadata.properties)) {
236
+ if (propMeta.required) {
237
+ if (propMeta.flag && propMeta.initial) {
238
+ graphTraversalFilters.push(
239
+ `count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`,
240
+ );
241
+ } else {
242
+ graphTraversalFilters.push(
243
+ `count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`,
244
+ );
245
+ }
246
+ }
247
+ }
248
+
249
+ if (graphTraversalFilters.length === 0) {
250
+ for (const [, propMeta] of Object.entries(metadata.properties)) {
251
+ if (propMeta.initial) {
252
+ if (propMeta.flag) {
253
+ graphTraversalFilters.push(
254
+ `count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`,
255
+ );
256
+ } else {
257
+ graphTraversalFilters.push(
258
+ `count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`,
259
+ );
260
+ }
261
+ break;
262
+ }
263
+ }
264
+ }
265
+
266
+ // Last-resort fallback: require at least one link with any of the model's
267
+ // own declared predicates (properties OR relations). This prevents matching
268
+ // SDNA registration nodes (which use sh://, ad4m://, rdf:// predicates) for
269
+ // models that have no @Flag, no required, and no initial-valued properties.
270
+ if (graphTraversalFilters.length === 0) {
271
+ const allPredicates = [
272
+ ...Object.values(metadata.properties).map((p) => p.predicate),
273
+ ...Object.values(metadata.relations).map((r) => r.predicate),
274
+ ].filter(Boolean);
275
+
276
+ if (allPredicates.length > 0) {
277
+ const predicateConditions = allPredicates
278
+ .map(
279
+ (p) =>
280
+ `count(->link[WHERE predicate = '${escapeSurrealString(p)}']) > 0`,
281
+ )
282
+ .join(" OR ");
283
+ graphTraversalFilters.push(`(${predicateConditions})`);
284
+ }
285
+ }
286
+
287
+ const userWhereClause = buildGraphTraversalWhereClause(metadata, where);
288
+
289
+ const whereConditions: string[] = [
290
+ ...graphTraversalFilters,
291
+ ...(userWhereClause ? [userWhereClause] : []),
292
+ ...(linkedFrom
293
+ ? [
294
+ `count(<-link[WHERE predicate = '${escapeSurrealString(linkedFrom.predicate)}' AND in.uri = '${escapeSurrealString(linkedFrom.id)}']) > 0`,
295
+ ]
296
+ : []),
297
+ ];
298
+
299
+ // Ensure we always have at least one condition to produce valid SurrealQL
300
+ const whereClause =
301
+ whereConditions.length > 0
302
+ ? whereConditions.join(" AND ")
303
+ : "count(->link) > 0";
304
+
305
+ return `
306
+ SELECT
307
+ id AS source,
308
+ uri AS source_uri,
309
+ (SELECT predicate, out.uri AS target, author, timestamp FROM link WHERE in = $parent.id ORDER BY timestamp ASC) AS links
310
+ FROM node
311
+ WHERE ${whereClause}
312
+ `.trim();
313
+ }
314
+
315
+ /**
316
+ * Builds a count query (same as `buildSurrealQuery` but without LIMIT/OFFSET).
317
+ */
318
+ export function buildSurrealCountQuery(
319
+ metadata: ModelMetadata,
320
+ query: Query,
321
+ ): string {
322
+ const countQuery = { ...query };
323
+ delete countQuery.limit;
324
+ delete countQuery.offset;
325
+ return buildSurrealQuery(metadata, countQuery);
326
+ }
327
+
328
+ // ── Post-query filtering ────────────────────────────────────────────────────
329
+
330
+ /**
331
+ * Checks whether a single value satisfies a WhereCondition.
332
+ * Used for post-query JavaScript filtering of operators that SurrealDB
333
+ * cannot evaluate reliably (gt/gte/lt/lte/between/contains on literals).
334
+ */
335
+ export function matchesCondition(
336
+ value: any,
337
+ condition: WhereCondition,
338
+ ): boolean {
339
+ if (Array.isArray(condition)) {
340
+ return (condition as any[]).includes(value);
341
+ }
342
+
343
+ if (typeof condition === "object" && condition !== null) {
344
+ const ops = condition as any;
345
+
346
+ let allMet = true;
347
+ if (ops.not !== undefined)
348
+ allMet =
349
+ allMet &&
350
+ (Array.isArray(ops.not)
351
+ ? !(ops.not as any[]).includes(value)
352
+ : value !== ops.not);
353
+ if (
354
+ ops.between !== undefined &&
355
+ Array.isArray(ops.between) &&
356
+ ops.between.length === 2
357
+ )
358
+ allMet = allMet && value >= ops.between[0] && value <= ops.between[1];
359
+ if (ops.gt !== undefined) allMet = allMet && value > ops.gt;
360
+ if (ops.gte !== undefined) allMet = allMet && value >= ops.gte;
361
+ if (ops.lt !== undefined) allMet = allMet && value < ops.lt;
362
+ if (ops.lte !== undefined) allMet = allMet && value <= ops.lte;
363
+ if (ops.contains !== undefined) {
364
+ if (typeof value === "string") {
365
+ allMet = allMet && value.includes(String(ops.contains));
366
+ } else if (Array.isArray(value)) {
367
+ allMet = allMet && value.includes(ops.contains);
368
+ } else {
369
+ allMet = false;
370
+ }
371
+ }
372
+ return allMet;
373
+ }
374
+
375
+ return value === condition;
376
+ }