@coasys/ad4m 0.12.0-rc1-dev.2 → 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 (153) hide show
  1. package/jest.config.js +10 -3
  2. package/lib/index.cjs +6872 -5886
  3. package/lib/index.js +6868 -5874
  4. package/lib/src/Ad4mClient.d.ts +9 -16
  5. package/lib/src/Ad4mClient.js +46 -25
  6. package/lib/src/Literal.d.ts +1 -2
  7. package/lib/src/Literal.js +38 -35
  8. package/lib/src/SmartLiteral.d.ts +1 -2
  9. package/lib/src/SmartLiteral.js +30 -15
  10. package/lib/src/agent/AgentClient.d.ts +1 -4
  11. package/lib/src/agent/AgentClient.js +79 -99
  12. package/lib/src/ai/AIClient.d.ts +1 -2
  13. package/lib/src/ai/AIClient.js +224 -220
  14. package/lib/src/expression/ExpressionClient.d.ts +1 -1
  15. package/lib/src/expression/ExpressionClient.js +73 -86
  16. package/lib/src/index.d.ts +1 -1
  17. package/lib/src/index.js +1 -1
  18. package/lib/src/language/LanguageClient.d.ts +1 -1
  19. package/lib/src/language/LanguageClient.js +52 -52
  20. package/lib/src/model/Ad4mModel.d.ts +1351 -144
  21. package/lib/src/model/Ad4mModel.js +3737 -228
  22. package/lib/src/model/Ad4mModel.test.js +522 -979
  23. package/lib/src/model/Subject.d.ts +3 -3
  24. package/lib/src/model/Subject.js +25 -25
  25. package/lib/src/model/decorators.d.ts +444 -100
  26. package/lib/src/model/decorators.js +686 -321
  27. package/lib/src/model/util.d.ts +6 -6
  28. package/lib/src/model/util.js +24 -24
  29. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +1 -5
  30. package/lib/src/neighbourhood/NeighbourhoodClient.js +179 -242
  31. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +1 -2
  32. package/lib/src/neighbourhood/NeighbourhoodProxy.js +28 -13
  33. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +5 -1
  34. package/lib/src/perspectives/PerspectiveClient.d.ts +9 -9
  35. package/lib/src/perspectives/PerspectiveClient.js +240 -316
  36. package/lib/src/perspectives/PerspectiveProxy.d.ts +99 -61
  37. package/lib/src/perspectives/PerspectiveProxy.js +485 -832
  38. package/lib/src/runtime/RuntimeClient.d.ts +1 -5
  39. package/lib/src/runtime/RuntimeClient.js +238 -412
  40. package/lib/src/shacl/SHACLFlow.test.js +105 -164
  41. package/lib/src/shacl/SHACLShape.d.ts +12 -17
  42. package/lib/src/shacl/SHACLShape.js +115 -128
  43. package/lib/src/shacl/SHACLShape.test.js +176 -244
  44. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  45. package/lib/src/shims/type-graphql.d.ts +32 -0
  46. package/lib/src/src/Ad4mClient.d.ts +28 -0
  47. package/lib/src/src/Address.d.ts +1 -0
  48. package/lib/src/src/DID.d.ts +1 -0
  49. package/lib/src/src/Exception.d.ts +7 -0
  50. package/lib/src/src/Literal.d.ts +7 -0
  51. package/lib/src/src/PubSub.d.ts +17 -0
  52. package/lib/src/src/SmartLiteral.d.ts +12 -0
  53. package/lib/src/src/agent/Agent.d.ts +110 -0
  54. package/lib/src/src/agent/AgentClient.d.ts +62 -0
  55. package/lib/src/src/agent/AgentResolver.d.ts +30 -0
  56. package/lib/src/src/agent/AgentStatus.d.ts +8 -0
  57. package/lib/src/src/ai/AIClient.d.ts +32 -0
  58. package/lib/src/src/ai/AIResolver.d.ts +75 -0
  59. package/lib/src/src/ai/Tasks.d.ts +37 -0
  60. package/lib/src/src/buildSchema.d.ts +1 -0
  61. package/lib/src/src/expression/Expression.d.ts +28 -0
  62. package/lib/src/src/expression/ExpressionClient.d.ts +13 -0
  63. package/lib/src/src/expression/ExpressionRef.d.ts +9 -0
  64. package/lib/src/src/expression/ExpressionResolver.d.ts +10 -0
  65. package/lib/src/src/index.d.ts +35 -0
  66. package/lib/src/src/jestSetup.d.ts +1 -0
  67. package/lib/src/src/language/Icon.d.ts +4 -0
  68. package/lib/src/src/language/Language.d.ts +206 -0
  69. package/lib/src/src/language/LanguageClient.d.ts +17 -0
  70. package/lib/src/src/language/LanguageContext.d.ts +37 -0
  71. package/lib/src/src/language/LanguageHandle.d.ts +9 -0
  72. package/lib/src/src/language/LanguageMeta.d.ts +35 -0
  73. package/lib/src/src/language/LanguageRef.d.ts +6 -0
  74. package/lib/src/src/language/LanguageResolver.d.ts +19 -0
  75. package/lib/src/src/links/Links.d.ts +39 -0
  76. package/lib/src/src/links/Links.test.d.ts +1 -0
  77. package/lib/src/src/model/Ad4mModel.d.ts +1438 -0
  78. package/lib/src/src/model/Ad4mModel.test.d.ts +1 -0
  79. package/lib/src/src/model/Subject.d.ts +25 -0
  80. package/lib/src/src/model/decorators.d.ts +545 -0
  81. package/lib/src/src/model/util.d.ts +12 -0
  82. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +10 -0
  83. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +25 -0
  84. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +19 -0
  85. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +1 -0
  86. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +24 -0
  87. package/lib/src/src/perspectives/LinkQuery.d.ts +11 -0
  88. package/lib/src/src/perspectives/Perspective.d.ts +38 -0
  89. package/lib/src/src/perspectives/Perspective.test.d.ts +1 -0
  90. package/lib/src/src/perspectives/PerspectiveClient.d.ts +97 -0
  91. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +9 -0
  92. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +18 -0
  93. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +865 -0
  94. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +57 -0
  95. package/lib/src/src/runtime/RuntimeClient.d.ts +56 -0
  96. package/lib/src/src/runtime/RuntimeResolver.d.ts +132 -0
  97. package/lib/src/src/shacl/SHACLFlow.d.ts +171 -0
  98. package/lib/src/src/shacl/SHACLFlow.test.d.ts +1 -0
  99. package/lib/src/src/shacl/SHACLShape.d.ts +117 -0
  100. package/lib/src/src/shacl/SHACLShape.test.d.ts +1 -0
  101. package/lib/src/src/typeDefs.d.ts +1 -0
  102. package/lib/src/src/unwrapApolloResult.d.ts +2 -0
  103. package/lib/src/src/utils.d.ts +25 -0
  104. package/lib/src/utils.d.ts +0 -8
  105. package/lib/src/utils.js +7 -21
  106. package/package.json +15 -14
  107. package/src/Ad4mClient.test.ts +1315 -1564
  108. package/src/Ad4mClient.ts +54 -55
  109. package/src/Literal.test.ts +26 -45
  110. package/src/Literal.ts +66 -82
  111. package/src/SmartLiteral.ts +58 -74
  112. package/src/agent/AgentClient.ts +99 -144
  113. package/src/ai/AIClient.ts +359 -409
  114. package/src/expression/ExpressionClient.ts +96 -142
  115. package/src/index.ts +1 -1
  116. package/src/language/LanguageClient.ts +113 -137
  117. package/src/model/Ad4mModel.test.ts +616 -1114
  118. package/src/model/Ad4mModel.ts +4361 -451
  119. package/src/model/Subject.ts +159 -0
  120. package/src/model/decorators.ts +1168 -667
  121. package/src/model/util.ts +54 -53
  122. package/src/neighbourhood/NeighbourhoodClient.ts +266 -392
  123. package/src/neighbourhood/NeighbourhoodProxy.test.ts +7 -3
  124. package/src/neighbourhood/NeighbourhoodProxy.ts +40 -58
  125. package/src/perspectives/PerspectiveClient.ts +540 -779
  126. package/src/perspectives/PerspectiveProxy.ts +2067 -2860
  127. package/src/runtime/RuntimeClient.ts +476 -775
  128. package/src/shacl/SHACLFlow.test.ts +129 -196
  129. package/src/shacl/SHACLShape.test.ts +190 -284
  130. package/src/shacl/SHACLShape.ts +200 -224
  131. package/src/utils.ts +17 -31
  132. package/tsconfig.json +10 -9
  133. package/src/model/IMPROVEMENTS.md +0 -482
  134. package/src/model/PREDICATE_COLLISION_FIX.md +0 -651
  135. package/src/model/README.md +0 -317
  136. package/src/model/SHACL_MUTATION_DECOUPLING.md +0 -356
  137. package/src/model/SUBSCRIPTION_STRATEGY.md +0 -317
  138. package/src/model/TC39_STAGE_3_DECORATORS.md +0 -609
  139. package/src/model/mutation.ts +0 -461
  140. package/src/model/parentUtils.ts +0 -91
  141. package/src/model/prolog/generatePrologFacts.ts +0 -176
  142. package/src/model/prolog/index.ts +0 -1
  143. package/src/model/query/ModelQueryBuilder.ts +0 -173
  144. package/src/model/query/fetchInstance.ts +0 -181
  145. package/src/model/query/hydration.ts +0 -273
  146. package/src/model/query/operations.ts +0 -510
  147. package/src/model/query/snapshot.ts +0 -126
  148. package/src/model/query/surrealCompiler.ts +0 -376
  149. package/src/model/schema/fromJSONSchema.ts +0 -411
  150. package/src/model/schema/metadata.ts +0 -148
  151. package/src/model/subscription.ts +0 -307
  152. package/src/model/transaction.ts +0 -60
  153. package/src/model/types.ts +0 -207
@@ -1,23 +1,5 @@
1
1
  import { Ad4mModel } from "./Ad4mModel";
2
- import { Model, Property, HasMany, Flag } from "./decorators";
3
- import { Literal } from "../Literal";
4
- import { resolveParentPredicate, normalizeParentQuery } from "./parentUtils";
5
-
6
- // ── Shared test fixtures ──────────────────────────────────────────────────────
7
- // Defined once at module level — used by queryToSurrealQL,
8
- // instancesFromSurrealResult, and hydration describe blocks alike.
9
-
10
- @Model({ name: "Recipe" })
11
- class Recipe extends Ad4mModel {
12
- @Property({ through: "recipe://name", required: true })
13
- name: string = "";
14
-
15
- @Property({ through: "recipe://rating", required: true })
16
- rating: number = 0;
17
-
18
- @HasMany({ through: "recipe://ingredient" })
19
- ingredients: string[] = [];
20
- }
2
+ import { Model, Property, Optional, ReadOnly, HasMany, Flag } from "./decorators";
21
3
 
