@coasys/ad4m 0.13.0-postmessage-ws-proxy.0 → 0.13.0-postmessage-ws-proxy.5

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 (52) hide show
  1. package/lib/index.cjs +825 -653
  2. package/lib/index.js +812 -654
  3. package/lib/src/Ad4mClient.d.ts +1 -0
  4. package/lib/src/Ad4mClient.js +1 -1
  5. package/lib/src/ai/AIClient.js +1 -1
  6. package/lib/src/apiClient.d.ts +4 -1
  7. package/lib/src/apiClient.js +6 -1
  8. package/lib/src/index.d.ts +4 -0
  9. package/lib/src/index.js +4 -0
  10. package/lib/src/model/Ad4mModel.d.ts +9 -32
  11. package/lib/src/model/Ad4mModel.js +36 -266
  12. package/lib/src/model/ModelQueryBuilder.d.ts +5 -10
  13. package/lib/src/model/ModelQueryBuilder.js +20 -36
  14. package/lib/src/model/decorators.d.ts +7 -4
  15. package/lib/src/model/shacl-gen.js +120 -47
  16. package/lib/src/model/types.d.ts +140 -4
  17. package/lib/src/perspectives/PerspectiveClient.d.ts +4 -4
  18. package/lib/src/perspectives/PerspectiveClient.js +5 -6
  19. package/lib/src/perspectives/PerspectiveProxy.d.ts +8 -7
  20. package/lib/src/perspectives/PerspectiveProxy.js +10 -9
  21. package/lib/src/perspectives/SparqlBindings.d.ts +47 -0
  22. package/lib/src/perspectives/SparqlBindings.js +65 -0
  23. package/lib/src/shacl/NodeExpression.d.ts +44 -0
  24. package/lib/src/shacl/NodeExpression.js +39 -0
  25. package/lib/src/shacl/SHACLShape.d.ts +23 -0
  26. package/lib/src/shacl/SHACLShape.js +115 -1
  27. package/lib/src/shacl/builders.d.ts +58 -0
  28. package/lib/src/shacl/builders.js +76 -0
  29. package/lib/src/shacl/index.d.ts +36 -0
  30. package/lib/src/shacl/index.js +33 -0
  31. package/package.json +8 -11
  32. package/src/Ad4mClient.ts +2 -2
  33. package/src/ai/AIClient.ts +1 -1
  34. package/src/apiClient.ts +8 -1
  35. package/src/index.ts +4 -0
  36. package/src/model/Ad4mModel.test.ts +33 -74
  37. package/src/model/Ad4mModel.ts +54 -272
  38. package/src/model/ModelQueryBuilder.ts +29 -46
  39. package/src/model/decorators.ts +7 -4
  40. package/src/model/relation-filtering.test.ts +46 -39
  41. package/src/model/shacl-gen.ts +128 -54
  42. package/src/model/shacl-roundtrip.test.ts +197 -0
  43. package/src/model/types-typed-query.test.ts +360 -0
  44. package/src/model/types.ts +196 -4
  45. package/src/perspectives/PerspectiveClient.ts +6 -8
  46. package/src/perspectives/PerspectiveProxy.ts +13 -13
  47. package/src/perspectives/SparqlBindings.ts +79 -0
  48. package/src/shacl/NodeExpression.ts +54 -0
  49. package/src/shacl/SHACLShape.test.ts +172 -0
  50. package/src/shacl/SHACLShape.ts +173 -1
  51. package/src/shacl/builders.ts +86 -0
  52. package/src/shacl/index.ts +72 -0
