@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
@@ -589,24 +589,27 @@ export class PerspectiveProxy {
589
589
  * @param query - SPARQL query string
590
590
  * @returns Query results as parsed JSON
591
591
  */
592
- async querySparql(query: string): Promise<any> {
592
+ async querySparql<T = any>(query: string): Promise<T> {
593
593
  const cached = getCachedResult(this.#handle.uuid, query);
594
- if (cached !== undefined) return cached;
594
+ if (cached !== undefined) return cached as T;
595
595
  const result = await this.#client.querySparql(this.#handle.uuid, query);
596
596
  setCachedResult(this.#handle.uuid, query, result);
597
- return result;
597
+ return result as T;
598
598
  }
599
599
 
600
600
  /**
601
601
  * Execute a model query — the executor-side replacement for SPARQL query building + JS hydration.
602
- *
602
+ *
603
+ * The executor resolves the model's shape from the perspective's SHACL
604
+ * triples (written by `addSdna`). Callers no longer ship shape
605
+ * metadata with the query; the perspective is the source of truth.
606
+ *
603
607
  * @param className - The model class name (e.g. "Recipe")
604
608
  * @param queryJson - Structured query as JSON string
605
- * @param shapeJson - Optional shape metadata JSON from the model class
606
609
  * @returns Object with `instances` array and `totalCount`
607
610
  */
608
- async modelQuery(className: string, queryJson: string, shapeJson?: string): Promise<{ instances: any[], totalCount: number }> {
609
- return await this.#client.modelQuery(this.#handle.uuid, className, queryJson, shapeJson);
611
+ async modelQuery(className: string, queryJson: string): Promise<{ instances: any[], totalCount: number }> {
612
+ return await this.#client.modelQuery(this.#handle.uuid, className, queryJson);
610
613
  }
611
614
 
612
615
  /**
@@ -618,18 +621,16 @@ export class PerspectiveProxy {
618
621
  *
619
622
  * @param className - The model class name (e.g. "Message")
620
623
  * @param instanceIds - Array of instance base expression URIs
621
- * @param shapeJson - Shape metadata JSON from the model class
622
624
  * @param propertyNames - Optional subset of property names to evaluate
623
625
  * @returns Map of instance ID → evaluated property values
624
626
  */
625
627
  async evaluateGetters(
626
628
  className: string,
627
629
  instanceIds: string[],
628
- shapeJson: string,
629
630
  propertyNames?: string[],
630
631
  ): Promise<Record<string, Record<string, any>>> {
631
632
  return await this.#client.evaluateGetters(
632
- this.#handle.uuid, className, instanceIds, shapeJson, propertyNames,
633
+ this.#handle.uuid, className, instanceIds, propertyNames,
633
634
  );
634
635
  }
635
636
 
@@ -643,11 +644,10 @@ export class PerspectiveProxy {
643
644
  *
644
645
  * @param className - The model class name
645
646
  * @param queryJson - JSON-serialized query parameters (same as modelQuery)
646
- * @param shapeJson - Optional shape metadata JSON from the model class
647
647
  * @returns Object with `subscriptionId` and initial `result`
648
648
  */
649
- async modelSubscribe(className: string, queryJson: string, shapeJson?: string): Promise<{ subscriptionId: string, result: any }> {
650
- return await this.#client.modelSubscribe(this.#handle.uuid, className, queryJson, shapeJson);
649
+ async modelSubscribe(className: string, queryJson: string): Promise<{ subscriptionId: string, result: any }> {
650
+ return await this.#client.modelSubscribe(this.#handle.uuid, className, queryJson);
651
651
  }
652
652
 
653
653
  /**
@@ -0,0 +1,79 @@
1
+ /**
2
+ * SPARQL binding helpers — typed shapes and parsers for `querySparql<T>()`.
3
+ *
4
+ * AD4M stores non-string property values as URL-encoded `Literal` payloads
5
+ * (see {@link Literal}). When raw SPARQL queries pull these values out of the
6
+ * RDF store the bindings are still in encoded form; consumers must decode
7
+ * before use. The helpers here centralise that decode step so each call site
8
+ * can pick the variant matching its declared binding type.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * interface MessageBinding {
13
+ * id: string;
14
+ * timestamp: string; // raw literal — decode with parseLitNumber
15
+ * body?: string; // raw literal — decode with parseLit
16
+ * }
17
+ * const rows = await perspective.querySparql<MessageBinding[]>(query);
18
+ * const ts = parseLitNumber(rows[0].timestamp); // number
19
+ * const body = rows[0].body ? parseLit(rows[0].body) : '';
20
+ * ```
21
+ */
22
+
23
+ import { Literal } from "../Literal";
24
+
25
+ /** Common AD4M link binding — matches the `?source/?predicate/?target/?author/?timestamp` pattern. */
26
+ export interface LinkBinding {
27
+ source: string;
28
+ predicate: string;
29
+ target: string;
30
+ author?: string;
31
+ timestamp?: string;
32
+ }
33
+
34
+ /** COUNT(?x) result binding — SPARQL returns counts as string literals. */
35
+ export interface CountBinding {
36
+ count: string;
37
+ }
38
+
39
+ /** Sum a SPARQL COUNT(?x) result down to a plain number (returns 0 on empty). */
40
+ export function parseSparqlCount(result: CountBinding[] | undefined | null): number {
41
+ if (!result || result.length === 0) return 0;
42
+ const raw = result[0].count;
43
+ const n = parseInt(raw, 10);
44
+ return Number.isNaN(n) ? 0 : n;
45
+ }
46
+
47
+ /**
48
+ * Decode a `Literal`-encoded SPARQL binding back to a plain string.
49
+ *
50
+ * Mirrors Flux's local `parseLit` helper. Returns `''` for `undefined`/empty
51
+ * input. Falls through to the raw value if decoding fails (defensive — the
52
+ * binding may already be a plain string for unwrapped properties).
53
+ */
54
+ export function parseLit(val: string | undefined | null): string {
55
+ if (val === undefined || val === null || val === '') return '';
56
+ try {
57
+ const result = Literal.fromUrl(val).get();
58
+ if (result && typeof result === 'object') {
59
+ return (result as { data?: string }).data ?? JSON.stringify(result);
60
+ }
61
+ return String(result);
62
+ } catch {
63
+ return val;
64
+ }
65
+ }
66
+
67
+ /** Decode a `Literal`-encoded binding to a number. Returns 0 on empty/invalid input. */
68
+ export function parseLitNumber(val: string | undefined | null): number {
69
+ if (val === undefined || val === null || val === '') return 0;
70
+ const decoded = parseLit(val);
71
+ const n = Number(decoded);
72
+ return Number.isNaN(n) ? 0 : n;
73
+ }
74
+
75
+ /** Decode a `Literal`-encoded binding to a boolean. Returns false on empty input. */
76
+ export function parseLitBoolean(val: string | undefined | null): boolean {
77
+ if (val === undefined || val === null || val === '') return false;
78
+ return parseLit(val) === 'true';
79
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * SHACL-AF Node Expressions for property transforms.
3
+ *
4
+ * A `NodeExpression` is a JSON-serializable tree that describes how to transform
5
+ * a resolved property value. Unlike JS lambdas, these are portable, inspectable,
6
+ * and can be executed in the Rust model query engine.
7
+ *
8
+ * Each expression is a tagged union that evaluates to a `Value` (JSON-compatible).
9
+ */
10
+
11
+ /**
12
+ * Union type representing all supported transform expressions.
13
+ * Each variant maps to a SHACL-AF §6 expression construct.
14
+ */
15
+ export type NodeExpression =
16
+ | { type: 'focus' }
17
+ | { type: 'literal'; value: string | number | boolean }
18
+ | { type: 'path'; predicate: string }
19
+ | { type: 'exists'; expr: NodeExpression }
20
+ | { type: 'if'; cond: NodeExpression; then: NodeExpression; else?: NodeExpression }
21
+ | { type: 'concat'; args: NodeExpression[] }
22
+ | { type: 'coalesce'; args: NodeExpression[] }
23
+ | { type: 'function'; iri: string; args: NodeExpression[] };
24
+
25
+ /**
26
+ * Type guard to check if a value is a valid NodeExpression.
27
+ */
28
+ export function isNodeExpression(v: unknown): v is NodeExpression {
29
+ if (typeof v !== 'object' || v === null) return false;
30
+ const obj = v as any;
31
+ const type = obj.type;
32
+
33
+ switch (type) {
34
+ case 'focus':
35
+ return typeof obj.type === 'string';
36
+ case 'literal':
37
+ return typeof obj.value === 'string' || typeof obj.value === 'number' || typeof obj.value === 'boolean';
38
+ case 'path':
39
+ return typeof obj.predicate === 'string';
40
+ case 'exists':
41
+ return isNodeExpression(obj.expr);
42
+ case 'if':
43
+ return isNodeExpression(obj.cond) && isNodeExpression(obj.then) &&
44
+ (obj.else === undefined || isNodeExpression(obj.else));
45
+ case 'concat':
46
+ return Array.isArray(obj.args) && obj.args.every(isNodeExpression);
47
+ case 'coalesce':
48
+ return Array.isArray(obj.args) && obj.args.every(isNodeExpression);
49
+ case 'function':
50
+ return typeof obj.iri === 'string' && Array.isArray(obj.args) && obj.args.every(isNodeExpression);
51
+ default:
52
+ return false;
53
+ }
54
+ }
@@ -1,4 +1,5 @@
1
1
  import { SHACLShape, SHACLPropertyShape, AD4MAction } from './SHACLShape';
2
+ import { concat, literal, focus } from './builders';
2
3
 
3
4
  describe('SHACLShape', () => {
4
5
  describe('toLinks()', () => {
@@ -491,4 +492,175 @@ describe('SHACLShape', () => {
491
492
  expect(reconstructed.properties[0].in).toEqual(original.properties[0].in);
492
493
  });
493
494
  });
495
+
496
+ describe('runtime metadata predicates (SHACL as source of truth)', () => {
497
+ it('emits and parses relationKind', () => {
498
+ const shape = new SHACLShape('ns://Recipe');
499
+ shape.addProperty({
500
+ name: 'ingredients',
501
+ path: 'ns://has_ingredient',
502
+ relationKind: 'hasMany',
503
+ });
504
+ const links = shape.toLinks();
505
+ const kindLink = links.find(l => l.predicate === 'ad4m://relationKind');
506
+ expect(kindLink?.target).toBe('literal:string:hasMany');
507
+
508
+ const round = SHACLShape.fromLinks(links, shape.nodeShapeUri);
509
+ expect(round.properties[0].relationKind).toBe('hasMany');
510
+ });
511
+
512
+ it('emits and parses targetClassName', () => {
513
+ const shape = new SHACLShape('ns://Recipe');
514
+ shape.addProperty({
515
+ name: 'ingredients',
516
+ path: 'ns://has_ingredient',
517
+ targetClassName: 'Ingredient',
518
+ });
519
+ const links = shape.toLinks();
520
+ const link = links.find(l => l.predicate === 'ad4m://targetClassName');
521
+ expect(link?.target).toBe('literal:string:Ingredient');
522
+
523
+ const round = SHACLShape.fromLinks(links, shape.nodeShapeUri);
524
+ expect(round.properties[0].targetClassName).toBe('Ingredient');
525
+ });
526
+
527
+ it('emits and parses whereFilter as a JSON literal', () => {
528
+ const shape = new SHACLShape('ns://Board');
529
+ shape.addProperty({
530
+ name: 'tasks',
531
+ path: 'ns://has_task',
532
+ whereFilter: { status: 'active' },
533
+ });
534
+ const links = shape.toLinks();
535
+ const link = links.find(l => l.predicate === 'ad4m://whereFilter');
536
+ expect(link?.target).toContain('"status"');
537
+
538
+ const round = SHACLShape.fromLinks(links, shape.nodeShapeUri);
539
+ expect(round.properties[0].whereFilter).toEqual({ status: 'active' });
540
+ });
541
+
542
+ it('emits and parses wherePredicates', () => {
543
+ const shape = new SHACLShape('ns://Board');
544
+ shape.addProperty({
545
+ name: 'tasks',
546
+ path: 'ns://has_task',
547
+ wherePredicates: { status: 'ns://status' },
548
+ });
549
+ const links = shape.toLinks();
550
+ const link = links.find(l => l.predicate === 'ad4m://wherePredicates');
551
+ expect(link).toBeDefined();
552
+
553
+ const round = SHACLShape.fromLinks(links, shape.nodeShapeUri);
554
+ expect(round.properties[0].wherePredicates).toEqual({ status: 'ns://status' });
555
+ });
556
+
557
+ it('omits wherePredicates link for empty maps', () => {
558
+ const shape = new SHACLShape('ns://Board');
559
+ shape.addProperty({
560
+ name: 'tasks',
561
+ path: 'ns://has_task',
562
+ wherePredicates: {},
563
+ });
564
+ const links = shape.toLinks();
565
+ const link = links.find(l => l.predicate === 'ad4m://wherePredicates');
566
+ expect(link).toBeUndefined();
567
+ });
568
+
569
+ it('emits and parses filter=false as a literal boolean', () => {
570
+ const shape = new SHACLShape('ns://Doc');
571
+ shape.addProperty({
572
+ name: 'tags',
573
+ path: 'ns://tag',
574
+ filter: false,
575
+ });
576
+ const links = shape.toLinks();
577
+ const link = links.find(l => l.predicate === 'ad4m://filter');
578
+ expect(link?.target).toBe('literal:false');
579
+
580
+ const round = SHACLShape.fromLinks(links, shape.nodeShapeUri);
581
+ expect(round.properties[0].filter).toBe(false);
582
+ });
583
+
584
+ it('round-trips all runtime metadata through toJSON() and fromJSON()', () => {
585
+ const original = new SHACLShape('ns://Board');
586
+ original.addProperty({
587
+ name: 'tasks',
588
+ path: 'ns://has_task',
589
+ relationKind: 'hasMany',
590
+ targetClassName: 'Task',
591
+ whereFilter: { status: 'active' },
592
+ wherePredicates: { status: 'ns://status' },
593
+ filter: false,
594
+ });
595
+ const json = original.toJSON();
596
+ const reconstructed = SHACLShape.fromJSON(json);
597
+ const prop = reconstructed.properties[0];
598
+ expect(prop.relationKind).toBe('hasMany');
599
+ expect(prop.targetClassName).toBe('Task');
600
+ expect(prop.whereFilter).toEqual({ status: 'active' });
601
+ expect(prop.wherePredicates).toEqual({ status: 'ns://status' });
602
+ expect(prop.filter).toBe(false);
603
+ });
604
+ });
605
+
606
+ describe('transform property emission', () => {
607
+ it('emits an ad4m://transform link when transform is a NodeExpression', () => {
608
+ const shape = new SHACLShape('ns://ImagePost');
609
+ shape.addProperty({
610
+ name: 'image',
611
+ path: 'image://data',
612
+ datatype: 'xsd://string',
613
+ resolveLanguage: '',
614
+ transform: concat(literal('data:image/png;base64,'), focus()),
615
+ });
616
+
617
+ const links = shape.toLinks();
618
+ const transformLinks = links.filter(l => l.predicate === 'ad4m://transform');
619
+ expect(transformLinks).toHaveLength(1);
620
+
621
+ // Payload must be a SHACL-serialized NodeExpression, never raw JS.
622
+ const target = transformLinks[0].target;
623
+ expect(target.startsWith('literal:string:')).toBe(true);
624
+ const json = target.replace(/^literal:string:/, '');
625
+ expect(() => JSON.parse(json)).not.toThrow();
626
+ expect(JSON.parse(json)).toEqual({
627
+ type: 'concat',
628
+ args: [
629
+ { type: 'literal', value: 'data:image/png;base64,' },
630
+ { type: 'focus' },
631
+ ],
632
+ });
633
+ });
634
+
635
+ // Regression guard for the `typeof prop.transform === 'object'` clause
636
+ // added alongside the SHACL-source-of-truth round-trip fix. Legacy model
637
+ // decorators still declare JS-function transforms (e.g. the pre-DSL
638
+ // `transform: (data) => ...` form). Those cannot be represented as a
639
+ // SHACL-AF Node Expression and must be silently dropped during link
640
+ // emission — never coerced through `JSON.stringify`, which would write a
641
+ // bogus `literal:string:undefined` triple and corrupt the store.
642
+ it('silently drops function-typed transforms (no ad4m://transform link emitted)', () => {
643
+ const shape = new SHACLShape('ns://LegacyModel');
644
+ shape.addProperty({
645
+ name: 'image',
646
+ path: 'ns://image',
647
+ datatype: 'xsd://string',
648
+ // Legacy JS-function form, still found in pre-migration model classes.
649
+ // Cast through `any` because the public type only permits NodeExpression.
650
+ transform: ((data: any) => `data:image/png;base64,${data}`) as any,
651
+ });
652
+
653
+ const links = shape.toLinks();
654
+ const transformLinks = links.filter(l => l.predicate === 'ad4m://transform');
655
+ expect(transformLinks).toHaveLength(0);
656
+
657
+ // Defensive: nothing in the emitted link set should carry the string
658
+ // "undefined" or a serialized function — that would indicate an
659
+ // accidental JSON.stringify of the function value.
660
+ for (const link of links) {
661
+ expect(link.target).not.toMatch(/^literal:string:undefined$/);
662
+ expect(link.target).not.toMatch(/^literal:string:.*function/);
663
+ }
664
+ });
665
+ });
494
666
  });
@@ -1,4 +1,6 @@
1
1
  import { Link } from "../links/Links";
2
+ import type { NodeExpression } from "./NodeExpression";
3
+ import { isNodeExpression } from "./NodeExpression";
2
4
 
3
5
  /**
4
6
  * Extract namespace from a URI
@@ -179,6 +181,34 @@ export interface SHACLPropertyShape {
179
181
  * Each entry has a `value` (the RDF term) and an optional `label` (human-readable name).
180
182
  * Standard SHACL `sh:in` only defines values; labels are an AD4M extension. */
181
183
  in?: Array<{ value: string; label?: string }>;
184
+
185
+ /** AD4M-specific: kind of relation this property describes.
186
+ * Drives direction (forward/reverse), scalar-vs-collection rendering,
187
+ * and default max-count. */
188
+ relationKind?: 'hasMany' | 'hasOne' | 'belongsToOne' | 'belongsToMany';
189
+
190
+ /** AD4M-specific: target class name (local-name) for a relation property.
191
+ * Complements `class` (the SHACL node-shape URI) by providing the bare
192
+ * model class name used by the executor to look up the target shape
193
+ * through the perspective's shape cache. */
194
+ targetClassName?: string;
195
+
196
+ /** AD4M-specific: post-getter where-clause filter for a relation property. */
197
+ whereFilter?: any;
198
+
199
+ /** AD4M-specific: predicate-IRI lookup map for `whereFilter` keys
200
+ * (property name → predicate URI on the target class). */
201
+ wherePredicates?: Record<string, string>;
202
+
203
+ /** AD4M-specific: whether conformance/type filtering is enabled for this
204
+ * relation. `false` opts out of DB-level type filtering while keeping
205
+ * hydration via `include`. */
206
+ filter?: boolean;
207
+
208
+ /** AD4M-specific: Transform expression (SHACL-AF Node Expression).
209
+ * Applied to resolved property values in the Rust model query engine.
210
+ * Only used for properties with resolveLanguage set. */
211
+ transform?: NodeExpression;
182
212
  }
183
213
 
184
214
  /**
@@ -494,7 +524,7 @@ export class SHACLShape {
494
524
  });
495
525
  }
496
526
 
497
- if (prop.resolveLanguage) {
527
+ if (prop.resolveLanguage != null) {
498
528
  links.push({
499
529
  source: propShapeId,
500
530
  predicate: "ad4m://resolveLanguage",
@@ -558,6 +588,54 @@ export class SHACLShape {
558
588
  target: `literal:string:${JSON.stringify(prop.in)}`
559
589
  });
560
590
  }
591
+
592
+ if (prop.relationKind) {
593
+ links.push({
594
+ source: propShapeId,
595
+ predicate: "ad4m://relationKind",
596
+ target: `literal:string:${prop.relationKind}`
597
+ });
598
+ }
599
+
600
+ if (prop.targetClassName) {
601
+ links.push({
602
+ source: propShapeId,
603
+ predicate: "ad4m://targetClassName",
604
+ target: `literal:string:${prop.targetClassName}`
605
+ });
606
+ }
607
+
608
+ if (prop.whereFilter !== undefined && prop.whereFilter !== null) {
609
+ links.push({
610
+ source: propShapeId,
611
+ predicate: "ad4m://whereFilter",
612
+ target: `literal:string:${JSON.stringify(prop.whereFilter)}`
613
+ });
614
+ }
615
+
616
+ if (prop.wherePredicates && Object.keys(prop.wherePredicates).length > 0) {
617
+ links.push({
618
+ source: propShapeId,
619
+ predicate: "ad4m://wherePredicates",
620
+ target: `literal:string:${JSON.stringify(prop.wherePredicates)}`
621
+ });
622
+ }
623
+
624
+ if (prop.filter !== undefined) {
625
+ links.push({
626
+ source: propShapeId,
627
+ predicate: "ad4m://filter",
628
+ target: `literal:${prop.filter}`
629
+ });
630
+ }
631
+
632
+ if (prop.transform && typeof prop.transform === 'object') {
633
+ links.push({
634
+ source: propShapeId,
635
+ predicate: "ad4m://transform",
636
+ target: `literal:string:${JSON.stringify(prop.transform)}`
637
+ });
638
+ }
561
639
  }
562
640
 
563
641
  return links;
@@ -800,6 +878,80 @@ export class SHACLShape {
800
878
  }
801
879
  }
802
880
 
881
+ const relationKindLink = links.find(l =>
882
+ l.source === propShapeId && l.predicate === "ad4m://relationKind"
883
+ );
884
+ if (relationKindLink) {
885
+ const val = relationKindLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
886
+ if (val === 'hasMany' || val === 'hasOne' || val === 'belongsToOne' || val === 'belongsToMany') {
887
+ prop.relationKind = val;
888
+ }
889
+ }
890
+
891
+ const targetClassNameLink = links.find(l =>
892
+ l.source === propShapeId && l.predicate === "ad4m://targetClassName"
893
+ );
894
+ if (targetClassNameLink) {
895
+ prop.targetClassName = targetClassNameLink.target.replace(
896
+ /^literal:\/\/string:|^literal:string:/, ''
897
+ );
898
+ }
899
+
900
+ const whereFilterLink = links.find(l =>
901
+ l.source === propShapeId && l.predicate === "ad4m://whereFilter"
902
+ );
903
+ if (whereFilterLink) {
904
+ try {
905
+ const jsonStr = whereFilterLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
906
+ prop.whereFilter = JSON.parse(jsonStr);
907
+ } catch (e) {
908
+ // Ignore parse errors
909
+ }
910
+ }
911
+
912
+ const wherePredicatesLink = links.find(l =>
913
+ l.source === propShapeId && l.predicate === "ad4m://wherePredicates"
914
+ );
915
+ if (wherePredicatesLink) {
916
+ try {
917
+ const jsonStr = wherePredicatesLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
918
+ prop.wherePredicates = JSON.parse(jsonStr);
919
+ } catch (e) {
920
+ // Ignore parse errors
921
+ }
922
+ }
923
+
924
+ const filterLink = links.find(l =>
925
+ l.source === propShapeId && l.predicate === "ad4m://filter"
926
+ );
927
+ if (filterLink) {
928
+ let val = filterLink.target.replace(/^literal:\/\/|^literal:/, '');
929
+ if (val.startsWith('boolean:')) val = val.substring(8);
930
+ prop.filter = val === 'true';
931
+ }
932
+
933
+ const transformLink = links.find(l =>
934
+ l.source === propShapeId && l.predicate === "ad4m://transform"
935
+ );
936
+ if (transformLink) {
937
+ const jsonStr = transformLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
938
+ try {
939
+ const parsed = JSON.parse(jsonStr);
940
+ if (!isNodeExpression(parsed)) {
941
+ throw new Error(
942
+ `Invalid transform for property ${propShapeId}: ` +
943
+ `payload is not a valid NodeExpression. Received: ${jsonStr}`
944
+ );
945
+ }
946
+ prop.transform = parsed;
947
+ } catch (e) {
948
+ throw new Error(
949
+ `Failed to deserialize transform for property ${propShapeId}: ` +
950
+ `${e instanceof Error ? e.message : String(e)}. Payload: ${jsonStr}`
951
+ );
952
+ }
953
+ }
954
+
803
955
  shape.addProperty(prop);
804
956
  }
805
957
 
@@ -838,6 +990,12 @@ export class SHACLShape {
838
990
  conformance_conditions: p.conformanceConditions,
839
991
  class: p.class,
840
992
  in: p.in,
993
+ relation_kind: p.relationKind,
994
+ target_class_name: p.targetClassName,
995
+ where_filter: p.whereFilter,
996
+ where_predicates: p.wherePredicates,
997
+ filter: p.filter,
998
+ transform: p.transform,
841
999
  })),
842
1000
  constructor_actions: this.constructor_actions,
843
1001
  destructor_actions: this.destructor_actions,
@@ -853,6 +1011,14 @@ export class SHACLShape {
853
1011
  : new SHACLShape(json.target_class);
854
1012
 
855
1013
  for (const p of json.properties || []) {
1014
+ // Validate transform if present
1015
+ if (p.transform && !isNodeExpression(p.transform)) {
1016
+ throw new Error(
1017
+ `Invalid transform for property ${p.name}: ` +
1018
+ `payload is not a valid NodeExpression. Received: ${JSON.stringify(p.transform)}`
1019
+ );
1020
+ }
1021
+
856
1022
  shape.addProperty({
857
1023
  path: p.path,
858
1024
  name: p.name,
@@ -874,6 +1040,12 @@ export class SHACLShape {
874
1040
  conformanceConditions: p.conformance_conditions,
875
1041
  class: p.class,
876
1042
  in: p.in,
1043
+ relationKind: p.relation_kind,
1044
+ targetClassName: p.target_class_name,
1045
+ whereFilter: p.where_filter,
1046
+ wherePredicates: p.where_predicates,
1047
+ filter: p.filter,
1048
+ transform: p.transform,
877
1049
  });
878
1050
  }
879
1051