22
4
  describe("Ad4mModel.getModelMetadata()", () => {
23
5
  it("should extract basic model metadata with className", () => {
@@ -25,7 +7,7 @@ describe("Ad4mModel.getModelMetadata()", () => {
25
7
  class SimpleModel extends Ad4mModel {}
26
8
 
27
9
  const metadata = SimpleModel.getModelMetadata();
28
-
10
+
29
11
  expect(metadata.className).toBe("SimpleModel");
30
12
  expect(metadata.properties).toEqual({});
31
13
  expect(metadata.relations).toEqual({});
@@ -34,67 +16,64 @@ describe("Ad4mModel.getModelMetadata()", () => {
34
16
  it("should extract property metadata with all fields", () => {
35
17
  @Model({ name: "PropertyModel" })
36
18
  class PropertyModel extends Ad4mModel {
37
- @Property({
38
- through: "test://name",
39
- resolveLanguage: "literal",
40
- required: true,
41
- })
19
+ @Property({ through: "test://name", resolveLanguage: "literal" })
42
20
  name: string = "";
43
-
44
- @Property({ through: "test://optional" })
21
+
22
+ @Optional({ through: "test://optional" })
45
23
  optional: string = "";
46
-
47
- @Property({ through: "test://readonly", readOnly: true })
24
+
25
+ @ReadOnly({ through: "test://readonly", prologGetter: "custom_getter" })
48
26
  readonly: string = "";
49
-
27
+
50
28
  @Flag({ through: "test://type", value: "test://flag" })
51
29
  type: string = "";
52
30
  }
53
31
 
54
32
  const metadata = PropertyModel.getModelMetadata();
55
-
33
+
56
34
  // Should have 4 properties
57
35
  expect(Object.keys(metadata.properties)).toHaveLength(4);
58
-
36
+
59
37
  // Verify "name" property
60
38
  expect(metadata.properties.name.predicate).toBe("test://name");
61
- expect(metadata.properties.name.required).toBe(true);
62
- expect(metadata.properties.name.readOnly).toBeFalsy();
39
+ expect(metadata.properties.name.required).toBe(false);
40
+ expect(metadata.properties.name.readOnly).toBe(false);
63
41
  expect(metadata.properties.name.resolveLanguage).toBe("literal");
64
-
42
+
65
43
  // Verify "optional" property
66
44
  expect(metadata.properties.optional.predicate).toBe("test://optional");
67
- expect(metadata.properties.optional.readOnly).toBeFalsy();
68
-
45
+ expect(metadata.properties.optional.readOnly).toBe(false);
46
+
69
47
  // Verify "readonly" property
70
48
  expect(metadata.properties.readonly.predicate).toBe("test://readonly");
71
49
  expect(metadata.properties.readonly.readOnly).toBe(true);
72
-
50
+ expect(metadata.properties.readonly.prologGetter).toBe("custom_getter");
51
+
73
52
  // Verify "type" property (flag)
74
53
  expect(metadata.properties.type.predicate).toBe("test://type");
75
54
  expect(metadata.properties.type.flag).toBe(true);
76
55
  expect(metadata.properties.type.initial).toBe("test://flag");
77
56
  });
78
57
 
79
- it("should extract collection metadata", () => {
80
- @Model({ name: "CollectionModel" })
81
- class CollectionModel extends Ad4mModel {
58
+ it("should extract relation metadata with various options", () => {
59
+ @Model({ name: "RelationModel" })
60
+ class RelationModel extends Ad4mModel {
82
61
  @HasMany({ through: "test://items" })
83
62
  items: string[] = [];
84
-
63
+
85
64
  @HasMany({ through: "test://local", local: true })
86
65
  local: string[] = [];
87
66
  }
88
67
 
89
- const metadata = CollectionModel.getModelMetadata();
90
-
91
- // Should have 2 collections
68
+ const metadata = RelationModel.getModelMetadata();
69
+
70
+ // Should have 2 relations
92
71
  expect(Object.keys(metadata.relations)).toHaveLength(2);
93
-
94
- // Verify "items" collection
72
+
73
+ // Verify "items" relation
95
74
  expect(metadata.relations.items.predicate).toBe("test://items");
96
-
97
- // Verify "local" collection
75
+
76
+ // Verify "local" relation
98
77
  expect(metadata.relations.local.predicate).toBe("test://local");
99
78
  expect(metadata.relations.local.local).toBe(true);
100
79
  });
@@ -102,120 +81,111 @@ describe("Ad4mModel.getModelMetadata()", () => {
102
81
  it("should extract transform function from property metadata", () => {
103
82
  @Model({ name: "TransformModel" })
104
83
  class TransformModel extends Ad4mModel {
105
- @Property({
84
+ @Optional({
106
85
  through: "test://data",
107
- transform: (value: string) => value.toUpperCase(),
86
+ transform: (value: string) => value.toUpperCase()
108
87
  })
109
88
  data: string = "";
110
89
  }
111
90
 
112
91
  const metadata = TransformModel.getModelMetadata();
113
-
92
+
114
93
  // Assert transform is a function
115
94
  expect(typeof metadata.properties.data.transform).toBe("function");
116
-
95
+
117
96
  // Test the transform function
118
97
  const transformed = metadata.properties.data.transform!("test");
119
98
  expect(transformed).toBe("TEST");
120
99
  });
121
100
 
122
- it("should extract custom SurrealQL getter from property metadata", () => {
101
+ it("should extract custom getter and setter from property metadata", () => {
123
102
  @Model({ name: "CustomModel" })
124
103
  class CustomModel extends Ad4mModel {
125
- @Property({
104
+ @Optional({
126
105
  through: "test://computed",
127
- getter: "(<-link[WHERE predicate = 'test://value'].in.uri)[0]",
106
+ prologGetter: "triple(Base, 'test://value', V), Value is V * 2",
107
+ prologSetter: "Value is V / 2, Actions = [{action: 'setSingleTarget', source: 'this', predicate: 'test://value', target: Value}]"
128
108
  })
129
- computed: string = "";
109
+ computed: number = 0;
130
110
  }
131
111
 
132
112
  const metadata = CustomModel.getModelMetadata();
133
-
134
- // Assert getter contains the custom SurrealQL code
135
- expect(metadata.properties.computed.getter).toContain("test://value");
113
+
114
+ // Assert prologGetter and prologSetter contain the custom code
115
+ expect(metadata.properties.computed.prologGetter).toContain("triple(Base, 'test://value', V), Value is V * 2");
116
+ expect(metadata.properties.computed.prologSetter).toContain("Value is V / 2");
117
+ expect(metadata.properties.computed.prologSetter).toContain("setSingleTarget");
136
118
  });
137
119
 
138
- it("should register relatedModel factory for typed @HasMany", () => {
120
+ it("should handle relation with typed target relation", () => {
139
121
  @Model({ name: "Comment" })
140
122
  class Comment extends Ad4mModel {}
141
-
123
+
142
124
  @Model({ name: "Post" })
143
125
  class Post extends Ad4mModel {
144
- @HasMany(() => Comment, { through: "post://comment" })
145
- comments: Comment[] = [];
126
+ @HasMany({
127
+ through: "post://comment",
128
+ target: () => Comment
129
+ })
130
+ comments: string[] = [];
146
131
  }
147
132
 
148
133
  const metadata = Post.getModelMetadata();
149
-
150
- // relatedModel factory should be registered and return Comment
151
- expect(metadata.relations.comments.relatedModel).toBeDefined();
152
- expect(metadata.relations.comments.relatedModel!()).toBe(Comment);
134
+
135
+ // Assert relation exists with correct predicate
136
+ expect(metadata.relations.comments).toBeDefined();
137
+ expect(metadata.relations.comments.predicate).toBe("post://comment");
153
138
  });
154
139
 
155
- it("should throw error for class without @ModelOptions decorator", () => {
140
+ it("should throw error for class without @Model decorator", () => {
156
141
  class NoDecoratorModel extends Ad4mModel {}
157
142
 
158
143
  // Assert that calling getModelMetadata throws an error
159
- expect(() => NoDecoratorModel.getModelMetadata()).toThrow(
160
- "Model class must be decorated with @Model",
161
- );
144
+ expect(() => NoDecoratorModel.getModelMetadata()).toThrow("Model class must be decorated with @Model");
162
145
  });
163
146
 
164
- it("should handle complex model with mixed property and collection types", () => {
147
+ it("should handle complex model with mixed property and relation types", () => {
165
148
  @Model({ name: "Recipe" })
166
149
  class Recipe extends Ad4mModel {
167
- @Property({
168
- through: "recipe://name",
169
- required: true,
170
- })
150
+ @Property({ through: "recipe://name", resolveLanguage: "literal" })
171
151
  name: string = "";
172
-
173
- @Property({ through: "recipe://description" })
152
+
153
+ @Optional({ through: "recipe://description" })
174
154
  description: string = "";
175
-
176
- @Property({
177
- through: "recipe://rating",
178
- getter: "avg_rating_surreal(Base, Value)",
179
- readOnly: true,
180
- })
155
+
156
+ @ReadOnly({ through: "recipe://rating", prologGetter: "avg_rating(Base, Value)" })
181
157
  rating: number = 0;
182
-
158
+
183
159
  @HasMany({ through: "recipe://ingredient" })
184
160
  ingredients: string[] = [];
185
-
161
+
186
162
  @HasMany({ through: "recipe://step", local: true })
187
163
  steps: string[] = [];
188
164
  }
189
165
 
190
166
  const metadata = Recipe.getModelMetadata();
191
-
167
+
192
168
  // Assert className
193
169
  expect(metadata.className).toBe("Recipe");
194
-
170
+
195
171
  // Assert properties has 3 entries
196
172
  expect(Object.keys(metadata.properties)).toHaveLength(3);
197
173
  expect(metadata.properties.name).toBeDefined();
198
174
  expect(metadata.properties.description).toBeDefined();
199
175
  expect(metadata.properties.rating).toBeDefined();
200
-
201
- // Assert collections has 2 entries
176
+
177
+ // Assert relations has 2 entries
202
178
  expect(Object.keys(metadata.relations)).toHaveLength(2);
203
179
  expect(metadata.relations.ingredients).toBeDefined();
204
180
  expect(metadata.relations.steps).toBeDefined();
205
-
181
+
206
182
  // Verify all metadata fields are correctly extracted
207
183
  expect(metadata.properties.name.predicate).toBe("recipe://name");
208
- expect(metadata.properties.name.resolveLanguage).toBeUndefined(); // "literal" is now the implicit default — no need to store it
209
- expect(metadata.properties.description.predicate).toBe(
210
- "recipe://description",
211
- );
184
+ expect(metadata.properties.name.resolveLanguage).toBe("literal");
185
+ expect(metadata.properties.description.predicate).toBe("recipe://description");
212
186
  expect(metadata.properties.rating.predicate).toBe("recipe://rating");
213
- expect(metadata.properties.rating.getter).toBe(
214
- "avg_rating_surreal(Base, Value)",
215
- );
216
- expect(metadata.relations.ingredients.predicate).toBe(
217
- "recipe://ingredient",
218
- );
187
+ expect(metadata.properties.rating.prologGetter).toBe("avg_rating(Base, Value)");
188
+ expect(metadata.relations.ingredients.predicate).toBe("recipe://ingredient");
219
189
  expect(metadata.relations.steps.predicate).toBe("recipe://step");
220
190
  expect(metadata.relations.steps.local).toBe(true);
221
191
  });
@@ -229,14 +199,15 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
229
199
  properties: {
230
200
  name: { type: "string" },
231
201
  price: { type: "number" },
232
- description: { type: "string" },
202
+ description: { type: "string" }
233
203
  },
234
- required: ["name", "price"],
204
+ required: ["name", "price"]
235
205
  };
236
206
 
237
207
  const ProductClass = Ad4mModel.fromJSONSchema(schema, {
238
208
  name: "Product",
239
209
  namespace: "product://",
210
+ resolveLanguage: "literal"
240
211
  });
241
212
 
242
213
  const metadata = ProductClass.getModelMetadata();
@@ -249,22 +220,20 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
249
220
  expect(metadata.properties.name).toBeDefined();
250
221
  expect(metadata.properties.name.predicate).toBe("product://name");
251
222
  expect(metadata.properties.name.required).toBe(true);
252
- expect(metadata.properties.name.readOnly).toBeFalsy();
253
- expect(metadata.properties.name.resolveLanguage).toBeUndefined(); // implicit literal default
223
+ expect(metadata.properties.name.readOnly).toBe(false);
224
+ expect(metadata.properties.name.resolveLanguage).toBe("literal");
254
225
 
255
226
  expect(metadata.properties.price).toBeDefined();
256
227
  expect(metadata.properties.price.predicate).toBe("product://price");
257
228
  expect(metadata.properties.price.required).toBe(true);
258
- expect(metadata.properties.price.resolveLanguage).toBeUndefined(); // implicit literal default
229
+ expect(metadata.properties.price.resolveLanguage).toBe("literal");
259
230
 
260
231
  expect(metadata.properties.description).toBeDefined();
261
- expect(metadata.properties.description.predicate).toBe(
262
- "product://description",
263
- );
232
+ expect(metadata.properties.description.predicate).toBe("product://description");
264
233
  expect(metadata.properties.description.required).toBe(false);
265
234
  });
266
235
 
267
- it("should extract collections from a model created via fromJSONSchema with arrays", () => {
236
+ it("should extract relations from a model created via fromJSONSchema with arrays", () => {
268
237
  const schema = {
269
238
  title: "Post",
270
239
  type: "object",
@@ -272,19 +241,19 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
272
241
  title: { type: "string" },
273
242
  tags: {
274
243
  type: "array",
275
- items: { type: "string" },
244
+ items: { type: "string" }
276
245
  },
277
246
  comments: {
278
247
  type: "array",
279
- items: { type: "string" },
280
- },
248
+ items: { type: "string" }
249
+ }
281
250
  },
282
- required: ["title"],
251
+ required: ["title"]
283
252
  };
284
253
 
285
254
  const PostClass = Ad4mModel.fromJSONSchema(schema, {
286
255
  name: "Post",
287
- namespace: "post://",
256
+ namespace: "post://"
288
257
  });
289
258
 
290
259
  const metadata = PostClass.getModelMetadata();
@@ -310,7 +279,7 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
310
279
  const schema = {
311
280
  title: "Contact",
312
281
  "x-ad4m": {
313
- namespace: "contact://",
282
+ namespace: "contact://"
314
283
  },
315
284
  type: "object",
316
285
  properties: {
@@ -318,29 +287,31 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
318
287
  type: "string",
319
288
  "x-ad4m": {
320
289
  through: "foaf://name",
321
- },
290
+ resolveLanguage: "literal",
291
+ writable: true
292
+ }
322
293
  },
323
294
  email: {
324
295
  type: "string",
325
296
  "x-ad4m": {
326
297
  through: "foaf://mbox",
327
- local: true,
328
- },
329
- },
298
+ local: true
299
+ }
300
+ }
330
301
  },
331
- required: ["name"],
302
+ required: ["name"]
332
303
  };
333
304
 
334
305
  const ContactClass = Ad4mModel.fromJSONSchema(schema, {
335
- name: "Contact",
306
+ name: "Contact"
336
307
  });
337
308
 
338
309
  const metadata = ContactClass.getModelMetadata();
339
310
 
340
311
  // Verify x-ad4m metadata is respected
341
312
  expect(metadata.properties.name.predicate).toBe("foaf://name");
342
- expect(metadata.properties.name.resolveLanguage).toBeUndefined(); // implicit literal default
343
- expect(metadata.properties.name.readOnly).toBeFalsy();
313
+ expect(metadata.properties.name.resolveLanguage).toBe("literal");
314
+ expect(metadata.properties.name.readOnly).toBe(false);
344
315
  expect(metadata.properties.name.required).toBe(true);
345
316
 
346
317
  expect(metadata.properties.email.predicate).toBe("foaf://mbox");
@@ -353,9 +324,9 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
353
324
  type: "object",
354
325
  properties: {
355
326
  username: { type: "string" },
356
- fullName: { type: "string" },
327
+ fullName: { type: "string" }
357
328
  },
358
- required: ["username"],
329
+ required: ["username"]
359
330
  };
360
331
 
361
332
  const UserClass = Ad4mModel.fromJSONSchema(schema, {
@@ -363,8 +334,8 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
363
334
  namespace: "user://",
364
335
  propertyMapping: {
365
336
  username: "custom://identifier",
366
- fullName: "custom://name",
367
- },
337
+ fullName: "custom://name"
338
+ }
368
339
  });
369
340
 
370
341
  const metadata = UserClass.getModelMetadata();
@@ -384,22 +355,23 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
384
355
  published: { type: "boolean" },
385
356
  authors: {
386
357
  type: "array",
387
- items: { type: "string" },
358
+ items: { type: "string" }
388
359
  },
389
360
  tags: {
390
361
  type: "array",
391
362
  items: { type: "string" },
392
363
  "x-ad4m": {
393
- local: true,
394
- },
395
- },
364
+ local: true
365
+ }
366
+ }
396
367
  },
397
- required: ["title", "published"],
368
+ required: ["title", "published"]
398
369
  };
399
370
 
400
371
  const ArticleClass = Ad4mModel.fromJSONSchema(schema, {
401
372
  name: "Article",
402
373
  namespace: "article://",
374
+ resolveLanguage: "literal"
403
375
  });
404
376
 
405
377
  const metadata = ArticleClass.getModelMetadata();
@@ -411,11 +383,11 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
411
383
  expect(metadata.properties.title).toBeDefined();
412
384
  expect(metadata.properties.title.predicate).toBe("article://title");
413
385
  expect(metadata.properties.title.required).toBe(true);
414
- expect(metadata.properties.title.resolveLanguage).toBeUndefined(); // implicit literal default
386
+ expect(metadata.properties.title.resolveLanguage).toBe("literal");
415
387
 
416
388
  expect(metadata.properties.views).toBeDefined();
417
389
  expect(metadata.properties.views.predicate).toBe("article://views");
418
- expect(metadata.properties.views.resolveLanguage).toBeUndefined(); // implicit literal default
390
+ expect(metadata.properties.views.resolveLanguage).toBe("literal");
419
391
 
420
392
  expect(metadata.properties.published).toBeDefined();
421
393
  expect(metadata.properties.published.predicate).toBe("article://published");
@@ -430,18 +402,16 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
430
402
  expect(metadata.relations.tags.local).toBe(true);
431
403
  });
432
404
 
433
- it("should handle models with only an auto-generated type flag", () => {
434
- const warnSpy = jest.spyOn(console, "warn").mockImplementation(() => {});
435
-
405
+ it("should handle models with no properties (open-world, no auto-flag)", () => {
436
406
  const schema = {
437
407
  title: "EmptyModel",
438
408
  type: "object",
439
- properties: {},
409
+ properties: {}
440
410
  };
441
411
 
442
412
  const EmptyModelClass = Ad4mModel.fromJSONSchema(schema, {
443
413
  name: "EmptyModel",
444
- namespace: "empty://",
414
+ namespace: "empty://"
445
415
  });
446
416
 
447
417
  const metadata = EmptyModelClass.getModelMetadata();
@@ -449,17 +419,14 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
449
419
  // Should have className
450
420
  expect(metadata.className).toBe("EmptyModel");
451
421
 
452
- // Should have the auto-generated __ad4m_type property
453
- expect(metadata.properties.__ad4m_type).toBeDefined();
454
- expect(metadata.properties.__ad4m_type.predicate).toBe("ad4m://type");
455
- expect(metadata.properties.__ad4m_type.initial).toBe("empty://instance");
456
- expect(metadata.properties.__ad4m_type.flag).toBe(true);
422
+ // Should NOT have an auto-generated __ad4m_type property —
423
+ // models with all-optional properties use open-world structural matching.
424
+ expect(metadata.properties.__ad4m_type).toBeUndefined();
457
425
 
458
- // The warning is the expected fallback signal for empty schemas
459
- expect(warnSpy).toHaveBeenCalledWith(
460
- expect.stringContaining("No properties with initial values found"),
461
- );
462
- warnSpy.mockRestore();
426
+ // SHACL shape should still be valid with empty constructor/destructor
427
+ const { shape } = (EmptyModelClass as any).generateSHACL();
428
+ expect(shape.constructor_actions).toEqual([]);
429
+ expect(shape.destructor_actions).toEqual([]);
463
430
  });
464
431
  });
465
432
 
@@ -469,7 +436,20 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
469
436
 
470
437
  // Helper function to normalize whitespace in queries for easier comparison
471
438
  function normalizeQuery(query: string): string {
472
- return query.replace(/\s+/g, " ").trim();
439
+ return query.replace(/\s+/g, ' ').trim();
440
+ }
441
+
442
+ // Test Recipe model — explicit required: true to test required-property query filters
443
+ @Model({ name: "Recipe" })
444
+ class Recipe extends Ad4mModel {
445
+ @Property({ through: "recipe://name", required: true })
446
+ name: string = "";
447
+
448
+ @Property({ through: "recipe://rating", required: true })
449
+ rating: number = 0;
450
+
451
+ @HasMany({ through: "recipe://ingredient" })
452
+ ingredients: string[] = [];
473
453
  }
474
454
 
475
455
  it("should generate basic query with no filters", async () => {
@@ -478,63 +458,43 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
478
458
  expect(query).toContain("id AS source");
479
459
  expect(query).toContain("uri AS source_uri");
480
460
  expect(query).toContain("FROM node");
481
- expect(query).toContain(
482
- "(SELECT predicate, out.uri AS target, author, timestamp FROM link WHERE in = $parent.id ORDER BY timestamp ASC) AS links",
483
- );
461
+ expect(query).toContain("->link AS links");
484
462
  expect(query).toContain("WHERE");
485
463
  // Should have graph traversal filters for required properties
486
464
  expect(query).toContain("count(->link[WHERE");
487
465
  });
488
466
 
489
467
  it("should generate query with simple property filter", async () => {
490
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
491
- where: { name: "Pasta" },
492
- });
493
-
468
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: "Pasta" } });
469
+
494
470
  // Should have graph traversal filters for required properties and user filter
495
- expect(query).toContain(
496
- "count(->link[WHERE predicate = 'recipe://name']) > 0",
497
- );
498
- expect(query).toContain(
499
- "count(->link[WHERE predicate = 'recipe://rating']) > 0",
500
- );
501
- expect(query).toContain(
502
- "count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0",
503
- );
471
+ expect(query).toContain("count(->link[WHERE predicate = 'recipe://name']) > 0");
472
+ expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating']) > 0");
473
+ expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
504
474
  });
505
475
 
506
476
  it("should generate query with multiple property filters", async () => {
507
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
508
- where: { name: "Pasta", rating: 5 },
509
- });
510
-
477
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: "Pasta", rating: 5 } });
478
+
511
479
  expect(query).toContain("WHERE");
512
- expect(query).toContain(
513
- "count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0",
514
- );
515
- expect(query).toContain(
516
- "count(->link[WHERE predicate = 'recipe://rating' AND fn::parse_literal(out.uri) = 5]) > 0",
517
- );
480
+ expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
481
+ expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating' AND fn::parse_literal(out.uri) = 5]) > 0");
518
482
  expect(query).toContain("AND");
519
483
  });
520
484
 
521
485
  it("should handle gt operator (filtered in JavaScript, not SQL)", async () => {
522
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
523
- where: { rating: { gt: 4 } },
524
- });
486
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { gt: 4 } } });
525
487
 
