@coasys/ad4m 0.13.0-postmessage-ws-proxy.3 → 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 (39) hide show
  1. package/lib/index.cjs +214 -145
  2. package/lib/index.js +205 -146
  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 +3 -0
  9. package/lib/src/index.js +3 -0
  10. package/lib/src/model/Ad4mModel.d.ts +0 -15
  11. package/lib/src/model/Ad4mModel.js +2 -118
  12. package/lib/src/model/ModelQueryBuilder.js +12 -22
  13. package/lib/src/model/decorators.d.ts +7 -4
  14. package/lib/src/model/shacl-gen.js +5 -1
  15. package/lib/src/model/types.d.ts +2 -1
  16. package/lib/src/shacl/NodeExpression.d.ts +44 -0
  17. package/lib/src/shacl/NodeExpression.js +39 -0
  18. package/lib/src/shacl/SHACLShape.d.ts +5 -0
  19. package/lib/src/shacl/SHACLShape.js +32 -1
  20. package/lib/src/shacl/builders.d.ts +58 -0
  21. package/lib/src/shacl/builders.js +76 -0
  22. package/lib/src/shacl/index.d.ts +36 -0
  23. package/lib/src/shacl/index.js +33 -0
  24. package/package.json +1 -1
  25. package/src/Ad4mClient.ts +2 -2
  26. package/src/ai/AIClient.ts +1 -1
  27. package/src/apiClient.ts +8 -1
  28. package/src/index.ts +3 -0
  29. package/src/model/Ad4mModel.test.ts +10 -10
  30. package/src/model/Ad4mModel.ts +2 -113
  31. package/src/model/ModelQueryBuilder.ts +12 -23
  32. package/src/model/decorators.ts +7 -4
  33. package/src/model/shacl-gen.ts +6 -1
  34. package/src/model/types.ts +2 -1
  35. package/src/shacl/NodeExpression.ts +54 -0
  36. package/src/shacl/SHACLShape.test.ts +62 -0
  37. package/src/shacl/SHACLShape.ts +48 -1
  38. package/src/shacl/builders.ts +86 -0
  39. package/src/shacl/index.ts +72 -0
