@coasys/ad4m 0.13.0-postmessage-ws-proxy.0 → 0.13.0-postmessage-ws-proxy.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 (33) hide show
  1. package/lib/index.cjs +564 -461
  2. package/lib/index.js +561 -462
  3. package/lib/src/index.d.ts +1 -0
  4. package/lib/src/index.js +1 -0
  5. package/lib/src/model/Ad4mModel.d.ts +9 -17
  6. package/lib/src/model/Ad4mModel.js +34 -148
  7. package/lib/src/model/ModelQueryBuilder.d.ts +5 -10
  8. package/lib/src/model/ModelQueryBuilder.js +8 -14
  9. package/lib/src/model/shacl-gen.js +115 -46
  10. package/lib/src/model/types.d.ts +138 -3
  11. package/lib/src/perspectives/PerspectiveClient.d.ts +4 -4
  12. package/lib/src/perspectives/PerspectiveClient.js +5 -6
  13. package/lib/src/perspectives/PerspectiveProxy.d.ts +8 -7
  14. package/lib/src/perspectives/PerspectiveProxy.js +10 -9
  15. package/lib/src/perspectives/SparqlBindings.d.ts +47 -0
  16. package/lib/src/perspectives/SparqlBindings.js +65 -0
  17. package/lib/src/shacl/SHACLShape.d.ts +18 -0
  18. package/lib/src/shacl/SHACLShape.js +83 -0
  19. package/package.json +8 -11
  20. package/src/index.ts +1 -0
  21. package/src/model/Ad4mModel.test.ts +23 -64
  22. package/src/model/Ad4mModel.ts +52 -159
  23. package/src/model/ModelQueryBuilder.ts +17 -23
  24. package/src/model/relation-filtering.test.ts +46 -39
  25. package/src/model/shacl-gen.ts +122 -53
  26. package/src/model/shacl-roundtrip.test.ts +197 -0
  27. package/src/model/types-typed-query.test.ts +360 -0
  28. package/src/model/types.ts +194 -3
  29. package/src/perspectives/PerspectiveClient.ts +6 -8
  30. package/src/perspectives/PerspectiveProxy.ts +13 -13
  31. package/src/perspectives/SparqlBindings.ts +79 -0
  32. package/src/shacl/SHACLShape.test.ts +110 -0
  33. package/src/shacl/SHACLShape.ts +125 -0