526
488
  // Comparison operators for regular properties are now filtered in JavaScript post-query
527
489
  // The SQL just filters on the predicate existing
528
490
  expect(query).toContain("FROM node");
529
-
491
+
530
492
  // Should NOT contain comparison operators in SQL for regular properties
531
493
  expect(query).not.toContain("target > 4");
532
494
  });
533
495
 
534
496
  it("should handle lt operator (filtered in JavaScript, not SQL)", async () => {
535
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
536
- where: { rating: { lt: 3 } },
537
- });
497
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { lt: 3 } } });
538
498
 
539
499
  // Comparison operators are filtered in JavaScript post-query
540
500
  expect(query).toContain("FROM node");
@@ -542,9 +502,7 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
542
502
  });
543
503
 
544
504
  it("should handle gte and lte operators (filtered in JavaScript, not SQL)", async () => {
545
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
546
- where: { rating: { gte: 3, lte: 5 } },
547
- });
505
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { gte: 3, lte: 5 } } });
548
506
 
549
507
  // Comparison operators are filtered in JavaScript post-query
550
508
  expect(query).toContain("FROM node");
@@ -553,31 +511,21 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
553
511
  });
554
512
 
555
513
  it("should handle not operator with single value", async () => {
556
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
557
- where: { name: { not: "Salad" } },
558
- });
514
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { not: "Salad" } } });
559
515
 
560
516
  // Not operator uses graph traversal with count = 0
561
- expect(query).toContain(
562
- "count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Salad']) = 0",
563
- );
517
+ expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Salad']) = 0");
564
518
  });
565
519
 
566
520
  it("should handle not operator with array (NOT IN)", async () => {
567
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
568
- where: { name: { not: ["Salad", "Soup"] } },
569
- });
521
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { not: ["Salad", "Soup"] } } });
570
522
 
571
523
  // Not operator with array uses graph traversal with count = 0
572
- expect(query).toContain(
573
- "count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) IN ['Salad', 'Soup']]) = 0",
574
- );
524
+ expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) IN ['Salad', 'Soup']]) = 0");
575
525
  });
576
526
 
577
527
  it("should handle between operator (filtered in JavaScript, not SQL)", async () => {
578
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
579
- where: { rating: { between: [3, 5] } },
580
- });
528
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { between: [3, 5] } } });
581
529
 
582
530
  // Between operator for regular properties is now filtered in JavaScript post-query
583
531
  expect(query).toContain("FROM node");
@@ -586,9 +534,7 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
586
534
  });
587
535
 
588
536
  it("should handle contains operator on string property (filtered in JavaScript, not SQL)", async () => {
589
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
590
- where: { name: { contains: "Past" } },
591
- });
537
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { contains: "Past" } } });
592
538
 
593
539
  // Contains operator for regular properties is now filtered in JavaScript post-query
594
540
  expect(query).toContain("FROM node");
@@ -596,34 +542,47 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
596
542
  });
597
543
 
598
544
  it("should handle contains operator on regular property with substring (filtered in JavaScript, not SQL)", async () => {
599
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
600
- where: { name: { contains: "Salad" } },
601
- });
545
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { contains: "Salad" } } });
602
546
 
603
547
  // Contains operator is filtered in JavaScript post-query
604
548
  expect(query).toContain("FROM node");
605
549
  expect(query).not.toContain("target CONTAINS 'Salad'");
606
550
  });
607
551
 
552
+ it.skip("should handle contains operator on special field (author)", async () => {
553
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { author: { contains: "alice" } } });
554
+
555
+ expect(query).toContain("WHERE author CONTAINS 'alice'");
556
+ // Should not use a subquery pattern
557
+ expect(query).not.toContain("SELECT source FROM node");
558
+ });
559
+
560
+ it.skip("should handle contains operator on special field (id)", async () => {
561
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { contains: "test" } } });
562
+
563
+ expect(query).toContain("WHERE source CONTAINS 'test'");
564
+ });
565
+
608
566
  it("should handle array values (IN clause)", async () => {
609
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
610
- where: { name: ["Pasta", "Pizza"] },
611
- });
567
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: ["Pasta", "Pizza"] } });
568
+
569
+ expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) IN ['Pasta', 'Pizza']]) > 0");
570
+ });
612
571
 