@@ -270,11 +270,18 @@ describe("generateSHACL() relation getter population", () => {
270
270
  it("should use explicit getter when provided (ignoring auto-generation)", () => {
271
271
  const { shape } = (ParentWithRelations as any).generateSHACL();
272
272
 
273
- // Getter-only relations have no predicate and are excluded from SHACL shapes
273
+ // Getter-only relations have no `through` predicate but must still
274
+ // appear in the SHACL shape so the executor can find the getter; the
275
+ // writer synthesises a deterministic IRI for `sh:path`.
274
276
  const customProp = shape.properties.find(
275
277
  (p: SHACLPropertyShape) => p.name === "customItems"
276
278
  );
277
- expect(customProp).toBeUndefined();
279
+ expect(customProp).toBeDefined();
280
+ expect(customProp!.getter).toBe(
281
+ "SELECT ?target WHERE { ?target <test://custom> ?source . }"
282
+ );
283
+ expect(customProp!.path).toBeDefined();
284
+ expect(customProp!.path).toContain("ad4m://getter/");
278
285
  });
279
286
 
280
287
  it("should survive full round-trip: generateSHACL → toLinks → fromLinks", () => {
@@ -299,11 +306,15 @@ describe("generateSHACL() relation getter population", () => {
299
306
  expect(flaggedProp!.conformanceConditions).toBeDefined();
300
307
  expect(flaggedProp!.conformanceConditions!.length).toBeGreaterThan(0);
301
308
 
302
- // The custom getter-only relation should NOT be in the SHACL shape
309
+ // Getter-only relations now round-trip too — the synthesised path
310
+ // lets the SHACL graph carry the entry through links/fromLinks.
303
311
  const customProp = reconstructed.properties.find(
304
312
  (p: SHACLPropertyShape) => p.name === "customItems"
305
313
  );
306
- expect(customProp).toBeUndefined();
314
+ expect(customProp).toBeDefined();
315
+ expect(customProp!.getter).toBe(
316
+ "SELECT ?target WHERE { ?target <test://custom> ?source . }"
317
+ );
307
318
  });
308
319
  });
309
320
 
@@ -574,7 +585,13 @@ describe("where clause validation", () => {
574
585
  });
575
586
 
576
587
  describe("where clause compilation", () => {
577
- it("should compile where clause to SPARQL getter", () => {
588
+ // Under the source-of-truth refactor the SHACL writer no longer inlines
589
+ // `where` conditions into the relation's SPARQL getter. Instead it emits
590
+ // `ad4m://whereFilter` + `ad4m://wherePredicates` triples that the
591
+ // Rust executor evaluates as a post-getter pass at query time. These
592
+ // tests assert that contract on the writer side.
593
+
594
+ it("should emit whereFilter and wherePredicates on the relation shape", () => {
578
595
  @Model({ name: "WhereTarget" })
579
596
  class WhereTarget extends Ad4mModel {
580
597
  @Property({ through: "test://status", required: true })
@@ -595,13 +612,11 @@ describe("where clause compilation", () => {
595
612
  (p: SHACLPropertyShape) => p.name === "items"
596
613
  );
597
614
  expect(itemsProp).toBeDefined();
598
- expect(itemsProp!.getter).toBeDefined();
599
- expect(itemsProp!.getter).toContain("test://has_item");
600
- expect(itemsProp!.getter).toContain("test://status");
601
- expect(itemsProp!.getter).toContain("active");
615
+ expect(itemsProp!.whereFilter).toEqual({ status: "active" });
616
+ expect(itemsProp!.wherePredicates).toEqual({ status: "test://status" });
602
617
  });
603
618
 
604
- it("should use where clause instead of auto-derived conformance when both target and where are set", () => {
619
+ it("should set whereFilter alongside an auto-derived conformance getter when target is provided", () => {
605
620
  @Model({ name: "WhereOverrideParent" })
606
621
  class WhereOverrideParent extends Ad4mModel {
607
622
  @HasMany(() => FlaggedTarget, {
@@ -616,16 +631,15 @@ describe("where clause compilation", () => {
616
631
  (p: SHACLPropertyShape) => p.name === "flaggedItems"
617
632
  );
618
633
  expect(prop).toBeDefined();
634
+ // whereFilter / wherePredicates carry the post-getter filter; type
635
+ // filtering stays on the auto-derived conformance getter.
636
+ expect(prop!.whereFilter).toEqual({ name: "specific" });
637
+ expect(prop!.wherePredicates).toEqual({ name: "test://name" });
619
638
  expect(prop!.getter).toBeDefined();
620
- // Should contain the where condition (name = specific)
621
- expect(prop!.getter).toContain("test://name");
622
- expect(prop!.getter).toContain("specific");
623
- // Should NOT contain the auto-derived flag condition
624
- // (where overrides auto-conformance)
625
- expect(prop!.getter).not.toContain("test://flagged_type");
639
+ expect(prop!.getter).toContain("test://flagged_type");
626
640
  });
627
641
 
628
- it("should compile where clause with not operator", () => {
642
+ it("should emit whereFilter with a not operator unchanged", () => {
629
643
  @Model({ name: "WhereNotTarget" })
630
644
  class WhereNotTarget extends Ad4mModel {
631
645
  @Property({ through: "test://status" })
@@ -646,13 +660,11 @@ describe("where clause compilation", () => {
646
660
  (p: SHACLPropertyShape) => p.name === "items"
647
661
  );
648
662
  expect(prop).toBeDefined();
649
- expect(prop!.getter).toBeDefined();
650
- // Should contain a negation condition
651
- expect(prop!.getter).toContain("test://status");
652
- expect(prop!.getter).toContain("archived");
663
+ expect(prop!.whereFilter).toEqual({ status: { not: "archived" } });
664
+ expect(prop!.wherePredicates).toEqual({ status: "test://status" });
653
665
  });
654
666
 
655
- it("should compile where clause with array values (IN)", () => {
667
+ it("should emit whereFilter with array (IN) values unchanged", () => {
656
668
  @Model({ name: "WhereArrayTarget" })
657
669
  class WhereArrayTarget extends Ad4mModel {
658
670
  @Property({ through: "test://category" })
@@ -673,13 +685,11 @@ describe("where clause compilation", () => {
673
685
  (p: SHACLPropertyShape) => p.name === "items"
674
686
  );
675
687
  expect(prop).toBeDefined();
676
- expect(prop!.getter).toBeDefined();
677
- expect(prop!.getter).toContain("test://category");
678
- expect(prop!.getter).toContain("food");
679
- expect(prop!.getter).toContain("drink");
688
+ expect(prop!.whereFilter).toEqual({ category: ["food", "drink"] });
689
+ expect(prop!.wherePredicates).toEqual({ category: "test://category" });
680
690
  });
681
691
 
682
- it("should compile where clause without target using raw predicate URIs", () => {
692
+ it("should emit whereFilter without wherePredicates when target metadata is absent", () => {
683
693
  @Model({ name: "WhereNoTargetParent" })
684
694
  class WhereNoTargetParent extends Ad4mModel {
685
695
  @HasMany({
@@ -694,12 +704,13 @@ describe("where clause compilation", () => {
694
704
  (p: SHACLPropertyShape) => p.name === "items"
695
705
  );
696
706
  expect(prop).toBeDefined();
697
- expect(prop!.getter).toBeDefined();
698
- expect(prop!.getter).toContain("test://status");
699
- expect(prop!.getter).toContain("active");
707
+ expect(prop!.whereFilter).toEqual({ "test://status": "active" });
708
+ // Without target metadata the writer cannot resolve property→predicate;
709
+ // the executor falls back to interpreting keys as raw IRIs.
710
+ expect(prop!.wherePredicates).toBeUndefined();
700
711
  });
701
712
 
702
- it("should set both where-compiled getter and sh:class when target is present", () => {
713
+ it("should set both whereFilter and sh:class when target is present", () => {
703
714
  @Model({ name: "WherePlusClassParent" })
704
715
  class WherePlusClassParent extends Ad4mModel {
705
716
  @HasMany(() => FlaggedTarget, {
@@ -714,15 +725,12 @@ describe("where clause compilation", () => {
714
725
  (p: SHACLPropertyShape) => p.name === "flaggedItems"
715
726
  );
716
727
  expect(prop).toBeDefined();
717
- // where-compiled getter
718
- expect(prop!.getter).toBeDefined();
719
- expect(prop!.getter).toContain("specific");
720
- // sh:class still set (target is present)
728
+ expect(prop!.whereFilter).toEqual({ name: "specific" });
721
729
  expect(prop!.class).toBeDefined();
722
730
  expect(prop!.class).toContain("FlaggedTarget");
723
731
  });
724
732
 
725
- it("should round-trip where-compiled getter through toLinks/fromLinks", () => {
733
+ it("should round-trip whereFilter and wherePredicates through toLinks/fromLinks", () => {
726
734
  @Model({ name: "WhereRoundTripTarget" })
727
735
  class WhereRoundTripTarget extends Ad4mModel {
728
736
  @Property({ through: "test://status", required: true })
@@ -749,9 +757,8 @@ describe("where clause compilation", () => {
749
757
  (p: SHACLPropertyShape) => p.name === "items"
750
758
  );
751
759
  expect(prop).toBeDefined();
752
- expect(prop!.getter).toBeDefined();
753
- expect(prop!.getter).toContain("test://status");
754
- expect(prop!.getter).toContain("active");
760
+ expect(prop!.whereFilter).toEqual({ status: "active" });
761
+ expect(prop!.wherePredicates).toEqual({ status: "test://status" });
755
762
  });
756
763
  });
757
764
 
@@ -8,8 +8,6 @@
8
8
  */
9
9
  import { SHACLShape } from "../shacl/SHACLShape";
10
10
  import type { SHACLPropertyShape, ConformanceCondition } from "../shacl/SHACLShape";
11
- import { escapeQueryString } from "../utils";
12
- import { compileWhereClause } from "./query-utils";
13
11
  import { propertyNameToSetterName } from "./util";
14
12
  import type { PropertyMetadataEntry, RelationMetadataEntry, Ad4mModelLike } from "./decorators";
15
13
 
@@ -41,9 +39,6 @@ export function buildSHACL(
41
39
 
42
40
  // ── Determine namespace from first property or relation ─────────────
43
41
  let namespace = "ad4m://";
44
- const relations = Object.fromEntries(
45
- Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany')
46
- );
47
42
 
48
43
  // Try properties first
49
44
  if (Object.keys(properties).length > 0) {
@@ -56,8 +51,8 @@ export function buildSHACL(
56
51
  }
57
52
  }
58
53
  // Fall back to relations if no properties
59
- else if (Object.keys(relations).length > 0) {
60
- const firstRel = relations[Object.keys(relations)[0]];
54
+ else if (Object.keys(allRelationsMeta).length > 0) {
55
+ const firstRel = allRelationsMeta[Object.keys(allRelationsMeta)[0]];
61
56
  if (firstRel.predicate) {
62
57
  const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
63
58
  if (match) {
@@ -142,10 +137,22 @@ export function buildSHACL(
142
137
  propShape.writable = propMeta.writable;
143
138
  }
144
139
 
145
- if (propMeta.resolveLanguage) {
140
+ if (propMeta.resolveLanguage != null) {
146
141
  propShape.resolveLanguage = propMeta.resolveLanguage;
147
142
  }
148
143
 
144
+ // Explicit getter SPARQL — the executor evaluates this when
145
+ // hydrating the property, in addition to (or instead of)
146
+ // reading raw links via `propMeta.through`.
147
+ if (propMeta.getter) {
148
+ propShape.getter = propMeta.getter;
149
+ }
150
+
151
+ // Serializable transform expression (SHACL-AF Node Expression)
152
+ if (propMeta.transform) {
153
+ propShape.transform = propMeta.transform;
154
+ }
155
+
149
156
  // ── Setter actions ──────────────────────────────────────────────
150
157
  if (propMeta.prologSetter) {
151
158
  console.warn(
@@ -190,71 +197,91 @@ export function buildSHACL(
190
197
  }
191
198
 
192
199
  // ── Convert relations to SHACL property shapes ─────────────────────
193
- for (const relName in relations) {
194
- const relMeta = relations[relName];
195
-
196
- if (!relMeta.predicate) continue;
200
+ for (const relName in allRelationsMeta) {
201
+ const relMeta = allRelationsMeta[relName];
202
+
203
+ // Getter-only relations (no `through`) have no real link predicate
204
+ // but still need a SHACL property entry so the executor can find
205
+ // the getter expression. Synthesize a deterministic IRI so the
206
+ // SHACL graph is well-formed; the predicate is never used to match
207
+ // links because the getter is the sole source of values. Use
208
+ // slash separators so the result is a valid IRI (colons in the
209
+ // authority confuse strict SPARQL IRI parsers).
210
+ if (!relMeta.predicate && !relMeta.getter) continue;
211
+ const synthesizedPath = relMeta.predicate
212
+ || `ad4m://getter/${subjectName}/${relName}`;
197
213
 
198
214
  const relShape: SHACLPropertyShape = {
199
215
  name: relName,
200
- path: relMeta.predicate,
216
+ path: synthesizedPath,
201
217
  };
202
218
 
203
219
  // Relations typically contain IRIs
204
220
  relShape.nodeKind = 'IRI';
205
221
 
222
+ // Encode relation kind so the executor can derive direction and
223
+ // scalar-vs-collection rendering without consulting the JS class.
224
+ relShape.relationKind = relMeta.kind;
225
+
226
+ // Scalar relations cap at 1.
227
+ if (relMeta.kind === 'hasOne' || relMeta.kind === 'belongsToOne') {
228
+ relShape.maxCount = 1;
229
+ } else if (relMeta.maxCount !== undefined) {
230
+ relShape.maxCount = relMeta.maxCount;
231
+ }
232
+
233
+ // Encode opt-out of type filtering (default true; only emit when false).
234
+ if (relMeta.filter === false) {
235
+ relShape.filter = false;
236
+ }
237
+
206
238
  // AD4M-specific metadata
207
239
  if (relMeta.local !== undefined) {
208
240
  relShape.local = relMeta.local;
209
241
  }
210
242
 
211
- // Adder action
212
- relShape.adder = [{
213
- action: "addLink",
214
- source: "this",
215
- predicate: relMeta.predicate,
216
- target: "value",
217
- ...(relMeta.local && { local: true })
218
- }];
219
-
220
- // Remover action
221
- relShape.remover = [{
222
- action: "removeLink",
223
- source: "this",
224
- predicate: relMeta.predicate,
225
- target: "value",
226
- ...(relMeta.local && { local: true })
227
- }];
243
+ // Adder / Remover actions — only meaningful for relations backed
244
+ // by a real link predicate. Getter-only relations are read-only.
245
+ if (relMeta.predicate) {
246
+ relShape.adder = [{
247
+ action: "addLink",
248
+ source: "this",
249
+ predicate: relMeta.predicate,
250
+ target: "value",
251
+ ...(relMeta.local && { local: true })
252
+ }];
253
+
254
+ relShape.remover = [{
255
+ action: "removeLink",
256
+ source: "this",
257
+ predicate: relMeta.predicate,
258
+ target: "value",
259
+ ...(relMeta.local && { local: true })
260
+ }];
261
+ }
228
262
 
229
263
  // ── Build Getter (conformance filter) ───────────────────────────
230
264
  // Priority chain:
231
265
  // 1. Explicit getter string → use verbatim
232
- // 2. `where` clause → compile DSL to SPARQL getter
233
- // 3. target + filter !== false → auto-derive from shape
266
+ // 2. target + filter !== false → auto-derive conformance getter
267
+ // from the shape. Where-clause filtering is applied as a
268
+ // post-getter pass via `whereFilter` / `wherePredicates`, which
269
+ // use `parse_literal_value` and so transparently handle
270
+ // `literal:json:` envelopes that simple FILTER(STR(?x) = ...)
271
+ // comparisons can't.
234
272
  if (relMeta.getter) {
235
273
  relShape.getter = relMeta.getter;
236
- } else if (relMeta.where) {
237
- try {
238
- const TargetClass = relMeta.target?.();
239
- const targetMetadata = TargetClass
240
- ? (TargetClass as any).getModelMetadata?.() ?? null
241
- : null;
242
-
243
- const conditions = compileWhereClause(
244
- relMeta.where,
245
- targetMetadata,
246
- );
247
-
248
- if (conditions.length > 0) {
249
- const escapedPredicate = escapeQueryString(relMeta.predicate);
250
- relShape.getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;
251
- }
252
- } catch (e) {
253
- // Target metadata may not be available yet
254
- }
255
- } else if (relMeta.target && relMeta.filter !== false) {
274
+ } else if (
275
+ relMeta.target
276
+ && relMeta.filter !== false
277
+ && relMeta.kind !== 'belongsToOne'
278
+ && relMeta.kind !== 'belongsToMany'
279
+ ) {
256
280
  // Lazy conformance filter: store deferred reference,
257
- // resolve on first access via a getter on relShape
281
+ // resolve on first access via a getter on relShape.
282
+ // Skipped for reverse relations (belongsTo*) because the
283
+ // auto-derived getter assumes forward direction; the executor's
284
+ // `resolve_reverse_relations` already populates these correctly.
258
285
  const targetThunk = relMeta.target;
259
286
  const predicate = relMeta.predicate;
260
287
  let resolved = false;
@@ -292,6 +319,8 @@ export function buildSHACL(
292
319
  }
293
320
 
294
321
  // ── sh:class — target shape reference ───────────────────────────
322
+ // Also emit ad4m:targetClassName so the executor can look up the
323
+ // target class shape through its in-memory cache by bare name.
295
324
  if (relMeta.target) {
296
325
  try {
297
326
  const TargetClass = relMeta.target();
@@ -299,8 +328,53 @@ export function buildSHACL(
299
328
  if (targetSHACL?.shape?.nodeShapeUri) {
300
329
  relShape.class = targetSHACL.shape.nodeShapeUri;
301
330
  }
331
+ if (targetSHACL?.name) {
332
+ relShape.targetClassName = targetSHACL.name;
333
+ } else {
334
+ const targetProto = (TargetClass as any).prototype;
335
+ if (targetProto?.className) {
336
+ relShape.targetClassName = targetProto.className;
337
+ }
338
+ }
339
+ } catch (e) {
340
+ // Target class resolution failed (typically a circular
341
+ // decorator dependency). Since the executor no longer
342
+ // receives target metadata over the wire, dropping the
343
+ // reference here would turn a transient build-time issue
344
+ // into a permanent broken-include at query time. Log
345
+ // loudly so the failure is discoverable.
346
+ console.warn(
347
+ `[shacl-gen] Failed to resolve target class for relation `
348
+ + `"${subjectName}.${relName}": ${e instanceof Error ? e.message : String(e)}`
349
+ );
350
+ }
351
+ }
352
+
353
+ // ── Where-clause metadata for post-getter filtering ─────────────
354
+ // The executor uses these to apply where conditions against the
355
+ // target class without needing the target's ModelMetadata at query time.
356
+ if (relMeta.where) {
357
+ relShape.whereFilter = relMeta.where;
358
+ try {
359
+ const TargetClass = relMeta.target?.();
360
+ const targetMetadata = TargetClass
361
+ ? (TargetClass as any).getModelMetadata?.() ?? null
362
+ : null;
363
+ if (targetMetadata?.properties) {
364
+ const predicates: Record<string, string> = {};
365
+ for (const propName of Object.keys(relMeta.where)) {
366
+ if (['id', 'author', 'timestamp'].includes(propName)) continue;
367
+ const propMeta = targetMetadata.properties[propName];
368
+ if (propMeta?.predicate) {
369
+ predicates[propName] = propMeta.predicate;
370
+ }
371
+ }
372
+ if (Object.keys(predicates).length > 0) {
373
+ relShape.wherePredicates = predicates;
374
+ }
375
+ }
302
376
  } catch (e) {
303
- // Target class may not be available yet
377
+ // Target metadata may not be available yet
304
378
  }
305
379
  }
306
380
 
@@ -0,0 +1,197 @@
1
+ /**
2
+ * Decorator → SHACL writer round-trip tests.
3
+ *
4
+ * Spec R11 gate on the TypeScript side: any field a decorator sets must
5
+ * survive into the SHACL graph produced by `generateSHACL()`. These tests
6
+ * compare against the SHACL link emission (the format the Rust executor
7
+ * stores and reads), not against `getModelMetadata()` — which is the
8
+ * dying shape transport, not the source of truth.
9
+ */
10
+ import { Ad4mModel } from "./Ad4mModel";
11
+ import {
12
+ Model,
13
+ Property,
14
+ Flag,
15
+ HasMany,
16
+ HasOne,
17
+ BelongsToOne,
18
+ BelongsToMany,
19
+ } from "./decorators";
20
+
21
+ function flatten(
22
+ shape: any,
23
+ ): Array<{ source: string; predicate: string; target: string }> {
24
+ return shape.toLinks().map((l: any) => ({
25
+ source: l.source,
26
+ predicate: l.predicate,
27
+ target: l.target,
28
+ }));
29
+ }
30
+
31
+ function findLinkTarget(
32
+ links: any[],
33
+ source: string,
34
+ predicate: string,
35
+ ): string | undefined {
36
+ return links.find((l) => l.source === source && l.predicate === predicate)
37
+ ?.target;
38
+ }
39
+
40
+ describe("Decorators → SHACL writer round-trip", () => {
41
+ it("emits ad4m:relationKind for every relation kind", () => {
42
+ @Model({ name: "Target" })
43
+ class Target extends Ad4mModel {}
44
+
45
+ @Model({ name: "Holder" })
46
+ class Holder extends Ad4mModel {
47
+ @HasMany({ through: "ns://hm", target: () => Target })
48
+ hmRel: string[] = [];
49
+
50
+ @HasOne({ through: "ns://ho", target: () => Target })
51
+ hoRel: string = "";
52
+
53
+ @BelongsToOne({ through: "ns://bto", target: () => Target })
54
+ btoRel: string = "";
55
+
56
+ @BelongsToMany({ through: "ns://btm", target: () => Target })
57
+ btmRel: string[] = [];
58
+ }
59
+
60
+ const { shape } = Holder.generateSHACL();
61
+ const links = flatten(shape);
62
+ const propUri = (name: string) => `ns://Holder.${name}`;
63
+
64
+ expect(findLinkTarget(links, propUri("hmRel"), "ad4m://relationKind")).toBe(
65
+ "literal:string:hasMany",
66
+ );
67
+ expect(findLinkTarget(links, propUri("hoRel"), "ad4m://relationKind")).toBe(
68
+ "literal:string:hasOne",
69
+ );
70
+ expect(
71
+ findLinkTarget(links, propUri("btoRel"), "ad4m://relationKind"),
72
+ ).toBe("literal:string:belongsToOne");
73
+ expect(
74
+ findLinkTarget(links, propUri("btmRel"), "ad4m://relationKind"),
75
+ ).toBe("literal:string:belongsToMany");
76
+ });
77
+
78
+ it("emits maxCount=1 for scalar relations", () => {
79
+ @Model({ name: "Target2" })
80
+ class Target2 extends Ad4mModel {}
81
+
82
+ @Model({ name: "Holder2" })
83
+ class Holder2 extends Ad4mModel {
84
+ @HasOne({ through: "ns://ho", target: () => Target2 })
85
+ hoRel: string = "";
86
+
87
+ @BelongsToOne({ through: "ns://bto", target: () => Target2 })
88
+ btoRel: string = "";
89
+ }
90
+
91
+ const { shape } = Holder2.generateSHACL();
92
+ const links = flatten(shape);
93
+
94
+ expect(findLinkTarget(links, "ns://Holder2.hoRel", "sh://maxCount")).toBe(
95
+ "literal:1^^xsd:integer",
96
+ );
97
+ expect(findLinkTarget(links, "ns://Holder2.btoRel", "sh://maxCount")).toBe(
98
+ "literal:1^^xsd:integer",
99
+ );
100
+ });
101
+
102
+ it("emits ad4m:targetClassName for relations with a target", () => {
103
+ @Model({ name: "Ingredient" })
104
+ class Ingredient extends Ad4mModel {}
105
+
106
+ @Model({ name: "Recipe" })
107
+ class Recipe extends Ad4mModel {
108
+ @HasMany({ through: "ns://ing", target: () => Ingredient })
109
+ ingredients: string[] = [];
110
+ }
111
+
112
+ const { shape } = Recipe.generateSHACL();
113
+ const links = flatten(shape);
114
+
115
+ expect(
116
+ findLinkTarget(
117
+ links,
118
+ "ns://Recipe.ingredients",
119
+ "ad4m://targetClassName",
120
+ ),
121
+ ).toBe("literal:string:Ingredient");
122
+ });
123
+
124
+ it("emits sh:hasValue for @Flag properties", () => {
125
+ @Model({ name: "Channel" })
126
+ class Channel extends Ad4mModel {
127
+ @Flag({ through: "ns://type", value: "ns://Channel" })
128
+ type: string = "";
129
+ }
130
+
131
+ const { shape } = Channel.generateSHACL();
132
+ const links = flatten(shape);
133
+
134
+ const hasValue = findLinkTarget(
135
+ links,
136
+ "ns://Channel.type",
137
+ "sh://hasValue",
138
+ );
139
+ expect(hasValue).toBeDefined();
140
+ // Writer emits literal:<value> for URI-style flags.
141
+ expect(hasValue).toContain("ns://Channel");
142
+ });
143
+
144
+ it("encodes ad4m:filter=false when explicitly disabled", () => {
145
+ @Model({ name: "Tag" })
146
+ class Tag extends Ad4mModel {}
147
+
148
+ @Model({ name: "Doc" })
149
+ class Doc extends Ad4mModel {
150
+ @HasMany({ through: "ns://tag", target: () => Tag, filter: false })
151
+ tags: string[] = [];
152
+ }
153
+
154
+ const { shape } = Doc.generateSHACL();
155
+ const links = flatten(shape);
156
+
157
+ expect(findLinkTarget(links, "ns://Doc.tags", "ad4m://filter")).toBe(
158
+ "literal:false",
159
+ );
160
+ });
161
+
162
+ it("does not emit ad4m:filter when defaulted to true", () => {
163
+ @Model({ name: "Tag2" })
164
+ class Tag2 extends Ad4mModel {}
165
+
166
+ @Model({ name: "Doc2" })
167
+ class Doc2 extends Ad4mModel {
168
+ @HasMany({ through: "ns://tag", target: () => Tag2 })
169
+ tags: string[] = [];
170
+ }
171
+
172
+ const { shape } = Doc2.generateSHACL();
173
+ const links = flatten(shape);
174
+
175
+ expect(
176
+ findLinkTarget(links, "ns://Doc2.tags", "ad4m://filter"),
177
+ ).toBeUndefined();
178
+ });
179
+
180
+ it("emits scalar property predicates", () => {
181
+ @Model({ name: "Profile" })
182
+ class Profile extends Ad4mModel {
183
+ @Property({ through: "ns://name", resolveLanguage: "literal" })
184
+ name: string = "";
185
+ }
186
+
187
+ const { shape } = Profile.generateSHACL();
188
+ const links = flatten(shape);
189
+
190
+ expect(findLinkTarget(links, "ns://Profile.name", "sh://path")).toBe(
191
+ "ns://name",
192
+ );
193
+ expect(
194
+ findLinkTarget(links, "ns://Profile.name", "ad4m://resolveLanguage"),
195
+ ).toBe("literal:string:literal");
196
+ });
197
+ });