@@ -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) {
@@ -146,6 +141,13 @@ export function buildSHACL(
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
+
149
151
  // ── Setter actions ──────────────────────────────────────────────
150
152
  if (propMeta.prologSetter) {
151
153
  console.warn(
@@ -190,71 +192,91 @@ export function buildSHACL(
190
192
  }
191
193
 
192
194
  // ── Convert relations to SHACL property shapes ─────────────────────
193
- for (const relName in relations) {
194
- const relMeta = relations[relName];
195
-
196
- if (!relMeta.predicate) continue;
195
+ for (const relName in allRelationsMeta) {
196
+ const relMeta = allRelationsMeta[relName];
197
+
198
+ // Getter-only relations (no `through`) have no real link predicate
199
+ // but still need a SHACL property entry so the executor can find
200
+ // the getter expression. Synthesize a deterministic IRI so the
201
+ // SHACL graph is well-formed; the predicate is never used to match
202
+ // links because the getter is the sole source of values. Use
203
+ // slash separators so the result is a valid IRI (colons in the
204
+ // authority confuse strict SPARQL IRI parsers).
205
+ if (!relMeta.predicate && !relMeta.getter) continue;
206
+ const synthesizedPath = relMeta.predicate
207
+ || `ad4m://getter/${subjectName}/${relName}`;
197
208
 
198
209
  const relShape: SHACLPropertyShape = {
199
210
  name: relName,
200
- path: relMeta.predicate,
211
+ path: synthesizedPath,
201
212
  };
202
213
 
203
214
  // Relations typically contain IRIs
204
215
  relShape.nodeKind = 'IRI';
205
216
 
217
+ // Encode relation kind so the executor can derive direction and
218
+ // scalar-vs-collection rendering without consulting the JS class.
219
+ relShape.relationKind = relMeta.kind;
220
+
221
+ // Scalar relations cap at 1.
222
+ if (relMeta.kind === 'hasOne' || relMeta.kind === 'belongsToOne') {
223
+ relShape.maxCount = 1;
224
+ } else if (relMeta.maxCount !== undefined) {
225
+ relShape.maxCount = relMeta.maxCount;
226
+ }
227
+
228
+ // Encode opt-out of type filtering (default true; only emit when false).
229
+ if (relMeta.filter === false) {
230
+ relShape.filter = false;
231
+ }
232
+
206
233
  // AD4M-specific metadata
207
234
  if (relMeta.local !== undefined) {
208
235
  relShape.local = relMeta.local;
209
236
  }
210
237
 
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
- }];
238
+ // Adder / Remover actions — only meaningful for relations backed
239
+ // by a real link predicate. Getter-only relations are read-only.
240
+ if (relMeta.predicate) {
241
+ relShape.adder = [{
242
+ action: "addLink",
243
+ source: "this",
244
+ predicate: relMeta.predicate,
245
+ target: "value",
246
+ ...(relMeta.local && { local: true })
247
+ }];
248
+
249
+ relShape.remover = [{
250
+ action: "removeLink",
251
+ source: "this",
252
+ predicate: relMeta.predicate,
253
+ target: "value",
254
+ ...(relMeta.local && { local: true })
255
+ }];
256
+ }
228
257
 
229
258
  // ── Build Getter (conformance filter) ───────────────────────────
230
259
  // Priority chain:
231
260
  // 1. Explicit getter string → use verbatim
232
- // 2. `where` clause → compile DSL to SPARQL getter
233
- // 3. target + filter !== false → auto-derive from shape
261
+ // 2. target + filter !== false → auto-derive conformance getter
262
+ // from the shape. Where-clause filtering is applied as a
263
+ // post-getter pass via `whereFilter` / `wherePredicates`, which
264
+ // use `parse_literal_value` and so transparently handle
265
+ // `literal:json:` envelopes that simple FILTER(STR(?x) = ...)
266
+ // comparisons can't.
234
267
  if (relMeta.getter) {
235
268
  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) {
269
+ } else if (
270
+ relMeta.target
271
+ && relMeta.filter !== false
272
+ && relMeta.kind !== 'belongsToOne'
273
+ && relMeta.kind !== 'belongsToMany'
274
+ ) {
256
275
  // Lazy conformance filter: store deferred reference,
257
- // resolve on first access via a getter on relShape
276
+ // resolve on first access via a getter on relShape.
277
+ // Skipped for reverse relations (belongsTo*) because the
278
+ // auto-derived getter assumes forward direction; the executor's
279
+ // `resolve_reverse_relations` already populates these correctly.
258
280
  const targetThunk = relMeta.target;
259
281
  const predicate = relMeta.predicate;
260
282
  let resolved = false;
@@ -292,6 +314,8 @@ export function buildSHACL(
292
314
  }
293
315
 
294
316
  // ── sh:class — target shape reference ───────────────────────────
317
+ // Also emit ad4m:targetClassName so the executor can look up the
318
+ // target class shape through its in-memory cache by bare name.
295
319
  if (relMeta.target) {
296
320
  try {
297
321
  const TargetClass = relMeta.target();
@@ -299,8 +323,53 @@ export function buildSHACL(
299
323
  if (targetSHACL?.shape?.nodeShapeUri) {
300
324
  relShape.class = targetSHACL.shape.nodeShapeUri;
301
325
  }
326
+ if (targetSHACL?.name) {
327
+ relShape.targetClassName = targetSHACL.name;
328
+ } else {
329
+ const targetProto = (TargetClass as any).prototype;
330
+ if (targetProto?.className) {
331
+ relShape.targetClassName = targetProto.className;
332
+ }
333
+ }
302
334
  } catch (e) {
303
- // Target class may not be available yet
335
+ // Target class resolution failed (typically a circular
336
+ // decorator dependency). Since the executor no longer
337
+ // receives target metadata over the wire, dropping the
338
+ // reference here would turn a transient build-time issue
339
+ // into a permanent broken-include at query time. Log
340
+ // loudly so the failure is discoverable.
341
+ console.warn(
342
+ `[shacl-gen] Failed to resolve target class for relation `
343
+ + `"${subjectName}.${relName}": ${e instanceof Error ? e.message : String(e)}`
344
+ );
345
+ }
346
+ }
347
+
348
+ // ── Where-clause metadata for post-getter filtering ─────────────
349
+ // The executor uses these to apply where conditions against the
350
+ // target class without needing the target's ModelMetadata at query time.
351
+ if (relMeta.where) {
352
+ relShape.whereFilter = relMeta.where;
353
+ try {
354
+ const TargetClass = relMeta.target?.();
355
+ const targetMetadata = TargetClass
356
+ ? (TargetClass as any).getModelMetadata?.() ?? null
357
+ : null;
358
+ if (targetMetadata?.properties) {
359
+ const predicates: Record<string, string> = {};
360
+ for (const propName of Object.keys(relMeta.where)) {
361
+ if (['id', 'author', 'timestamp'].includes(propName)) continue;
362
+ const propMeta = targetMetadata.properties[propName];
363
+ if (propMeta?.predicate) {
364
+ predicates[propName] = propMeta.predicate;
365
+ }
366
+ }
367
+ if (Object.keys(predicates).length > 0) {
368
+ relShape.wherePredicates = predicates;
369
+ }
370
+ }
371
+ } catch (e) {
372
+ // Target metadata may not be available yet
304
373
  }
305
374
  }
306
375
 
@@ -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
+ });