613
- expect(query).toContain(
614
- "count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) IN ['Pasta', 'Pizza']]) > 0",
615
- );
572
+ it.skip("should handle special fields (author, timestamp) without subqueries", async () => {
573
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { author: "did:key:alice" } });
574
+
575
+ expect(query).toContain("WHERE author = 'did:key:alice'");
576
+ // Ensure it's NOT using a subquery pattern for author in WHERE clause
577
+ expect(normalizeQuery(query)).not.toMatch(/WHERE.*source IN.*SELECT source FROM node.*author/);
616
578
  });
617
579
 
618
580
  it("should not generate ORDER BY clause in SQL (handled in JavaScript)", async () => {
619
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
620
- order: { timestamp: "DESC" },
621
- });
581
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { order: { timestamp: "DESC" } });
622
582
 
623
583
  // ORDER BY is now handled in JavaScript post-query
624
- // Note: the links correlated subquery uses ORDER BY timestamp ASC internally for link ordering
625
584
  expect(query).toContain("FROM node");
626
- expect(query).not.toContain("ORDER BY timestamp DESC");
585
+ expect(query).not.toContain("ORDER BY");
627
586
  });
628
587
 
629
588
  it("should not generate LIMIT clause in SQL (handled in JavaScript)", async () => {
@@ -635,9 +594,7 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
635
594
  });
636
595
 
637
596
  it("should not generate START clause in SQL (handled in JavaScript)", async () => {
638
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
639
- offset: 20,
640
- });
597
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { offset: 20 });
641
598
 
642
599
  // START/offset is now handled in JavaScript post-query
643
600
  expect(query).toContain("FROM node");
@@ -649,38 +606,32 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
649
606
  where: { name: "Pasta", rating: { gt: 4 } },
650
607
  order: { timestamp: "DESC" },
651
608
  limit: 10,
652
- offset: 20,
609
+ offset: 20
653
610
  });
654
611
 
655
612
  // WHERE clause uses graph traversal filters
656
613
  expect(query).toContain("WHERE");
657
- expect(query).toContain(
658
- "count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0",
659
- );
614
+ expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
660
615
  // Comparison operators (gt) are filtered in JavaScript, not SQL
661
616
  expect(query).not.toContain("out.uri > 4");
662
617
  expect(query).not.toContain("target > 4");
663
618
  // ORDER BY, LIMIT, START are now handled in JavaScript post-query
664
- // Note: the links subquery uses ORDER BY timestamp ASC internally
665
- expect(query).not.toContain("ORDER BY timestamp DESC");
619
+ expect(query).not.toContain("ORDER BY");
666
620
  expect(query).not.toContain("LIMIT");
667
621
  expect(query).not.toContain("START");
668
622
  });
669
623
 
670
- it("should only select requested fields", async () => {
671
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
672
- properties: ["name"],
673
- });
624
+ it("should only select requested properties", async () => {
625
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name"] });
674
626
 
675
627
  // With array::group(), all link data is selected, filtering happens in instancesFromSurrealResult
676
- expect(query).toContain(
677
- "(SELECT predicate, out.uri AS target, author, timestamp FROM link WHERE in = $parent.id ORDER BY timestamp ASC) AS links",
678
- );
628
+ expect(query).toContain("->link AS links");
629
+
679
630
  });
680
631
 
681
- it("should only select requested relations", async () => {
682
- @Model({ name: "MultiCollectionModel" })
683
- class MultiCollectionModel extends Ad4mModel {
632
+ it("should select all link data for relations", async () => {
633
+ @Model({ name: "MultiRelationModel" })
634
+ class MultiRelationModel extends Ad4mModel {
684
635
  @HasMany({ through: "test://coll1" })
685
636
  coll1: string[] = [];
686
637
 
@@ -688,34 +639,26 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
688
639
  coll2: string[] = [];
689
640
  }
690
641
 
691
- const query = await MultiCollectionModel.queryToSurrealQL(
692
- mockPerspective,
693
- {},
694
- );
642
+ const query = await MultiRelationModel.queryToSurrealQL(mockPerspective, {});
695
643
 
696
- // With array::group(), all link data is selected, filtering happens in instancesFromSurrealResult
697
- expect(query).toContain(
698
- "(SELECT predicate, out.uri AS target, author, timestamp FROM link WHERE in = $parent.id ORDER BY timestamp ASC) AS links",
699
- );
644
+ // With array::group(), all link data is selected
645
+ expect(query).toContain("->link AS links");
646
+
700
647
  });
701
648
 
702
649
  it("should escape single quotes in string values", async () => {
703
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
704
- where: { name: "O'Brien's Recipe" },
705
- });
650
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: "O'Brien's Recipe" } });
706
651
 
707
652
  // Single quotes are escaped with backslash in SurrealDB
708
653
  expect(query).toContain("O\\'Brien\\'s Recipe");
709
654
  });
710
655
 
711
656
  it("should handle numeric values without quotes", async () => {
712
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
713
- where: { rating: 5 },
714
- });
715
-
657
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: 5 } });
658
+
716
659
  // Numeric values should not have quotes around them
717
660
  expect(query).toContain("fn::parse_literal(out.uri) = 5");
718
- expect(query).not.toContain("out.uri = '5'");
661
+ expect(query).not.toContain("fn::parse_literal(out.uri) = '5'");
719
662
  });
720
663
 
721
664
  it("should handle complex nested query (comparisons, ORDER BY, LIMIT handled in JS)", async () => {
@@ -723,18 +666,16 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
723
666
  where: {
724
667
  name: "Pasta",
725
668
  rating: { gte: 4, lte: 5 },
726
- author: "did:key:alice",
669
+ author: "did:key:alice"
727
670
  },
728
671
  order: { rating: "DESC" },
729
- limit: 5,
672
+ limit: 5
730
673
  });
731
674
 
732
675
  const normalized = normalizeQuery(query);
733
676
 
734
677
  // Verify graph traversal filters are present
735
- expect(normalized).toContain(
736
- "count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0",
737
- );
678
+ expect(normalized).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
738
679
  // Comparison operators (gte, lte) are filtered in JavaScript, not SQL
739
680
  expect(normalized).not.toContain("out.uri >= 4");
740
681
  expect(normalized).not.toContain("target >= 4");
@@ -744,8 +685,7 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
744
685
  expect(normalized).not.toContain("author = 'did:key:alice'");
745
686
 
746
687
  // ORDER BY and LIMIT are handled in JavaScript post-query
747
- // Note: the links correlated subquery uses ORDER BY timestamp ASC internally
748
- expect(normalized).not.toContain("ORDER BY rating");
688
+ expect(normalized).not.toContain("ORDER BY");
749
689
  expect(normalized).not.toContain("LIMIT");
750
690
 
751
691
  // Verify query structure (FROM node, no GROUP BY)
@@ -754,91 +694,67 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
754
694
 
755
695
  it("should handle empty query object", async () => {
756
696
  const query = await Recipe.queryToSurrealQL(mockPerspective, {});
757
-
697
+
758
698
  // Should generate valid query with WHERE clause for required properties (name and rating)
759
699
  expect(query).toContain("id AS source");
760
700
  expect(query).toContain("uri AS source_uri");
761
701
  expect(query).toContain("FROM node");
762
-
702
+
763
703
  // Should have WHERE clause filtering for required properties using graph traversal
764
704
  expect(query).toContain("WHERE");
765
- expect(query).toContain(
766
- "count(->link[WHERE predicate = 'recipe://name']) > 0",
767
- );
768
- expect(query).toContain(
769
- "count(->link[WHERE predicate = 'recipe://rating']) > 0",
770
- );
771
- // No user-requested ORDER BY or START should appear at the top level
705
+ expect(query).toContain("count(->link[WHERE predicate = 'recipe://name']) > 0");
706
+ expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating']) > 0");
707
+ expect(query).not.toContain("ORDER BY");
772
708
  expect(query).not.toContain("START");
773
709
  });
774
710
 
775
- it("should handle base special field", async () => {
776
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
777
- where: { base: "literal://test" },
778
- });
779
-
711
+ it("should handle id special field", async () => {
712
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: "literal://test" } });
713
+
780
714
  expect(query).toContain("uri = 'literal://test'");
781
715
  });
782
716
 
783
- it("should handle base special field with array (IN clause)", async () => {
784
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
785
- where: { base: ["literal://test1", "literal://test2"] },
786
- });
787
-
717
+ it("should handle id special field with array (IN clause)", async () => {
718
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: ["literal://test1", "literal://test2"] } });
719
+
788
720
  expect(query).toContain("uri IN ['literal://test1', 'literal://test2']");
789
721
  });
790
722
 
791
- it("should handle base special field with not operator", async () => {
792
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
793
- where: { base: { not: "literal://test" } },
794
- });
795
-
723
+ it("should handle id special field with not operator", async () => {
724
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { not: "literal://test" } } });
725
+
796
726
  expect(query).toContain("uri != 'literal://test'");
797
727
  });
798
728
 
799
- it("should handle base special field with not operator and array (NOT IN)", async () => {
800
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
801
- where: { base: { not: ["literal://test1", "literal://test2"] } },
802
- });
803
-
804
- expect(query).toContain(
805
- "uri NOT IN ['literal://test1', 'literal://test2']",
806
- );
729
+ it("should handle id special field with not operator and array (NOT IN)", async () => {
730
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { not: ["literal://test1", "literal://test2"] } } });
731
+
732
+ expect(query).toContain("uri NOT IN ['literal://test1', 'literal://test2']");
807
733
  });
808
734
 
809
- it("should handle base special field with between operator", async () => {
810
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
811
- where: { base: { between: ["literal://a", "literal://z"] } },
812
- } as any);
813
-
735
+ it("should handle id special field with between operator", async () => {
736
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { between: ["literal://a", "literal://z"] } } } as any);
737
+
814
738
  const normalized = normalizeQuery(query);
815
- expect(normalized).toContain(
816
- "uri >= 'literal://a' AND uri <= 'literal://z'",
817
- );
739
+ expect(normalized).toContain("uri >= 'literal://a' AND uri <= 'literal://z'");
818
740
  });
819
741
 
820
- it("should handle base special field with gt operator", async () => {
821
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
822
- where: { base: { gt: "literal://m" } },
823
- } as any);
824
-
742
+ it("should handle id special field with gt operator", async () => {
743
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { gt: "literal://m" } } } as any);
744
+
825
745
  expect(query).toContain("uri > 'literal://m'");
826
746
  });
827
747
 
828
- it("should handle base special field with gte and lte operators", async () => {
829
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
830
- where: { base: { gte: "literal://a", lte: "literal://z" } },
831
- } as any);
832
-
748
+ it("should handle id special field with gte and lte operators", async () => {
749
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { gte: "literal://a", lte: "literal://z" } } } as any);
750
+
833
751
  const normalized = normalizeQuery(query);
834
752
  expect(normalized).toContain("uri >= 'literal://a'");
835
753
  expect(normalized).toContain("uri <= 'literal://z'");
836
754
  });
837
755
 
838
756
  it("should handle timestamp special field with gt operator (filtered in JavaScript)", async () => {
839
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
840
- where: { timestamp: { gt: 1234567890 } },
841
- });
757
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { timestamp: { gt: 1234567890 } } });
842
758
 
843
759
  // timestamp filtering is done in JavaScript post-query
844
760
  expect(query).toContain("FROM node");
@@ -849,8 +765,8 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
849
765
  const query = await Recipe.queryToSurrealQL(mockPerspective, {
850
766
  where: {
851
767
  author: "did:key:alice",
852
- timestamp: { gt: 1000 },
853
- },
768
+ timestamp: { gt: 1000 }
769
+ }
854
770
  });
855
771
 
856
772
  // author and timestamp filtering is done in JavaScript post-query
@@ -864,15 +780,13 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
864
780
  where: {
865
781
  name: "Pasta",
866
782
  author: "did:key:alice",
867
- rating: { gt: 4 },
868
- },
783
+ rating: { gt: 4 }
784
+ }
869
785
  });
870
786
 
871
787
  const normalized = normalizeQuery(query);
872
788
  // Regular properties use graph traversal filters
873
- expect(normalized).toContain(
874
- "count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0",
875
- );
789
+ expect(normalized).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
876
790
  // Comparison operators (gt) are filtered in JavaScript, not SQL
877
791
  expect(normalized).not.toContain("out.uri > 4");
878
792
  expect(normalized).not.toContain("target > 4");
@@ -883,114 +797,77 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
883
797
  it("should handle boolean values", async () => {
884
798
  @Model({ name: "Task" })
885
799
  class Task extends Ad4mModel {
886
- @Property({
887
- through: "task://completed",
888
- required: true,
889
- })
800
+ @Property({ through: "task://completed" })
890
801
  completed: boolean = false;
891
802
  }
892
- const query = await Task.queryToSurrealQL(mockPerspective, {
893
- where: { completed: true },
894
- });
895
803
 
804
+ const query = await Task.queryToSurrealQL(mockPerspective, { where: { completed: true } });
805
+
896
806
  expect(query).toContain("fn::parse_literal(out.uri) = true");
897
807
  });