package/src/Ad4mClient.ts CHANGED
@@ -33,11 +33,11 @@ export class Ad4mClient {
33
33
  baseUrl: string,
34
34
  token?: string,
35
35
  subscribe: boolean = true,
36
- options?: { webSocketImpl?: new (url: string) => WebSocket }
36
+ options?: { webSocketImpl?: new (url: string) => WebSocket; fetchImpl?: typeof fetch }
37
37
  ) {
38
38
  this.#baseUrl = baseUrl
39
39
  this.#token = token
40
- this.#apiClient = new ApiClient(baseUrl, token, options?.webSocketImpl)
40
+ this.#apiClient = new ApiClient(baseUrl, token, options?.webSocketImpl, options?.fetchImpl)
41
41
  this.#agentClient = new AgentClient(baseUrl, token, subscribe, this.#apiClient)
42
42
  this.#expressionClient = new ExpressionClient(baseUrl, token, this.#apiClient)
43
43
  this.#languageClient = new LanguageClient(baseUrl, token, this.#apiClient)
@@ -156,7 +156,7 @@ export class AIClient {
156
156
  typedAudio.byteOffset + typedAudio.byteLength
157
157
  );
158
158
 
159
- const response = await fetch(`${baseUrl}/api/v1/ai/transcription/feed`, {
159
+ const response = await this.#apiClient.doFetch(`${baseUrl}/api/v1/ai/transcription/feed`, {
160
160
  method: 'POST',
161
161
  headers: {
162
162
  'Content-Type': 'application/octet-stream',
package/src/apiClient.ts CHANGED
@@ -44,16 +44,23 @@ export class ApiClient {
44
44
  private baseUrl: string
45
45
  private token?: string
46
46
  private readonly _webSocketImpl?: new (url: string) => WebSocket
47
+ private readonly _fetchImpl?: typeof fetch
47
48
 
48
- constructor(baseUrl: string, token?: string, webSocketImpl?: new (url: string) => WebSocket) {
49
+ constructor(baseUrl: string, token?: string, webSocketImpl?: new (url: string) => WebSocket, fetchImpl?: typeof fetch) {
49
50
  this.baseUrl = baseUrl
50
51
  this.token = token
51
52
  this._webSocketImpl = webSocketImpl
53
+ this._fetchImpl = fetchImpl
52
54
  }
53
55
 
54
56
  getBaseUrl(): string { return this.baseUrl }
55
57
  getToken(): string | undefined { return this.token }
56
58
 
59
+ /** Perform an HTTP request, using an injected fetch implementation if provided. */
60
+ doFetch(url: string, init: RequestInit): Promise<Response> {
61
+ return this._fetchImpl ? this._fetchImpl(url, init) : fetch(url, init)
62
+ }
63
+
57
64
  setToken(token: string) {
58
65
  this.token = token
59
66
  }
package/src/index.ts CHANGED
@@ -34,6 +34,9 @@ export * from "./runtime/RuntimeTypes"
34
34
  export { Model as AIModel, ModelApi, TokenizerSource, LocalModel, ModelType, ModelApiInput, TokenizerSourceInput, LocalModelInput, ModelInput, VoiceActivityParamsInput } from "./ai/AITypes"
35
35
  export * from './shacl/SHACLShape'
36
36
  export { SHACLFlow, FlowState, FlowTransition, LinkPattern, FlowableCondition } from './shacl/SHACLFlow'
37
+ export * from './shacl/NodeExpression'
38
+ export * from './shacl/builders'
39
+ export { fileToDataUri } from './shacl/index'
37
40
  export * from "./generated/api";
38
41
  export { RpcError } from "./apiClient";
39
42
  /** @deprecated Use `RpcError` instead. */
@@ -1,6 +1,7 @@
1
1
  import { Ad4mModel } from "./Ad4mModel";
2
2
  import { isIncludeProjection } from "./types";
3
3
  import { Model, Property, Optional, ReadOnly, HasMany, HasOne, Flag } from "./decorators";
4
+ import { path } from "../shacl/builders";
4
5
 
5
6
  describe("Ad4mModel.getModelMetadata()", () => {
6
7
  it("should extract basic model metadata with className", () => {
@@ -79,24 +80,23 @@ describe("Ad4mModel.getModelMetadata()", () => {
79
80
  expect(metadata.relations.local.local).toBe(true);
80
81
  });
81
82
 
82
- it("should extract transform function from property metadata", () => {
83
+ it("should support NodeExpression transforms in properties", () => {
84
+ // Transforms are now NodeExpression objects, not callable functions
85
+ // The fileToDataUri and other builders are exported from @coasys/ad4m
86
+ const transform = path("test://prefix");
87
+
83
88
  @Model({ name: "TransformModel" })
84
89
  class TransformModel extends Ad4mModel {
85
- @Optional({
90
+ @Optional({
86
91
  through: "test://data",
87
- transform: (value: string) => value.toUpperCase()
92
+ transform
88
93
  })
89
94
  data: string = "";
90
95
  }
91
96
 
92
97
  const metadata = TransformModel.getModelMetadata();
93
-
94
- // Assert transform is a function
95
- expect(typeof metadata.properties.data.transform).toBe("function");
96
-
97
- // Test the transform function
98
- const transformed = metadata.properties.data.transform!("test");
99
- expect(transformed).toBe("TEST");
98
+ expect(metadata.properties.data).toBeDefined();
99
+ expect(metadata.properties.data.transform).toEqual(transform);
100
100
  });
101
101
 
102
102
  it("should extract custom getter and setter from property metadata", () => {
@@ -25,45 +25,6 @@ import type {
25
25
  } from "./types";
26
26
 
27
27
 
28
- // ---------------------------------------------------------------------------
29
- // Default decoder for file-storage (non-literal resolveLanguage) properties
30
- // ---------------------------------------------------------------------------
31
-
32
- /**
33
- * When the Rust executor resolves a non-literal expression it may return a
34
- * `FileData`-shaped object (`{ data_base64, file_type, ... }`) rather than a
35
- * raw URI string. If the model class has no custom `transform` registered
36
- * (e.g. it was synthesised from a SHACL shape at runtime) we still want to
37
- * decode the content rather than passing raw `FileData` to callers.
38
- *
39
- * Decoding rules (mirrors the JS `decodeFileAsJson` / `decodeFileAsString` helpers):
40
- * - `application/json` (default when `file_type` is absent) → JSON.parse
41
- * - anything else → raw decoded string
42
- *
43
- * If `resolved` is not a `FileData` object the value is returned unchanged so
44
- * that callers can use this as a safe unconditional fallback.
45
- */
46
- function defaultFileDecode(resolved: unknown): unknown {
47
- if (
48
- resolved !== null &&
49
- typeof resolved === 'object' &&
50
- 'data_base64' in (resolved as object)
51
- ) {
52
- const fd = resolved as { data_base64: string; file_type?: string };
53
- let raw: string;
54
- try {
55
- raw = atob(fd.data_base64);
56
- } catch {
57
- return resolved; // malformed base64 — keep as-is
58
- }
59
- const isJson = !fd.file_type || fd.file_type === 'application/json';
60
- if (isJson) {
61
- try { return JSON.parse(raw); } catch { return raw; }
62
- }
63
- return raw;
64
- }
65
- return resolved;
66
- }
67
28
 
68
29
  // ---------------------------------------------------------------------------
69
30
  // Helpers for Rust-side include resolution
@@ -119,19 +80,6 @@ function jsonToModelInstance<T extends Ad4mModel>(
119
80
  instance[key] = value;
120
81
  }
121
82
 
122
- // Apply property transform functions from decorators (only for literal-resolved
123
- // or no-resolveLanguage properties; non-literal properties are resolved + transformed
124
- // asynchronously in executeModelQuery).
125
- try {
126
- const propsMeta = getPropertiesMetadata(ModelClass as any);
127
- for (const [propName, opts] of Object.entries(propsMeta)) {
128
- const o = opts as any;
129
- if (typeof o.transform !== 'function' || !(propName in json)) continue;
130
- // Skip non-literal resolveLanguage props — they need async expression resolution first
131
- if (o.resolveLanguage != null && o.resolveLanguage !== 'literal') continue;
132
- instance[propName] = o.transform(instance[propName]);
133
- }
134
- } catch (e) { console.debug('jsonToModelInstance: transform metadata unavailable:', e); }
135
83
 
136
84
  // Recursively convert included relation values to class instances
137
85
  if (include) {
@@ -395,8 +343,8 @@ export class Ad4mModel {
395
343
  ...(options.getter !== undefined && { getter: options.getter }),
396
344
  ...(options.prologSetter !== undefined && { prologSetter: options.prologSetter }),
397
345
  ...(options.local !== undefined && { local: options.local }),
398
- ...(options.transform !== undefined && { transform: options.transform }),
399
- ...(options.flag !== undefined && { flag: options.flag })
346
+ ...(options.flag !== undefined && { flag: options.flag }),
347
+ ...(options.transform !== undefined && { transform: options.transform })
400
348
  };
401
349
  }
402
350
 
@@ -920,59 +868,6 @@ export class Ad4mModel {
920
868
  return arr.map((json: any) => jsonToModelInstance(this, perspective, json, include, properties));
921
869
  }
922
870
 
923
- /**
924
- * Resolve non-literal (file-language) properties on an array of already-constructed
925
- * model instances. Handles two cases:
926
- *
927
- * 1. The Rust executor returned a raw URI string → fetch via `getExpression` then apply transform.
928
- * 2. The Rust executor already resolved the expression and returned a `FileData` object
929
- * (happens when the perspective backend eagerly fetches file content) → apply transform
930
- * (or `defaultFileDecode` if no transform is registered on the class, e.g. for SHACL-
931
- * synthesised model classes).
932
- *
933
- * Extracted as a public static so `ModelQueryBuilder.subscribe()` can reuse it without
934
- * duplicating logic or introducing a circular dependency.
935
- * @internal
936
- */
937
- static async resolveNonLiteralProps<T extends Ad4mModel>(
938
- this: typeof Ad4mModel & (new (...args: any[]) => T),
939
- perspective: PerspectiveProxy,
940
- instances: T[],
941
- ): Promise<void> {
942
- const propsMeta = getPropertiesMetadata(this as any);
943
- const resolveProps = Object.entries(propsMeta).filter(
944
- ([, opts]: [string, any]) =>
945
- opts.resolveLanguage != null &&
946
- opts.resolveLanguage !== 'literal',
947
- );
948
- if (resolveProps.length === 0) return;
949
-
950
- await Promise.all(
951
- instances.map(async (inst: any) => {
952
- for (const [propName, opts] of resolveProps) {
953
- const val = inst[propName];
954
- const transform = (opts as any).transform;
955
- const applyTransform = (resolved: unknown) =>
956
- typeof transform === 'function' ? transform(resolved) : defaultFileDecode(resolved);
957
-
958
- if (typeof val === 'string' && val && !val.startsWith('literal:')) {
959
- // Case 1: raw URI — fetch from language runtime
960
- try {
961
- const expression = await perspective.getExpression(val);
962
- if (expression) {
963
- let resolved: any;
964
- try { resolved = JSON.parse(expression.data); } catch { resolved = expression.data; }
965
- inst[propName] = applyTransform(resolved);
966
- }
967
- } catch (e) { console.debug(`resolveNonLiteralProps: resolution failed for '${propName}':`, e); }
968
- } else if (val !== null && val !== undefined && typeof val === 'object') {
969
- // Case 2: already resolved by Rust — apply transform / default decode
970
- inst[propName] = applyTransform(val);
971
- }
972
- }
973
- }),
974
- );
975
- }
976
871
 
977
872
  // instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
978
873
 
@@ -1004,12 +899,6 @@ export class Ad4mModel {
1004
899
  return jsonToModelInstance(this, perspective, json, query.include, query.properties);
1005
900
  });
1006
901
 
1007
- // Resolve non-literal expressions (e.g. file languages where the stored
1008
- // value is a content-addressed hash that must be fetched from the language
1009
- // runtime). The Rust endpoint may return either a raw target URI (string)
1010
- // or an already-resolved FileData object — both cases are handled here.
1011
- await (this as any).resolveNonLiteralProps(perspective, instances);
1012
-
1013
902
  // Take snapshots for dirty tracking (exclude $-prefixed projection keys)
1014
903
  const snapshotRelations = query.include
1015
904
  ? Object.fromEntries(Object.entries(query.include).filter(([k]) => !k.startsWith('$')))
@@ -387,15 +387,8 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
387
387
  return (ctor as any).parseModelResult(this.perspective, raw, this.queryParams.include, this.queryParams.properties);
388
388
  };
389
389
 
390
- // Resolve non-literal (file-language) properties — handles both raw URI strings
391
- // and already-resolved FileData objects returned by the Rust executor.
392
- const resolveAndReturn = async (instances: T[]): Promise<T[]> => {
393
- await (ctor as any).resolveNonLiteralProps(this.perspective, instances);
394
- return instances;
395
- };
396
-
397
- // Parse initial results (with non-literal resolution)
398
- const initialResults = await resolveAndReturn(parseResults(initialModelResult));
390
+ // Transforms are now applied by the Rust executor during hydration
391
+ const initialResults = parseResults(initialModelResult);
399
392
 
400
393
  // Track last emitted result fingerprint to suppress duplicate callbacks
401
394
  let lastResultFingerprint: string | null = null;
@@ -413,20 +406,16 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
413
406
  subscriptionId,
414
407
  (rawResult: any) => {
415
408
  try {
416
- const parsed = parseResults(rawResult);
417
- console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${parsed.length} instances`);
418
- resolveAndReturn(parsed).then((results) => {
419
- const fp = buildFingerprint(results);
420
- if (fp === lastResultFingerprint) {
421
- console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);
422
- return;
423
- }
424
- console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);
425
- lastResultFingerprint = fp;
426
- callback(results);
427
- }).catch((e) => {
428
- console.error('Model subscription update resolve error:', e);
429
- });
409
+ const results = parseResults(rawResult);
410
+ console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${results.length} instances`);
411
+ const fp = buildFingerprint(results);
412
+ if (fp === lastResultFingerprint) {
413
+ console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);
414
+ return;
415
+ }
416
+ console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);
417
+ lastResultFingerprint = fp;
418
+ callback(results);
430
419
  } catch (e) {
431
420
  console.error('Model subscription update parse error:', e);
432
421
  }
@@ -274,11 +274,14 @@ export interface PropertyOptions {
274
274
  local?: boolean;
275
275
 
276
276
  /**
277
- * Optional transform function to modify the property value after it is retrieved.
278
- * This is useful for transforming raw data into a more usable format.
279
- * The function takes the raw value as input and returns the transformed value.
277
+ * Optional transform expression to modify the property value.
278
+ * This is a SHACL-AF Node Expression that runs in the Rust model query engine.
279
+ * Examples: `fileToDataUri`, `concat(literal('prefix_'), focus())`, etc.
280
+ * Builders (`focus`, `literal`, `path`, `exists`, `ifExpr`, `concat`,
281
+ * `coalesce`, `fn`) and the `fileToDataUri` built-in are exported from
282
+ * the package root: `import { concat, literal, focus } from '@coasys/ad4m'`.
280
283
  */
281
- transform?: (value: any) => any;
284
+ transform?: import('../shacl/NodeExpression').NodeExpression;
282
285
 
283
286
  /**
284
287
  * Allowed values for this property (enum constraint).
@@ -137,7 +137,7 @@ export function buildSHACL(
137
137
  propShape.writable = propMeta.writable;
138
138
  }
139
139
 
140
- if (propMeta.resolveLanguage) {
140
+ if (propMeta.resolveLanguage != null) {
141
141
  propShape.resolveLanguage = propMeta.resolveLanguage;
142
142
  }
143
143
 
@@ -148,6 +148,11 @@ export function buildSHACL(
148
148
  propShape.getter = propMeta.getter;
149
149
  }
150
150
 
151
+ // Serializable transform expression (SHACL-AF Node Expression)
152
+ if (propMeta.transform) {
153
+ propShape.transform = propMeta.transform;
154
+ }
155
+
151
156
  // ── Setter actions ──────────────────────────────────────────────
152
157
  if (propMeta.prologSetter) {
153
158
  console.warn(
@@ -10,6 +10,7 @@
10
10
  // Forward type-only reference to Ad4mModel (no runtime circular dependency)
11
11
  // ---------------------------------------------------------------------------
12
12
  import type { Ad4mModel } from "./Ad4mModel";
13
+ import type { NodeExpression } from "../shacl/NodeExpression";
13
14
 
14
15
  // ---------------------------------------------------------------------------
15
16
  // Query DSL types
@@ -390,7 +391,7 @@ export interface PropertyMetadata {
390
391
  /** Whether stored locally only */
391
392
  local?: boolean;
392
393
  /** Transform function */
393
- transform?: (value: any) => any;
394
+ transform?: NodeExpression;
394
395
  /** Whether this is a flag property */
395
396
  flag?: boolean;
396
397
  }
@@ -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()', () => {
@@ -601,4 +602,65 @@ describe('SHACLShape', () => {
601
602
  expect(prop.filter).toBe(false);
602
603
  });
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
+ });
604
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
@@ -202,6 +204,11 @@ export interface SHACLPropertyShape {
202
204
  * relation. `false` opts out of DB-level type filtering while keeping
203
205
  * hydration via `include`. */
204
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;
205
212
  }
206
213
 
207
214
  /**
@@ -517,7 +524,7 @@ export class SHACLShape {
517
524
  });
518
525
  }
519
526
 
520
- if (prop.resolveLanguage) {
527
+ if (prop.resolveLanguage != null) {
521
528
  links.push({
522
529
  source: propShapeId,
523
530
  predicate: "ad4m://resolveLanguage",
@@ -621,6 +628,14 @@ export class SHACLShape {
621
628
  target: `literal:${prop.filter}`
622
629
  });
623
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
+ }
624
639
  }
625
640
 
626
641
  return links;
@@ -915,6 +930,28 @@ export class SHACLShape {
915
930
  prop.filter = val === 'true';
916
931
  }
917
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
+
918
955
  shape.addProperty(prop);
919
956
  }
920
957
 
@@ -958,6 +995,7 @@ export class SHACLShape {
958
995
  where_filter: p.whereFilter,
959
996
  where_predicates: p.wherePredicates,
960
997
  filter: p.filter,
998
+ transform: p.transform,
961
999
  })),
962
1000
  constructor_actions: this.constructor_actions,
963
1001
  destructor_actions: this.destructor_actions,
@@ -973,6 +1011,14 @@ export class SHACLShape {
973
1011
  : new SHACLShape(json.target_class);
974
1012
 
975
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
+
976
1022
  shape.addProperty({
977
1023
  path: p.path,
978
1024
  name: p.name,
@@ -999,6 +1045,7 @@ export class SHACLShape {
999
1045
  whereFilter: p.where_filter,
1000
1046
  wherePredicates: p.where_predicates,
1001
1047
  filter: p.filter,
1048
+ transform: p.transform,
1002
1049
  });
1003
1050
  }
1004
1051