898
808
 
899
809
  it("should handle array of numbers", async () => {
900
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
901
- where: { rating: [4, 5] },
902
- });
903
-
904
- expect(query).toContain(
905
- "count(->link[WHERE predicate = 'recipe://rating' AND fn::parse_literal(out.uri) IN [4, 5]]) > 0",
906
- );
810
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: [4, 5] } });
811
+
812
+ expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating' AND fn::parse_literal(out.uri) IN [4, 5]]) > 0");
907
813
  });
908
814
 
909
815
  it("should skip unknown properties in where clause", async () => {
910
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
911
- where: { unknownProp: "value" } as any,
912
- });
913
-
816
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { unknownProp: "value" } as any });
817
+
914
818
  // Should not throw error, just skip the unknown property
915
819
  expect(query).toContain("source");
916
-
820
+
917
821
  // Should not contain any condition for unknownProp
918
822
  expect(query).not.toContain("unknownProp");
919
823
  });
920
824
 
825
+ it.skip("should skip unknown properties in select clause", async () => {
826
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name", "unknownProp"] as any });
827
+
828
+ // Should include name using aggregation
829
+ expect(query).toContain("array::first(target[WHERE predicate = 'recipe://name']) AS name");
830
+ // Should not error on unknownProp, just skip it
831
+ expect(query).not.toContain("unknownProp");
832
+ });
833
+
921
834
  it("should handle order by regular property (handled in JavaScript)", async () => {
922
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
923
- order: { name: "ASC" },
924
- });
835
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { order: { name: "ASC" } });
925
836
 
926
837
  // ORDER BY is now handled in JavaScript post-query
927
- // Note: the links correlated subquery uses ORDER BY timestamp ASC internally
928
838
  expect(query).toContain("FROM node");
929
- expect(query).not.toContain("ORDER BY name");
839
+ expect(query).not.toContain("ORDER BY");
930
840
  });
931
841
 
932
- it("should generate query with only fields, no relations", async () => {
933
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
934
- properties: ["name", "rating"],
935
- });
842
+ it("should generate query with only properties specified", async () => {
843
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name", "rating"] });
936
844
 
937
845
  // With array::group(), all link data is selected, filtering happens in instancesFromSurrealResult
938
- expect(query).toContain(
939
- "(SELECT predicate, out.uri AS target, author, timestamp FROM link WHERE in = $parent.id ORDER BY timestamp ASC) AS links",
940
- );
941
- });
942
-
943
- it("should generate query with only relations, no fields", async () => {
944
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
945
- properties: [],
946
- });
947
-
948
- // With array::group(), all link data is selected, filtering happens in instancesFromSurrealResult
949
- expect(query).toContain(
950
- "(SELECT predicate, out.uri AS target, author, timestamp FROM link WHERE in = $parent.id ORDER BY timestamp ASC) AS links",
951
- );
952
- });
953
-
954
- it("should include backward link filter when parent is given as raw predicate form", async () => {
955
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
956
- parent: { id: "some://parent-uri", predicate: "custom://has_recipe" },
957
- });
958
-
959
- expect(query).toContain(
960
- "count(<-link[WHERE predicate = 'custom://has_recipe' AND in.uri = 'some://parent-uri']) > 0",
961
- );
962
- });
963
-
964
- it("should resolve model-backed parent form and include correct backward link filter", async () => {
965
- @Model({ name: "MenuForQueryTest" })
966
- class MenuForQueryTest extends Ad4mModel {
967
- @HasMany(() => Recipe, { through: "menu://has_recipe" })
968
- recipes: Recipe[] = [];
969
- }
970
-
971
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
972
- parent: {
973
- id: "some://menu-uri",
974
- model: MenuForQueryTest,
975
- field: "recipes",
976
- },
977
- });
978
-
979
- expect(query).toContain(
980
- "count(<-link[WHERE predicate = 'menu://has_recipe' AND in.uri = 'some://menu-uri']) > 0",
981
- );
846
+ expect(query).toContain("->link AS links");
847
+
982
848
  });
983
849
  });
984
850
 
985
- describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatch", () => {
851
+ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", () => {
852
+ // Test Recipe model
853
+ @Model({ name: "Recipe" })
854
+ class Recipe extends Ad4mModel {
855
+ @Property({ through: "recipe://name" })
856
+ name: string = "";
857
+
858
+ @Property({ through: "recipe://rating" })
859
+ rating: number = 0;
860
+
861
+ @HasMany({ through: "recipe://ingredient" })
862
+ ingredients: string[] = [];
863
+ }
864
+
986
865
  // Mock perspective with both querySurrealDB and infer methods
987
866
  const mockPerspective = {
988
867
  querySurrealDB: jest.fn(),
989
868
  infer: jest.fn(),
990
- uuid: "test-perspective-uuid",
991
- stringOrTemplateObjectToSubjectClassName: jest
992
- .fn()
993
- .mockResolvedValue("Recipe"),
869
+ uuid: 'test-perspective-uuid',
870
+ stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
994
871
  } as any;
995
872
 
996
873
  beforeEach(() => {
@@ -998,12 +875,8 @@ describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatc
998
875
  });
999
876
 
1000
877
  it("should convert empty SurrealDB results correctly", async () => {
1001
- const result = await Recipe.instancesFromSurrealResult(
1002
- mockPerspective,
1003
- {},
1004
- [],
1005
- );
1006
-
878
+ const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, []);
879
+
1007
880
  expect(result.results).toEqual([]);
1008
881
  expect(result.totalCount).toBe(0);
1009
882
  });
@@ -1014,81 +887,27 @@ describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatc
1014
887
  source: "node:abc123",
1015
888
  source_uri: "literal://recipe1",
1016
889
  links: [
1017
- {
1018
- predicate: "recipe://name",
1019
- target: Literal.from("Pasta").toUrl(),
1020
- author: "did:key:alice",
1021
- timestamp: "2023-01-01T00:00:00Z",
1022
- },
1023
- {
1024
- predicate: "recipe://rating",
1025
- target: Literal.from(5).toUrl(),
1026
- author: "did:key:alice",
1027
- timestamp: "2023-01-01T00:00:00Z",
1028
- },
1029
- {
1030
- predicate: "recipe://ingredient",
1031
- target: "pasta",
1032
- author: "did:key:alice",
1033
- timestamp: "2023-01-01T00:00:00Z",
1034
- },
1035
- {
1036
- predicate: "recipe://ingredient",
1037
- target: "tomato",
1038
- author: "did:key:alice",
1039
- timestamp: "2023-01-01T00:00:00Z",
1040
- },
1041
- {
1042
- predicate: "recipe://ingredient",
1043
- target: "cheese",
1044
- author: "did:key:alice",
1045
- timestamp: "2023-01-01T00:00:00Z",
1046
- },
1047
- ],
890
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
891
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
892
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
893
+ { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
894
+ { predicate: "recipe://ingredient", target: "cheese", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
895
+ ]
1048
896
  },
1049
897
  {
1050
898
  source: "node:def456",
1051
899
  source_uri: "literal://recipe2",
1052
900
  links: [
1053
- {
1054
- predicate: "recipe://name",
1055
- target: Literal.from("Pizza").toUrl(),
1056
- author: "did:key:bob",
1057
- timestamp: "2023-01-02T00:00:00Z",
1058
- },
1059
- {
1060
- predicate: "recipe://rating",
1061
- target: Literal.from(4).toUrl(),
1062
- author: "did:key:bob",
1063
- timestamp: "2023-01-02T00:00:00Z",
1064
- },
1065
- {
1066
- predicate: "recipe://ingredient",
1067
- target: "dough",
1068
- author: "did:key:bob",
1069
- timestamp: "2023-01-02T00:00:00Z",
1070
- },
1071
- {
1072
- predicate: "recipe://ingredient",
1073
- target: "cheese",
1074
- author: "did:key:bob",
1075
- timestamp: "2023-01-02T00:00:00Z",
1076
- },
1077
- {
1078
- predicate: "recipe://ingredient",
1079
- target: "tomato",
1080
- author: "did:key:bob",
1081
- timestamp: "2023-01-02T00:00:00Z",
1082
- },
1083
- ],
1084
- },
901
+ { predicate: "recipe://name", target: "Pizza", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
902
+ { predicate: "recipe://rating", target: "4", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
903
+ { predicate: "recipe://ingredient", target: "dough", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
904
+ { predicate: "recipe://ingredient", target: "cheese", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
905
+ { predicate: "recipe://ingredient", target: "tomato", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" }
906
+ ]
907
+ }
1085
908
  ];
1086
909
 
1087
- const result = await Recipe.instancesFromSurrealResult(
1088
- mockPerspective,
1089
- {},
1090
- surrealResults,
1091
- );
910
+ const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, surrealResults);
1092
911
 
1093
912
  expect(result.results).toHaveLength(2);
1094
913
  expect(result.totalCount).toBe(2);
@@ -1105,180 +924,55 @@ describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatc
1105
924
  expect(recipe2.rating).toBe(4);
1106
925
  });
1107
926
 
1108
- it("should set instance id from source_uri", async () => {
1109
- const result = await Recipe.instancesFromSurrealResult(
1110
- mockPerspective,
1111
- {},
1112
- [
1113
- {
1114
- source: "node:abc123",
1115
- source_uri: "literal://recipe1",
1116
- links: [
1117
- {
1118
- predicate: "recipe://name",
1119
- target: Literal.from("Pasta").toUrl(),
1120
- author: "did:key:alice",
1121
- timestamp: "2023-01-01T00:00:00Z",
1122
- },
1123
- {
1124
- predicate: "recipe://rating",
1125
- target: Literal.from(5).toUrl(),
1126
- author: "did:key:alice",
1127
- timestamp: "2023-01-01T00:00:00Z",
1128
- },
1129
- ],
1130
- },
1131
- ],
1132
- );
1133
-
1134
- expect(result.results).toHaveLength(1);
1135
- // id is derived from source_uri (the node's URI in the graph)
1136
- expect(result.results[0].id).toBe("literal://recipe1");
1137
- });
927
+ it("should filter properties when query specifies properties", async () => {
928
+ const surrealResults = [
929
+ {
930
+ source: "node:abc123",
931
+ source_uri: "literal://recipe1",
932
+ links: [
933
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
934
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
935
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
936
+ { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
937
+ ]
938
+ }
939
+ ];
1138
940
 
1139
- it("should use latest-wins semantics when multiple links share a predicate", async () => {
1140
941
  const result = await Recipe.instancesFromSurrealResult(
1141
942
  mockPerspective,
1142
- {},
1143
- [
1144
- {
1145
- source: "node:abc123",
1146
- source_uri: "literal://recipe1",
1147
- links: [
1148
- {
1149
- predicate: "recipe://name",
1150
- target: Literal.from("Old Name").toUrl(),
1151
- author: "did:key:alice",
1152
- timestamp: "2023-01-01T00:00:00Z",
1153
- },
1154
- {
1155
- // later timestamp — this value should win
1156
- predicate: "recipe://name",
1157
- target: Literal.from("New Name").toUrl(),
1158
- author: "did:key:alice",
1159
- timestamp: "2023-01-02T00:00:00Z",
1160
- },
1161
- {
1162
- predicate: "recipe://rating",
1163
- target: Literal.from(5).toUrl(),
1164
- author: "did:key:alice",
1165
- timestamp: "2023-01-01T00:00:00Z",
1166
- },
1167
- ],
1168
- },
1169
- ],
1170
- );
1171
-
1172
- expect(result.results).toHaveLength(1);
1173
- expect(result.results[0].name).toBe("New Name");
1174
- });
1175
-
1176
- it("should apply transform function during hydration", async () => {
1177
- @Model({ name: "TransformRecipe" })
1178
- class TransformRecipe extends Ad4mModel {
1179
- @Property({
1180
- through: "recipe://name",
1181
- transform: (v: string) => v.toUpperCase(),
1182
- })
1183
- name: string = "";
1184
- }
1185
-
1186
- const result = await TransformRecipe.instancesFromSurrealResult(
1187
- mockPerspective,
1188
- {},
1189
- [
1190
- {
1191
- source: "node:abc123",
1192
- source_uri: "literal://tr1",
1193
- links: [
1194
- {
1195
- predicate: "recipe://name",
1196
- target: Literal.from("pasta").toUrl(),
1197
- author: "did:key:alice",
1198
- timestamp: "2023-01-01T00:00:00Z",
1199
- },
1200
- ],
1201
- },
1202
- ],
943
+ { properties: ["name"] },
944
+ surrealResults
1203
945
  );
1204
946
 
1205
947
  expect(result.results).toHaveLength(1);
1206
- expect(result.results[0].name).toBe("PASTA");
1207
- });
1208
-
1209
- it("should apply JS-level operator filters — smoke test", async () => {
1210
- // Ratings 1–5 encoded as Literals so the JS filter receives actual numbers
1211
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1212
- source: `node:abc${i + 1}`,
1213
- source_uri: `literal://recipe${i + 1}`,
1214
- links: [
1215
- {
1216
- predicate: "recipe://name",
1217
- target: Literal.from(`Recipe ${i + 1}`).toUrl(),
1218
- author: "did:key:alice",
1219
- timestamp: "2023-01-01T00:00:00Z",
1220
- },
1221
- {
1222
- predicate: "recipe://rating",
1223
- target: Literal.from(i + 1).toUrl(),
1224
- author: "did:key:alice",
1225
- timestamp: "2023-01-01T00:00:00Z",
1226
- },
1227
- ],
1228
- }));
1229
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1230
-
1231
- // Only ratings 4 and 5 pass the JS-level gt filter
1232
- const results = await Recipe.findAll(mockPerspective, {
1233
- where: { rating: { gt: 3 } },
1234
- });
1235
- expect(results).toHaveLength(2);
1236
-
1237
- // count() must be consistent with findAll()
1238
- const count = await Recipe.count(mockPerspective, {
1239
- where: { rating: { gt: 3 } },
1240
- });
1241
- expect(count).toBe(2);
948
+ const recipe = result.results[0];
949
+ expect(recipe.name).toBe("Pasta");
950
+ // rating and ingredients should be removed since only "name" was requested
951
+ expect(recipe.rating).toBeUndefined();
952
+ expect(recipe.ingredients).toBeUndefined();
953
+ // author, createdAt, updatedAt are also stripped unless explicitly requested
954
+ expect(recipe.author).toBeUndefined();
955
+ expect(recipe.timestamp).toBeUndefined();
1242
956
  });
1243
957
 
1244
- it("should filter fields when query specifies fields", async () => {
958
+ it("should filter properties when query specifies properties", async () => {
1245
959
  const surrealResults = [
1246
960
  {
1247
961
  source: "node:abc123",
1248
962
  source_uri: "literal://recipe1",
1249
963
  links: [
1250
- {
1251
- predicate: "recipe://name",
1252
- target: "Pasta",
1253
- author: "did:key:alice",
1254
- timestamp: "2023-01-01T00:00:00Z",
1255
- },
1256
- {
1257
- predicate: "recipe://rating",
1258
- target: "5",
1259
- author: "did:key:alice",
1260
- timestamp: "2023-01-01T00:00:00Z",
1261
- },
1262
- {
1263
- predicate: "recipe://ingredient",
1264
- target: "pasta",
1265
- author: "did:key:alice",
1266
- timestamp: "2023-01-01T00:00:00Z",
1267
- },
1268
- {
1269
- predicate: "recipe://ingredient",
1270
- target: "tomato",
1271
- author: "did:key:alice",
1272
- timestamp: "2023-01-01T00:00:00Z",
1273
- },
1274
- ],
1275
- },
964
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
965
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
966
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
967
+ { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
968
+ ]
969
+ }
1276
970
  ];
1277
971
 
1278
972
  const result = await Recipe.instancesFromSurrealResult(
1279
973
  mockPerspective,
1280
974
  { properties: ["name"] },
1281
- surrealResults,
975
+ surrealResults
1282
976
  );
1283
977
 
1284
978
  expect(result.results).toHaveLength(1);
@@ -1286,40 +980,20 @@ describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatc
1286
980
  expect(recipe.name).toBe("Pasta");
1287
981
  // rating and ingredients should be removed since only "name" was requested
1288
982
  expect(recipe.rating).toBeUndefined();
1289
- expect(recipe.ingredients).toBeUndefined();
1290
- // author and timestamp are metadata fields — they are also stripped unless
1291
- // explicitly listed in `properties`. Integration tests cover the
1292
- // `properties: ["author", "createdAt"]` case.
1293
- expect(recipe.author).toBeUndefined();
1294
- expect(recipe.createdAt).toBeUndefined();
1295
983
  });
1296
984
 
1297
985
  it("should handle results missing base field", async () => {
1298
986
  const surrealResults = [
1299
987
  {
1300
988
  links: [
1301
- {
1302
- predicate: "recipe://name",
1303
- target: "Pasta",
1304
- author: "did:key:alice",
1305
- timestamp: "2023-01-01T00:00:00Z",
1306
- },
1307
- {
1308
- predicate: "recipe://rating",
1309
- target: "5",
1310
- author: "did:key:alice",
1311
- timestamp: "2023-01-01T00:00:00Z",
1312
- },
1313
- ],
989
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
990
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
991
+ ]
1314
992
  // Missing source field
1315
- } as any,
993
+ } as any
1316
994
  ];
1317
995
 
1318
- const result = await Recipe.instancesFromSurrealResult(
1319
- mockPerspective,
1320
- {},
1321
- surrealResults,
1322
- );
996
+ const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, surrealResults);
1323
997
 
1324
998
  // Should filter out the invalid result (or handle gracefully)
1325
999
  expect(result.results).toHaveLength(0);
@@ -1332,26 +1006,11 @@ describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatc
1332
1006
  source: "node:abc123",
1333
1007
  source_uri: "literal://recipe1",
1334
1008
  links: [
1335
- {
1336
- predicate: "recipe://name",
1337
- target: "Pasta",
1338
- author: "did:key:alice",
1339
- timestamp: "2023-01-01T00:00:00Z",
1340
- },
1341
- {
1342
- predicate: "recipe://rating",
1343
- target: "5",
1344
- author: "did:key:alice",
1345
- timestamp: "2023-01-01T00:00:00Z",
1346
- },
1347
- {
1348
- predicate: "recipe://ingredient",
1349
- target: "pasta",
1350
- author: "did:key:alice",
1351
- timestamp: "2023-01-01T00:00:00Z",
1352
- },
1353
- ],
1354
- },
1009
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1010
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1011
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1012
+ ]
1013
+ }
1355
1014
  ];
1356
1015
 
1357
1016
  mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
@@ -1364,40 +1023,39 @@ describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatc
1364
1023
  expect(results[0].name).toBe("Pasta");
1365
1024
  });
1366
1025
 
1026
+ it("should use Prolog when useSurrealDB is false in findAll()", async () => {
1027
+ const prologResults = [{
1028
+ AllInstances: [
1029
+ ["literal://recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
1030
+ ],
1031
+ TotalCount: 1
1032
+ }];
1033
+
1034
+ mockPerspective.infer.mockResolvedValue(prologResults);
1035
+
1036
+ const results = await Recipe.findAll(mockPerspective, {}, false);
1037
+
1038
+ expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1039
+ expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1040
+ expect(results).toHaveLength(1);
1041
+ });
1042
+
1367
1043
  it("should use SurrealDB by default in findAllAndCount()", async () => {
1368
1044
  const surrealResults = [
1369
1045
  {
1370
1046
  source: "node:abc123",
1371
1047
  source_uri: "literal://recipe1",
1372
1048
  links: [
1373
- {
1374
- predicate: "recipe://name",
1375
- target: "Pasta",
1376
- author: "did:key:alice",
1377
- timestamp: "2023-01-01T00:00:00Z",
1378
- },
1379
- {
1380
- predicate: "recipe://rating",
1381
- target: "5",
1382
- author: "did:key:alice",
1383
- timestamp: "2023-01-01T00:00:00Z",
1384
- },
1385
- {
1386
- predicate: "recipe://ingredient",
1387
- target: "pasta",
1388
- author: "did:key:alice",
1389
- timestamp: "2023-01-01T00:00:00Z",
1390
- },
1391
- ],
1392
- },
1049
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1050
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1051
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1052
+ ]
1053
+ }
1393
1054
  ];
1394
1055
 
1395
1056
  mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1396
1057
 
1397
- const { results, totalCount } = await Recipe.findAllAndCount(
1398
- mockPerspective,
1399
- {},
1400
- );
1058
+ const { results, totalCount } = await Recipe.findAllAndCount(mockPerspective, {});
1401
1059
 
1402
1060
  expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
1403
1061
  expect(mockPerspective.infer).not.toHaveBeenCalled();
@@ -1411,26 +1069,11 @@ describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatc
1411
1069
  source: "node:abc123",
1412
1070
  source_uri: "literal://recipe1",
1413
1071
  links: [
1414
- {
1415
- predicate: "recipe://name",
1416
- target: "Pasta",
1417
- author: "did:key:alice",
1418
- timestamp: "2023-01-01T00:00:00Z",
1419
- },
1420
- {
1421
- predicate: "recipe://rating",
1422
- target: "5",
1423
- author: "did:key:alice",
1424
- timestamp: "2023-01-01T00:00:00Z",
1425
- },
1426
- {
1427
- predicate: "recipe://ingredient",
1428
- target: "pasta",
1429
- author: "did:key:alice",
1430
- timestamp: "2023-01-01T00:00:00Z",
1431
- },
1432
- ],
1433
- },
1072
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1073
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1074
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1075
+ ]
1076
+ }
1434
1077
  ];
1435
1078
 
1436
1079
  mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
@@ -1448,22 +1091,12 @@ describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatc
1448
1091
  // Since count() uses result.length and GROUP BY returns one row per source,
1449
1092
  // mock 5 recipe sources
1450
1093
  const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1451
- source: `node:abc${i + 1}`,
1452
- source_uri: `literal://recipe${i + 1}`,
1094
+ source: `node:abc${i+1}`,
1095
+ source_uri: `literal://recipe${i+1}`,
1453
1096
  links: [
1454
- {
1455
- predicate: "recipe://name",
1456
- target: `Recipe ${i + 1}`,
1457
- author: "did:key:alice",
1458
- timestamp: "2023-01-01T00:00:00Z",
1459
- },
1460
- {
1461
- predicate: "recipe://rating",
1462
- target: "5",
1463
- author: "did:key:alice",
1464
- timestamp: "2023-01-01T00:00:00Z",
1465
- },
1466
- ],
1097
+ { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1098
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1099
+ ]
1467
1100
  }));
1468
1101
 
1469
1102
  mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
@@ -1475,32 +1108,28 @@ describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatc
1475
1108
  expect(count).toBe(5);
1476
1109
  });
1477
1110
 
1111
+ it("should use Prolog when useSurrealDB is false in count()", async () => {
1112
+ const prologResults = [{ TotalCount: 10 }];
1113
+ mockPerspective.infer.mockResolvedValue(prologResults);
1114
+
1115
+ const count = await Recipe.count(mockPerspective, {}, false);
1116
+
1117
+ expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1118
+ expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1119
+ expect(count).toBe(10);
1120
+ });
1121
+
1478
1122
  it("should use SurrealDB by default in ModelQueryBuilder.get()", async () => {
1479
1123
  const surrealResults = [
1480
1124
  {
1481
1125
  source: "node:abc123",
1482
1126
  source_uri: "literal://recipe1",
1483
1127
  links: [
1484
- {
1485
- predicate: "recipe://name",
1486
- target: "Pasta",
1487
- author: "did:key:alice",
1488
- timestamp: "2023-01-01T00:00:00Z",
1489
- },
1490
- {
1491
- predicate: "recipe://rating",
1492
- target: "5",
1493
- author: "did:key:alice",
1494
- timestamp: "2023-01-01T00:00:00Z",
1495
- },
1496
- {
1497
- predicate: "recipe://ingredient",
1498
- target: "pasta",
1499
- author: "did:key:alice",
1500
- timestamp: "2023-01-01T00:00:00Z",
1501
- },
1502
- ],
1503
- },
1128
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1129
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1130
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1131
+ ]
1132
+ }
1504
1133
  ];
1505
1134
 
1506
1135
  mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
@@ -1515,25 +1144,35 @@ describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatc
1515
1144
  expect(results[0].name).toBe("Pasta");
1516
1145
  });
1517
1146
 
1147
+ it("should use Prolog when useSurrealDB(false) in ModelQueryBuilder.get()", async () => {
1148
+ const prologResults = [{
1149
+ AllInstances: [
1150
+ ["literal://recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
1151
+ ],
1152
+ TotalCount: 1
1153
+ }];
1154
+
1155
+ mockPerspective.infer.mockResolvedValue(prologResults);
1156
+
1157
+ const results = await Recipe.query(mockPerspective)
1158
+ .where({ name: "Pasta" })
1159
+ .useSurrealDB(false)
1160
+ .get();
1161
+
1162
+ expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1163
+ expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1164
+ expect(results).toHaveLength(1);
1165
+ });
1166
+
1518
1167
  it("should use SurrealDB by default in ModelQueryBuilder.count()", async () => {
1519
1168
  // count() counts the number of rows returned by the query (one row per source)
1520
1169
  const surrealResults = Array.from({ length: 3 }, (_, i) => ({
1521
- source: `node:abc${i + 1}`,
1522
- source_uri: `literal://recipe${i + 1}`,
1170
+ source: `node:abc${i+1}`,
1171
+ source_uri: `literal://recipe${i+1}`,
1523
1172
  links: [
1524
- {
1525
- predicate: "recipe://name",
1526
- target: `Recipe ${i + 1}`,
1527
- author: "did:key:alice",
1528
- timestamp: "2023-01-01T00:00:00Z",
1529
- },
1530
- {
1531
- predicate: "recipe://rating",
1532
- target: "5",
1533
- author: "did:key:alice",
1534
- timestamp: "2023-01-01T00:00:00Z",
1535
- },
1536
- ],
1173
+ { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1174
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1175
+ ]
1537
1176
  }));
1538
1177
  mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1539
1178
 
@@ -1552,26 +1191,11 @@ describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatc
1552
1191
  source: "node:abc123",
1553
1192
  source_uri: "literal://recipe1",
1554
1193
  links: [
1555
- {
1556
- predicate: "recipe://name",
1557
- target: "Pasta",
1558
- author: "did:key:alice",
1559
- timestamp: "2023-01-01T00:00:00Z",
1560
- },
1561
- {
1562
- predicate: "recipe://rating",
1563
- target: "5",
1564
- author: "did:key:alice",
1565
- timestamp: "2023-01-01T00:00:00Z",
1566
- },
1567
- {
1568
- predicate: "recipe://ingredient",
1569
- target: "pasta",
1570
- author: "did:key:alice",
1571
- timestamp: "2023-01-01T00:00:00Z",
1572
- },
1573
- ],
1574
- },
1194
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1195
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1196
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1197
+ ]
1198
+ }
1575
1199
  ];
1576
1200
 
1577
1201
  mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
@@ -1588,370 +1212,248 @@ describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatc
1588
1212
  });
1589
1213
  });
1590
1214
 
1591
- describe("resolveLanguage implicit literal default", () => {
1592
- // A plain @Property with no resolveLanguage should behave identically to
1593
- // resolveLanguage: "literal" — scalar values encoded as literal:// URIs
1594
- // are unwrapped on read, and no createExpression call is made on write.
1595
- @Model({ name: "ImplicitLiteralModel" })
1596
- class ImplicitLiteralModel extends Ad4mModel {
1597
- @Property({ through: "test://name" })
1215
+ describe("Ad4mModel.count() with advanced where conditions", () => {
1216
+ // Test Recipe model
1217
+ @Model({ name: "Recipe" })
1218
+ class Recipe extends Ad4mModel {
1219
+ @Property({ through: "recipe://name" })
1598
1220
  name: string = "";
1599
-
1600
- @Property({ through: "test://count" })
1601
- count: number = 0;
1602
-
1603
- @Property({ through: "test://active" })
1604
- active: boolean = false;
1221
+
1222
+ @Property({ through: "recipe://rating" })
1223
+ rating: number = 0;
1224
+
1225
+ @HasMany({ through: "recipe://ingredient" })
1226
+ ingredients: string[] = [];
1605
1227
  }
1606
1228
 
1229
+ // Mock perspective
1607
1230
  const mockPerspective = {
1608
1231
  querySurrealDB: jest.fn(),
1609
1232
  infer: jest.fn(),
1610
- uuid: "test-perspective-uuid",
1611
- stringOrTemplateObjectToSubjectClassName: jest
1612
- .fn()
1613
- .mockResolvedValue("ImplicitLiteralModel"),
1233
+ uuid: 'test-perspective-uuid',
1234
+ stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
1614
1235
  } as any;
1615
1236
 
1616
- beforeEach(() => jest.clearAllMocks());
1617
-
1618
- it('should store undefined resolveLanguage in metadata (not "literal")', () => {
1619
- const metadata = ImplicitLiteralModel.getModelMetadata();
1620
- expect(metadata.properties.name.resolveLanguage).toBeUndefined();
1621
- expect(metadata.properties.count.resolveLanguage).toBeUndefined();
1622
- expect(metadata.properties.active.resolveLanguage).toBeUndefined();
1237
+ beforeEach(() => {
1238
+ jest.clearAllMocks();
1623
1239
  });
1624
1240
 
1625
- it("should hydrate literal:// encoded targets for properties with no resolveLanguage", async () => {
1626
- const surrealResults = [
1627
- {
1628
- source: "node:abc123",
1629
- source_uri: "literal://base",
1630
- links: [
1631
- {
1632
- predicate: "test://name",
1633
- target: Literal.from("hello world").toUrl(),
1634
- author: "did:key:alice",
1635
- timestamp: "2023-01-01T00:00:00Z",
1636
- },
1637
- {
1638
- predicate: "test://count",
1639
- target: Literal.from(42).toUrl(),
1640
- author: "did:key:alice",
1641
- timestamp: "2023-01-01T00:00:00Z",
1642
- },
1643
- {
1644
- predicate: "test://active",
1645
- target: Literal.from(true).toUrl(),
1646
- author: "did:key:alice",
1647
- timestamp: "2023-01-01T00:00:00Z",
1648
- },
1649
- ],
1650
- },
1651
- ];
1652
-
1241
+ it("should apply JS-level filtering for gt operator on properties in SurrealDB count()", async () => {
1242
+ // Mock SurrealDB results: 5 recipes with ratings 1, 2, 3, 4, 5
1243
+ const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1244
+ source: `node:abc${i+1}`,
1245
+ source_uri: `literal://recipe${i+1}`,
1246
+ links: [
1247
+ { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1248
+ { predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1249
+ ]
1250
+ }));
1251
+
1653
1252
  mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1654
1253
 
1655
- const result = await ImplicitLiteralModel.instancesFromSurrealResult(
1656
- mockPerspective,
1657
- {},
1658
- surrealResults,
1659
- );
1660
-
1661
- expect(result.results).toHaveLength(1);
1662
- const instance = result.results[0];
1663
- expect(instance.name).toBe("hello world");
1664
- expect(instance.count).toBe(42);
1665
- expect(instance.active).toBe(true);
1254
+ // Count recipes with rating > 3 (should match 2 recipes: rating 4 and 5)
1255
+ const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } });
1256
+
1257
+ // Verify count matches the number of instances that would be returned by findAll
1258
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { gt: 3 } } });
1259
+
1260
+ expect(count).toBe(2);
1261
+ expect(count).toBe(findAllResults.length);
1666
1262
  });
1667
1263
 
1668
- it("should NOT call perspective.getExpression for properties with no resolveLanguage", async () => {
1669
- const surrealResults = [
1670
- {
1671
- source: "node:abc123",
1672
- source_uri: "literal://base",
1673
- links: [
1674
- {
1675
- predicate: "test://name",
1676
- target: Literal.from("test").toUrl(),
1677
- author: "did:key:alice",
1678
- timestamp: "2023-01-01T00:00:00Z",
1679
- },
1680
- ],
1681
- },
1682
- ];
1683
-
1264
+ it("should apply JS-level filtering for between operator on properties in SurrealDB count()", async () => {
1265
+ // Mock SurrealDB results: 5 recipes with ratings 1, 2, 3, 4, 5
1266
+ const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1267
+ source: `node:abc${i+1}`,
1268
+ source_uri: `literal://recipe${i+1}`,
1269
+ links: [
1270
+ { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1271
+ { predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1272
+ ]
1273
+ }));
1274
+
1684
1275
  mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1685
- const getExpression = jest.fn();
1686
- mockPerspective.getExpression = getExpression;
1687
-
1688
- await ImplicitLiteralModel.instancesFromSurrealResult(
1689
- mockPerspective,
1690
- {},
1691
- surrealResults,
1692
- );
1693
-
1694
- expect(getExpression).not.toHaveBeenCalled();
1695
- });
1696
- });
1697
-
1698
- describe("resolveParentPredicate()", () => {
1699
- @Model({ name: "Comment" })
1700
- class Comment extends Ad4mModel {}
1701
-
1702
- @Model({ name: "Tag" })
1703
- class Tag extends Ad4mModel {}
1704
-
1705
- @Model({ name: "Channel" })
1706
- class Channel extends Ad4mModel {
1707
- @HasMany(() => Comment, { through: "channel://has_comment" })
1708
- comments: Comment[] = [];
1709
-
1710
- @HasMany(() => Tag, { through: "channel://has_tag" })
1711
- tags: Tag[] = [];
1712
- }
1713
-
1714
- @Model({ name: "AmbiguousParent" })
1715
- class AmbiguousParent extends Ad4mModel {
1716
- @HasMany(() => Comment, { through: "parent://primary_comments" })
1717
- primaryComments: Comment[] = [];
1718
-
1719
- @HasMany(() => Comment, { through: "parent://secondary_comments" })
1720
- secondaryComments: Comment[] = [];
1721
- }
1722
-
1723
- it("resolves predicate by explicit field name", () => {
1724
- const meta = Channel.getModelMetadata();
1725
- expect(resolveParentPredicate(meta, Comment, "comments")).toBe(
1726
- "channel://has_comment",
1727
- );
1728
- });
1729
-
1730
- it("infers predicate from child constructor when field is omitted", () => {
1731
- const meta = Channel.getModelMetadata();
1732
- expect(resolveParentPredicate(meta, Comment)).toBe("channel://has_comment");
1733
- });
1734
-
1735
- it("throws when explicit field does not exist on parent", () => {
1736
- const meta = Channel.getModelMetadata();
1737
- expect(() => resolveParentPredicate(meta, Comment, "nonExistent")).toThrow(
1738
- /field "nonExistent" not found/,
1739
- );
1740
- });
1741
1276
 
1742
- it("throws when no relation on parent matches the child type", () => {
1743
- @Model({ name: "UnrelatedParent" })
1744
- class UnrelatedParent extends Ad4mModel {}
1745
- const meta = UnrelatedParent.getModelMetadata();
1746
- expect(() => resolveParentPredicate(meta, Comment)).toThrow(
1747
- /no forward relation pointing to "Comment"/,
1748
- );
1277
+ // Count recipes with rating between 2 and 4 (should match 3 recipes: rating 2, 3, 4)
1278
+ const count = await Recipe.count(mockPerspective, { where: { rating: { between: [2, 4] } } });
1279
+
1280
+ // Verify count matches the number of instances that would be returned by findAll
1281
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { between: [2, 4] } } });
1282
+
1283
+ expect(count).toBe(3);
1284
+ expect(count).toBe(findAllResults.length);
1749
1285
  });
1750
1286
 
1751
- it("throws when neither field nor childCtor is provided", () => {
1752
- const meta = Channel.getModelMetadata();
1753
- expect(() => resolveParentPredicate(meta, undefined)).toThrow(
1754
- /either "field" or a child model constructor must be provided/,
1755
- );
1756
- });
1287
+ it("should apply JS-level filtering for timestamp gt operator in SurrealDB count()", async () => {
1288
+ // Mock SurrealDB results: 5 recipes with different timestamps
1289
+ const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1290
+ source: `node:abc${i+1}`,
1291
+ source_uri: `literal://recipe${i+1}`,
1292
+ links: [
1293
+ { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1294
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1295
+ ]
1296
+ }));
1297
+
1298
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1757
1299
 
1758
- it("throws with disambiguation hint when multiple relations point to the same type", () => {
1759
- const meta = AmbiguousParent.getModelMetadata();
1760
- expect(() => resolveParentPredicate(meta, Comment)).toThrow(
1761
- /multiple relations.*provide "field" to disambiguate/i,
1762
- );
1300
+ // Count recipes with timestamp > 2023-01-03 (should match 2 recipes: 2023-01-04 and 2023-01-05)
1301
+ const targetTimestamp = new Date("2023-01-03T00:00:00Z").getTime();
1302
+ const count = await Recipe.count(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } });
1303
+
1304
+ // Verify count matches the number of instances that would be returned by findAll
1305
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } });
1306
+
1307
+ expect(count).toBe(2);
1308
+ expect(count).toBe(findAllResults.length);
1763
1309
  });
1764
- });
1765
-
1766
- describe("normalizeParentQuery()", () => {
1767
- @Model({ name: "NpqTag" })
1768
- class NpqTag extends Ad4mModel {}
1769
-
1770
- @Model({ name: "NpqComment" })
1771
- class NpqComment extends Ad4mModel {}
1772
1310
 
1773
- @Model({ name: "NpqBlogPost" })
1774
- class NpqBlogPost extends Ad4mModel {
1775
- @HasMany(() => NpqTag, { through: "blog://has_tag" })
1776
- tags: NpqTag[] = [];
1777
-
1778
- @HasMany(() => NpqComment, { through: "blog://has_comment" })
1779
- comments: NpqComment[] = [];
1780
-
1781
- @HasMany(() => NpqComment, { through: "blog://has_pinned_comment" })
1782
- pinnedComments: NpqComment[] = [];
1783
- }
1784
-
1785
- it("passes through raw { id, predicate } form unchanged", () => {
1786
- const raw = { id: "some://uri", predicate: "custom://predicate" };
1787
- expect(normalizeParentQuery(raw)).toEqual(raw);
1788
- });
1311
+ it("should apply JS-level filtering for timestamp between operator in SurrealDB count()", async () => {
1312
+ // Mock SurrealDB results: 5 recipes with different timestamps
1313
+ const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1314
+ source: `node:abc${i+1}`,
1315
+ source_uri: `literal://recipe${i+1}`,
1316
+ links: [
1317
+ { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1318
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1319
+ ]
1320
+ }));
1321
+
1322
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1789
1323
 
1790
- it("resolves model-backed form with explicit field", () => {
1791
- const result = normalizeParentQuery({
1792
- id: "some://uri",
1793
- model: NpqBlogPost,
1794
- field: "tags",
1324
+ // Count recipes with timestamp between 2023-01-02 and 2023-01-04
1325
+ const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1326
+ const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
1327
+ const count = await Recipe.count(mockPerspective, {
1328
+ where: { timestamp: { between: [startTimestamp, endTimestamp] } }
1795
1329
  });
1796
- expect(result).toEqual({ id: "some://uri", predicate: "blog://has_tag" });
1797
- });
1798
-
1799
- it("infers predicate from childCtor when field is omitted", () => {
1800
- const result = normalizeParentQuery(
1801
- { id: "some://uri", model: NpqBlogPost },
1802
- NpqTag,
1803
- );
1804
- expect(result).toEqual({ id: "some://uri", predicate: "blog://has_tag" });
1805
- });
1806
-
1807
- it("throws when model-backed form has no field and multiple relations point to the same child type", () => {
1808
- expect(() =>
1809
- normalizeParentQuery(
1810
- { id: "some://uri", model: NpqBlogPost },
1811
- NpqComment,
1812
- ),
1813
- ).toThrow(/multiple relations.*provide "field" to disambiguate/i);
1814
- });
1815
- });
1816
-
1817
- describe("Ad4mModel.update() — static convenience method", () => {
1818
- @Model({ name: "UpdatableModel" })
1819
- class UpdatableModel extends Ad4mModel {
1820
- @Property({ through: "test://title" })
1821
- title: string = "";
1822
- @Property({ through: "test://body" })
1823
- body: string = "";
1824
- @Property({ through: "test://count" })
1825
- count: number = 0;
1826
- }
1827
-
1828
- it("calls get() then save() after merging data", async () => {
1829
- const existingTitle = "Original Title";
1830
- const existingBody = "Original Body";
1831
-
1832
- const mockPerspective = {
1833
- querySurrealDB: jest.fn().mockResolvedValue([
1834
- {
1835
- source: "literal://string:abc123",
1836
- source_uri: "literal://string:abc123",
1837
- links: [
1838
- { predicate: "test://title", target: `literal://string:${existingTitle}`, author: "did:key:alice", timestamp: "2024-01-01T00:00:00Z" },
1839
- { predicate: "test://body", target: `literal://string:${existingBody}`, author: "did:key:alice", timestamp: "2024-01-01T00:00:00Z" },
1840
- { predicate: "test://count", target: "literal://number:5", author: "did:key:alice", timestamp: "2024-01-01T00:00:00Z" },
1841
- ],
1842
- },
1843
- ]),
1844
- infer: jest.fn(),
1845
- uuid: "test-uuid",
1846
- stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue("UpdatableModel"),
1847
- add: jest.fn(),
1848
- remove: jest.fn(),
1849
- get: jest.fn().mockResolvedValue([]),
1850
- removeSubject: jest.fn(),
1851
- createSubject: jest.fn(),
1852
- subjectEntities: jest.fn().mockResolvedValue([]),
1853
- } as any;
1854
-
1855
- const saveSpy = jest.spyOn(UpdatableModel.prototype, "save").mockResolvedValue();
1856
- const getSpy = jest.spyOn(UpdatableModel.prototype, "get").mockImplementation(async function (this: any) {
1857
- this.title = existingTitle;
1858
- this.body = existingBody;
1859
- this.count = 5;
1860
- return this;
1330
+
1331
+ // Verify count matches the number of instances that would be returned by findAll
1332
+ const findAllResults = await Recipe.findAll(mockPerspective, {
1333
+ where: { timestamp: { between: [startTimestamp, endTimestamp] } }
1861
1334
  });
1862
-
1863
- const result = await UpdatableModel.update(
1864
- mockPerspective,
1865
- "literal://string:abc123",
1866
- { title: "New Title" },
1867
- );
1868
-
1869
- // get() must be called to fetch the pre-existing state
1870
- expect(getSpy).toHaveBeenCalledTimes(1);
1871
-
1872
- // save() must be called after merging
1873
- expect(saveSpy).toHaveBeenCalledTimes(1);
1874
-
1875
- // Only the provided field was overwritten
1876
- expect(result.title).toBe("New Title");
1877
-
1878
- // Other fields are preserved from the fetched state
1879
- expect(result.body).toBe(existingBody);
1880
- expect(result.count).toBe(5);
1881
-
1882
- getSpy.mockRestore();
1883
- saveSpy.mockRestore();
1335
+
1336
+ expect(count).toBe(3);
1337
+ expect(count).toBe(findAllResults.length);
1884
1338
  });
1885
1339
 
1886
- it("returns the updated instance", async () => {
1887
- const saveSpy = jest.spyOn(UpdatableModel.prototype, "save").mockResolvedValue();
1888
- const getSpy = jest.spyOn(UpdatableModel.prototype, "get").mockImplementation(async function (this: any) {
1889
- this.title = "Old";
1890
- this.body = "kept";
1891
- return this;
1892
- });
1893
-
1894
- const mockPerspective = {} as any;
1895
- const result = await UpdatableModel.update(mockPerspective, "literal://string:xyz", { title: "New" });
1896
-
1897
- expect(result).toBeInstanceOf(UpdatableModel);
1898
- expect(result.id).toBe("literal://string:xyz");
1340
+ it("should apply JS-level filtering for author filtering in SurrealDB count()", async () => {
1341
+ // Mock SurrealDB results: 3 recipes by Alice and 2 by Bob
1342
+ const surrealResults = [
1343
+ ...Array.from({ length: 3 }, (_, i) => ({
1344
+ source: `node:abc${i+1}`,
1345
+ source_uri: `literal://recipe${i+1}`,
1346
+ links: [
1347
+ { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1348
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1349
+ ]
1350
+ })),
1351
+ ...Array.from({ length: 2 }, (_, i) => ({
1352
+ source: `node:def${i+4}`,
1353
+ source_uri: `literal://recipe${i+4}`,
1354
+ links: [
1355
+ { predicate: "recipe://name", target: `Recipe ${i+4}`, author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
1356
+ { predicate: "recipe://rating", target: "5", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" }
1357
+ ]
1358
+ }))
1359
+ ];
1360
+
1361
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1899
1362
 
1900
- getSpy.mockRestore();
1901
- saveSpy.mockRestore();
1363
+ // Count recipes by Alice (should match 3 recipes)
1364
+ const count = await Recipe.count(mockPerspective, { where: { author: "did:key:alice" } });
1365
+
1366
+ // Verify count matches the number of instances that would be returned by findAll
1367
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { author: "did:key:alice" } });
1368
+
1369
+ expect(count).toBe(3);
1370
+ expect(count).toBe(findAllResults.length);
1902
1371
  });
1903
1372
 
1904
- it("passes batchId through to save()", async () => {
1905
- const saveSpy = jest.spyOn(UpdatableModel.prototype, "save").mockResolvedValue();
1906
- const getSpy = jest.spyOn(UpdatableModel.prototype, "get").mockImplementation(async function (this: any) {
1907
- return this;
1908
- });
1909
-
1910
- await UpdatableModel.update({} as any, "literal://string:id1", {}, "batch-42");
1911
- expect(saveSpy).toHaveBeenCalledWith("batch-42");
1373
+ it("should apply JS-level filtering in ModelQueryBuilder.count() with gt operator", async () => {
1374
+ // Mock SurrealDB results: 5 recipes with ratings 1, 2, 3, 4, 5
1375
+ const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1376
+ source: `node:abc${i+1}`,
1377
+ source_uri: `literal://recipe${i+1}`,
1378
+ links: [
1379
+ { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1380
+ { predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1381
+ ]
1382
+ }));
1383
+
1384
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1912
1385
 
1913
- getSpy.mockRestore();
1914
- saveSpy.mockRestore();
1386
+ // Count recipes with rating > 3 using ModelQueryBuilder
1387
+ const count = await Recipe.query(mockPerspective)
1388
+ .where({ rating: { gt: 3 } })
1389
+ .count();
1390
+
1391
+ // Verify count matches the number of instances that would be returned by get()
1392
+ const getResults = await Recipe.query(mockPerspective)
1393
+ .where({ rating: { gt: 3 } })
1394
+ .get();
1395
+
1396
+ expect(count).toBe(2);
1397
+ expect(count).toBe(getResults.length);
1915
1398
  });
1916
- });
1917
1399
 
1918
- describe("Ad4mModel.delete() — static convenience method", () => {
1919
- @Model({ name: "DeletableModel" })
1920
- class DeletableModel extends Ad4mModel {
1921
- @Property({ through: "test://label" })
1922
- label: string = "";
1923
- }
1924
-
1925
- it("calls instance.delete() with no batchId by default", async () => {
1926
- const deleteSpy = jest.spyOn(DeletableModel.prototype, "delete").mockResolvedValue();
1927
-
1928
- await DeletableModel.delete({} as any, "literal://string:del1");
1929
-
1930
- expect(deleteSpy).toHaveBeenCalledTimes(1);
1931
- expect(deleteSpy).toHaveBeenCalledWith(undefined);
1400
+ it("should apply JS-level filtering in ModelQueryBuilder.count() with timestamp between", async () => {
1401
+ // Mock SurrealDB results: 5 recipes with different timestamps
1402
+ const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1403
+ source: `node:abc${i+1}`,
1404
+ source_uri: `literal://recipe${i+1}`,
1405
+ links: [
1406
+ { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1407
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1408
+ ]
1409
+ }));
1410
+
1411
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1932
1412
 
1933
- deleteSpy.mockRestore();
1413
+ const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1414
+ const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
1415
+
1416
+ // Count using ModelQueryBuilder
1417
+ const count = await Recipe.query(mockPerspective)
1418
+ .where({ timestamp: { between: [startTimestamp, endTimestamp] } })
1419
+ .count();
1420
+
1421
+ // Verify count matches the number of instances that would be returned by get()
1422
+ const getResults = await Recipe.query(mockPerspective)
1423
+ .where({ timestamp: { between: [startTimestamp, endTimestamp] } })
1424
+ .get();
1425
+
1426
+ expect(count).toBe(3);
1427
+ expect(count).toBe(getResults.length);
1934
1428
  });
1935
1429
 
1936
- it("forwards batchId to instance.delete()", async () => {
1937
- const deleteSpy = jest.spyOn(DeletableModel.prototype, "delete").mockResolvedValue();
1938
-
1939
- await DeletableModel.delete({} as any, "literal://string:del2", "batch-99");
1940
-
1941
- expect(deleteSpy).toHaveBeenCalledWith("batch-99");
1430
+ it("should handle count() with Prolog for gt operator (legacy)", async () => {
1431
+ const prologResults = [{ TotalCount: 2 }];
1432
+ mockPerspective.infer.mockResolvedValue(prologResults);
1942
1433
 
1943
- deleteSpy.mockRestore();
1434
+ const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } }, false);
1435
+
1436
+ expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1437
+ expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1438
+ expect(count).toBe(2);
1944
1439
  });
1945
1440
 
1946
- it("constructs an instance with the given id", async () => {
1947
- const deleteSpy = jest.spyOn(DeletableModel.prototype, "delete").mockResolvedValue();
1948
-
1949
- const targetId = "literal://string:target-id";
1950
- await DeletableModel.delete({} as any, targetId);
1951
-
1952
- // The static method must target the correct id
1953
- expect((deleteSpy.mock.instances[0] as unknown as DeletableModel).id).toBe(targetId);
1441
+ it("should handle count() with Prolog for timestamp between (legacy)", async () => {
1442
+ const prologResults = [{ TotalCount: 3 }];
1443
+ mockPerspective.infer.mockResolvedValue(prologResults);
1954
1444
 
1955
- deleteSpy.mockRestore();
1445
+ const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1446
+ const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
1447
+
1448
+ const count = await Recipe.count(
1449
+ mockPerspective,
1450
+ { where: { timestamp: { between: [startTimestamp, endTimestamp] } } },
1451
+ false
1452
+ );
1453
+
1454
+ expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1455
+ expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1456
+ expect(count).toBe(3);
1956
1457
  });
1957
1458
  });
1459
+