@coasys/ad4m 0.13.0-test-1 → 0.13.0-test-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 (115) hide show
  1. package/lib/index.cjs +2377 -849
  2. package/lib/index.js +2354 -846
  3. package/lib/src/Literal.js +6 -5
  4. package/lib/src/agent/AgentClient.d.ts +5 -1
  5. package/lib/src/agent/AgentClient.js +48 -2
  6. package/lib/src/expression/ExpressionRef.js +2 -2
  7. package/lib/src/index.d.ts +0 -1
  8. package/lib/src/index.js +0 -1
  9. package/lib/src/language/Language.d.ts +26 -176
  10. package/lib/src/language/Language.js +28 -2
  11. package/lib/src/model/Ad4mModel.d.ts +52 -28
  12. package/lib/src/model/Ad4mModel.js +255 -118
  13. package/lib/src/model/Ad4mModel.test.js +1727 -537
  14. package/lib/src/model/ModelQueryBuilder.d.ts +67 -34
  15. package/lib/src/model/ModelQueryBuilder.js +208 -79
  16. package/lib/src/model/Subject.js +6 -6
  17. package/lib/src/model/decorators.d.ts +14 -8
  18. package/lib/src/model/decorators.js +41 -14
  19. package/lib/src/model/hydration-batch.d.ts +34 -0
  20. package/lib/src/model/hydration-batch.js +147 -0
  21. package/lib/src/model/hydration-batching.test.d.ts +7 -0
  22. package/lib/src/model/hydration-batching.test.js +456 -0
  23. package/lib/src/model/hydration.d.ts +4 -3
  24. package/lib/src/model/hydration.js +365 -86
  25. package/lib/src/model/index.d.ts +4 -1
  26. package/lib/src/model/index.js +4 -1
  27. package/lib/src/model/json-schema.js +2 -2
  28. package/lib/src/model/query-cache.d.ts +30 -0
  29. package/lib/src/model/query-cache.js +66 -0
  30. package/lib/src/model/query-cache.test.d.ts +1 -0
  31. package/lib/src/model/query-cache.test.js +43 -0
  32. package/lib/src/model/query-common.d.ts +1 -1
  33. package/lib/src/model/query-common.js +1 -1
  34. package/lib/src/model/query-sparql-batch.d.ts +17 -0
  35. package/lib/src/model/query-sparql-batch.js +260 -0
  36. package/lib/src/model/query-sparql.d.ts +124 -0
  37. package/lib/src/model/query-sparql.js +767 -0
  38. package/lib/src/model/query-sparql.test.d.ts +1 -0
  39. package/lib/src/model/query-sparql.test.js +495 -0
  40. package/lib/src/model/{surreal-utils.d.ts → query-utils.d.ts} +12 -9
  41. package/lib/src/model/{surreal-utils.js → query-utils.js} +43 -27
  42. package/lib/src/model/relation-filtering.test.js +15 -15
  43. package/lib/src/model/sdna.js +1 -1
  44. package/lib/src/model/shacl-gen.js +42 -18
  45. package/lib/src/model/subscription-delta.test.d.ts +24 -0
  46. package/lib/src/model/subscription-delta.test.js +180 -0
  47. package/lib/src/model/subscription-pool.d.ts +39 -0
  48. package/lib/src/model/subscription-pool.js +165 -0
  49. package/lib/src/model/types.d.ts +52 -4
  50. package/lib/src/model/types.js +1 -1
  51. package/lib/src/perspectives/PerspectiveClient.d.ts +3 -17
  52. package/lib/src/perspectives/PerspectiveClient.js +42 -66
  53. package/lib/src/perspectives/PerspectiveClient.test.d.ts +1 -0
  54. package/lib/src/perspectives/PerspectiveClient.test.js +169 -0
  55. package/lib/src/perspectives/PerspectiveProxy.d.ts +54 -30
  56. package/lib/src/perspectives/PerspectiveProxy.js +239 -177
  57. package/lib/src/perspectives/PerspectiveResolver.d.ts +0 -1
  58. package/lib/src/perspectives/PerspectiveResolver.js +0 -11
  59. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +3 -3
  60. package/lib/src/perspectives/WakerSubscriptionManager.js +7 -8
  61. package/lib/src/runtime/RuntimeResolver.d.ts +11 -0
  62. package/lib/src/runtime/RuntimeResolver.js +56 -0
  63. package/lib/src/schema.gql +11 -1
  64. package/lib/src/shacl/SHACLFlow.d.ts +1 -1
  65. package/lib/src/shacl/SHACLFlow.js +9 -9
  66. package/lib/src/shacl/SHACLShape.d.ts +1 -1
  67. package/lib/src/shacl/SHACLShape.js +38 -38
  68. package/lib/src/typeDefs.js +11 -1
  69. package/lib/src/utils.d.ts +6 -6
  70. package/lib/src/utils.js +6 -6
  71. package/package.json +1 -1
  72. package/src/Ad4mClient.test.ts +56 -1
  73. package/src/Literal.test.ts +10 -5
  74. package/src/Literal.ts +6 -5
  75. package/src/agent/AgentClient.ts +53 -1
  76. package/src/expression/ExpressionRef.ts +2 -2
  77. package/src/index.ts +0 -1
  78. package/src/language/Language.ts +55 -231
  79. package/src/model/Ad4mModel.test.ts +1709 -572
  80. package/src/model/Ad4mModel.ts +274 -120
  81. package/src/model/ModelQueryBuilder.ts +234 -87
  82. package/src/model/Subject.ts +6 -6
  83. package/src/model/decorators.ts +51 -22
  84. package/src/model/hydration-batch.ts +205 -0
  85. package/src/model/hydration-batching.test.ts +563 -0
  86. package/src/model/hydration.ts +349 -84
  87. package/src/model/index.ts +4 -1
  88. package/src/model/json-schema.ts +2 -2
  89. package/src/model/query-cache.test.ts +54 -0
  90. package/src/model/query-cache.ts +79 -0
  91. package/src/model/query-common.ts +1 -1
  92. package/src/model/query-sparql-batch.ts +301 -0
  93. package/src/model/query-sparql.test.ts +568 -0
  94. package/src/model/query-sparql.ts +820 -0
  95. package/src/model/{surreal-utils.ts → query-utils.ts} +44 -27
  96. package/src/model/relation-filtering.test.ts +15 -15
  97. package/src/model/sdna.ts +1 -1
  98. package/src/model/shacl-gen.ts +42 -17
  99. package/src/model/subscription-delta.test.ts +207 -0
  100. package/src/model/subscription-pool.ts +211 -0
  101. package/src/model/types.ts +53 -4
  102. package/src/perspectives/PerspectiveClient.test.ts +204 -0
  103. package/src/perspectives/PerspectiveClient.ts +41 -68
  104. package/src/perspectives/PerspectiveProxy.ts +244 -181
  105. package/src/perspectives/PerspectiveResolver.ts +0 -8
  106. package/src/perspectives/WakerSubscriptionManager.ts +8 -9
  107. package/src/runtime/RuntimeResolver.ts +43 -0
  108. package/src/shacl/SHACLFlow.ts +9 -9
  109. package/src/shacl/SHACLShape.ts +39 -39
  110. package/src/utils.ts +6 -6
  111. package/lib/src/model/query-surreal.d.ts +0 -44
  112. package/lib/src/model/query-surreal.js +0 -249
  113. package/src/language/LanguageContext.ts +0 -37
  114. package/src/model/query-surreal.ts +0 -280
  115. package/tsconfig-browser.json +0 -82
@@ -1,21 +1,23 @@
1
1
  /**
2
- * Shared SurrealQL compilation utilities.
2
+ * Shared query compilation utilities.
3
3
  *
4
4
  * These functions are used by both the runtime query builder (`Ad4mModel`) and
5
5
  * the compile-time SHACL generator (`decorators.ts`).
6
+ *
7
+ * All output uses native SPARQL syntax.
6
8
  */
7
9
 
8
10
  import type { WhereCondition, Where, ModelMetadata } from "./types";
9
- import { escapeSurrealString } from "../utils";
11
+ import { escapeQueryString } from "../utils";
10
12
 
11
13
  /**
12
- * Format a JavaScript value for embedding in a SurrealQL expression.
14
+ * Format a JavaScript value for embedding in a query expression.
13
15
  *
14
16
  * - Strings are single-quoted with backslash / quote / newline escaping
15
17
  * - Numbers and booleans are passed through as-is
16
18
  * - Arrays are recursed
17
19
  */
18
- export function formatSurrealValue(value: any): string {
20
+ export function formatQueryValue(value: any): string {
19
21
  if (typeof value === 'string') {
20
22
  // Escape backslashes first, then single quotes and other special characters
21
23
  const escaped = value
@@ -29,38 +31,51 @@ export function formatSurrealValue(value: any): string {
29
31
  } else if (typeof value === 'number' || typeof value === 'boolean') {
30
32
  return String(value);
31
33
  } else if (Array.isArray(value)) {
32
- return `[${value.map(v => formatSurrealValue(v)).join(', ')}]`;
34
+ return `[${value.map(v => formatQueryValue(v)).join(', ')}]`;
33
35
  } else {
34
36
  return String(value);
35
37
  }
36
38
  }
37
39
 
38
40
  /**
39
- * Compile a single Where condition for a property into a SurrealQL
40
- * graph-traversal sub-expression.
41
+ * Compile a single Where condition for a property into a SPARQL triple pattern
42
+ * that can be embedded in a getter's WHERE clause.
41
43
  *
42
- * Operates on the **target node** — generates `count(->link[WHERE ...]) > 0`
43
- * style checks that can be used inside a `[WHERE ...]` filter on nodes.
44
+ * The generated pattern operates on `?target` — e.g.:
45
+ * `?target <pred> <value> .`
46
+ * `FILTER EXISTS { ?target <pred> ?_v0 }`
44
47
  *
45
48
  * @param predicate - The predicate URI for the property
46
49
  * @param condition - The Where condition value
47
50
  * @param opts - Optional settings (e.g. `resolveLanguage`)
48
- * @returns A single SurrealQL condition string
51
+ * @returns A single SPARQL condition string
49
52
  */
50
53
  export function buildWhereCondition(
51
54
  predicate: string,
52
55
  condition: WhereCondition,
53
56
  opts?: { resolveLanguage?: string },
54
57
  ): string {
55
- const escapedPredicate = escapeSurrealString(predicate);
56
- const targetField = opts?.resolveLanguage === 'literal'
57
- ? 'fn::parse_literal(out.uri)'
58
- : 'out.uri';
58
+ const escapedPredicate = escapeQueryString(predicate);
59
+ // For literal-resolved properties, we match against the raw IRI (which is a literal: URI)
60
+ // For language-resolved properties, we match against the plain URI
61
+ // For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>
62
+ // For language-resolved properties, values are plain URIs
63
+ const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
64
+
65
+ function formatValue(v: any): string {
66
+ if (typeof v === 'string') {
67
+ return isLiteral
68
+ ? `<literal:string:${escapeQueryString(v)}>`
69
+ : `<${escapeQueryString(v)}>`;
70
+ }
71
+ // Numbers/booleans — also stored as literal:string: in AD4M
72
+ return `<literal:string:${v}>`;
73
+ }
59
74
 
60
75
  if (Array.isArray(condition)) {
61
- // Array values → IN clause
62
- const formattedValues = (condition as any[]).map(v => formatSurrealValue(v)).join(', ');
63
- return `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} IN [${formattedValues}]]) > 0`;
76
+ // Array values → FILTER IN
77
+ const formattedValues = (condition as any[]).map(formatValue).join(', ');
78
+ return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;
64
79
  } else if (typeof condition === 'object' && condition !== null) {
65
80
  // Operator object
66
81
  const ops = condition as any;
@@ -68,39 +83,41 @@ export function buildWhereCondition(
68
83
 
69
84
  if (ops.not !== undefined) {
70
85
  if (Array.isArray(ops.not)) {
71
- const formattedValues = ops.not.map((v: any) => formatSurrealValue(v)).join(', ');
86
+ const formattedValues = ops.not.map((v: any) => formatValue(v)).join(', ');
87
+ // FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
88
+ // so O(N²) behavior is bounded by the number of values for this property.
72
89
  parts.push(
73
- `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} IN [${formattedValues}]]) = 0`,
90
+ `FILTER NOT EXISTS { ?target <${escapedPredicate}> ?_nval . FILTER(?_nval IN (${formattedValues})) }`,
74
91
  );
75
92
  } else {
93
+ // FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
94
+ // so O(N²) behavior is bounded by the number of values for this property.
76
95
  parts.push(
77
- `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`,
96
+ `FILTER NOT EXISTS { ?target <${escapedPredicate}> ${formatValue(ops.not)} }`,
78
97
  );
79
98
  }
80
99
  }
81
100
 
82
- // Comparison operators — ensure property exists (actual comparison
83
- // may be post-filtered in JS at runtime, but the SurrealQL condition
84
- // is valid for compile-time getter generation too).
101
+ // Comparison operators — ensure property exists
85
102
  const hasComparisonOps =
86
103
  ops.gt !== undefined || ops.gte !== undefined ||
87
104
  ops.lt !== undefined || ops.lte !== undefined ||
88
105
  ops.between !== undefined || ops.contains !== undefined;
89
106
  if (hasComparisonOps) {
90
107
  parts.push(
91
- `count(->link[WHERE predicate = '${escapedPredicate}']) > 0`,
108
+ `FILTER EXISTS { ?target <${escapedPredicate}> ?_cmp }`,
92
109
  );
93
110
  }
94
111
 
95
- return parts.join(' AND ');
112
+ return parts.join(' ');
96
113
  } else {
97
114
  // Simple equality
98
- return `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} = ${formatSurrealValue(condition)}]) > 0`;
115
+ return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
99
116
  }
100
117
  }
101
118
 
102
119
  /**
103
- * Compile a full `Where` clause to an array of SurrealQL condition strings.
120
+ * Compile a full `Where` clause to an array of SPARQL condition strings.
104
121
  *
105
122
  * When `metadata` is provided, property names are resolved to predicates
106
123
  * using the model's property metadata. When `metadata` is `null`, property
@@ -22,7 +22,7 @@ import {
22
22
  SHACLPropertyShape,
23
23
  ConformanceCondition,
24
24
  } from "../shacl/SHACLShape";
25
- import { compileWhereClause } from "./surreal-utils";
25
+ import { compileWhereClause } from "./query-utils";
26
26
 
27
27
  // ============================================================================
28
28
  // Test models
@@ -65,7 +65,7 @@ class ParentWithRelations extends Ad4mModel {
65
65
  unfilteredItems: string[] = [];
66
66
 
67
67
  @HasMany({
68
- getter: "(<-link[WHERE predicate = 'test://custom'].in.uri)",
68
+ getter: "SELECT ?target WHERE { ?target <test://custom> ?source . }",
69
69
  })
70
70
  customItems: string[] = [];
71
71
  }
@@ -93,8 +93,8 @@ describe("buildConformanceFilter()", () => {
93
93
  expect(reqCond!.predicate).toBe("test://name");
94
94
  expect(reqCond!.value).toBeUndefined();
95
95
 
96
- // Getter string should be a SurrealQL expression
97
- expect(result!.getter).toContain("->link[WHERE predicate =");
96
+ // Getter string should be a SPARQL expression
97
+ expect(result!.getter).toContain("SELECT ?target WHERE");
98
98
  expect(result!.getter).toContain("test://has_flagged");
99
99
  expect(result!.getter).toContain("test://type");
100
100
  expect(result!.getter).toContain("test://flagged_type");
@@ -130,7 +130,7 @@ describe("buildConformanceFilter()", () => {
130
130
  @Property({
131
131
  through: "test://computed",
132
132
  required: true,
133
- getter: "(<-link[WHERE predicate = 'test://custom'].in.uri)[0]",
133
+ getter: "SELECT ?target WHERE { ?target <test://custom> ?source . } LIMIT 1",
134
134
  })
135
135
  computed: string = "";
136
136
  }
@@ -148,7 +148,7 @@ describe("buildConformanceFilter()", () => {
148
148
  // ============================================================================
149
149
 
150
150
  describe("SHACL shape getter serialization", () => {
151
- const testGetter = "(->link[WHERE predicate = 'test://pred'].out[WHERE count(->link[WHERE predicate = 'test://type' AND out.uri = 'test://flag']) > 0].uri)";
151
+ const testGetter = "SELECT ?target WHERE { <Base> <test://pred> ?target . ?target <test://type> <test://flag> . }";
152
152
  const testConditions: ConformanceCondition[] = [
153
153
  { type: "flag", predicate: "test://type", value: "test://flag" },
154
154
  { type: "required", predicate: "test://name" },
@@ -170,7 +170,7 @@ describe("SHACL shape getter serialization", () => {
170
170
  // Verify getter link exists
171
171
  const getterLink = links.find(l => l.predicate === "ad4m://getter");
172
172
  expect(getterLink).toBeDefined();
173
- expect(getterLink!.target).toBe(`literal://string:${testGetter}`);
173
+ expect(getterLink!.target).toBe(`literal:string:${testGetter}`);
174
174
 
175
175
  // Verify conditions link exists
176
176
  const conditionsLink = links.find(l => l.predicate === "ad4m://conformanceConditions");
@@ -338,7 +338,7 @@ describe("Ad4mModel.getModelMetadata() relation filtering fields", () => {
338
338
 
339
339
  // Explicit getter provided via decorator (getter-only, no predicate)
340
340
  expect(metadata.relations.customItems.getter).toBe(
341
- "(<-link[WHERE predicate = 'test://custom'].in.uri)"
341
+ "SELECT ?target WHERE { ?target <test://custom> ?source . }"
342
342
  );
343
343
  expect(metadata.relations.customItems.predicate).toBe("");
344
344
 
@@ -388,7 +388,7 @@ describe("Relation decorator validation", () => {
388
388
  @Model({ name: "InvalidGetterTarget" })
389
389
  class _Invalid extends Ad4mModel {
390
390
  @HasMany({
391
- getter: "(<-link.in.uri)",
391
+ getter: "SELECT ?target WHERE { ?target ?p ?source . }",
392
392
  target: () => FlaggedTarget,
393
393
  })
394
394
  items: string[] = [];
@@ -401,7 +401,7 @@ describe("Relation decorator validation", () => {
401
401
  @Model({ name: "InvalidGetterThrough" })
402
402
  class _Invalid extends Ad4mModel {
403
403
  @HasMany({
404
- getter: "(<-link.in.uri)",
404
+ getter: "SELECT ?target WHERE { ?target ?p ?source . }",
405
405
  through: "test://pred",
406
406
  })
407
407
  items: string[] = [];
@@ -414,7 +414,7 @@ describe("Relation decorator validation", () => {
414
414
  @Model({ name: "ValidGetterOnly" })
415
415
  class _Valid extends Ad4mModel {
416
416
  @HasMany({
417
- getter: "(<-link.in.uri)",
417
+ getter: "SELECT ?target WHERE { ?target ?p ?source . }",
418
418
  })
419
419
  items: string[] = [];
420
420
  }
@@ -551,7 +551,7 @@ describe("where clause validation", () => {
551
551
  class _Invalid extends Ad4mModel {
552
552
  @HasMany({
553
553
  where: { status: "active" },
554
- getter: "(<-link.in.uri)",
554
+ getter: "SELECT ?target WHERE { ?target ?p ?source . }",
555
555
  })
556
556
  items: string[] = [];
557
557
  }
@@ -574,7 +574,7 @@ describe("where clause validation", () => {
574
574
  });
575
575
 
576
576
  describe("where clause compilation", () => {
577
- it("should compile where clause to SurrealQL getter", () => {
577
+ it("should compile where clause to SPARQL getter", () => {
578
578
  @Model({ name: "WhereTarget" })
579
579
  class WhereTarget extends Ad4mModel {
580
580
  @Property({ through: "test://status", required: true })
@@ -760,7 +760,7 @@ describe("where clause compilation", () => {
760
760
  // ============================================================================
761
761
 
762
762
  describe("compileWhereClause()", () => {
763
- it("should compile simple equality to SurrealQL condition", () => {
763
+ it("should compile simple equality to SPARQL condition", () => {
764
764
  const conditions = compileWhereClause(
765
765
  { status: "active" },
766
766
  { properties: { status: { name: "status", predicate: "test://status", required: false, readOnly: false } }, relations: {}, className: "Test" }
@@ -776,7 +776,7 @@ describe("compileWhereClause()", () => {
776
776
  { properties: { status: { name: "status", predicate: "test://status", required: false, readOnly: false } }, relations: {}, className: "Test" }
777
777
  );
778
778
  expect(conditions).toHaveLength(1);
779
- expect(conditions[0]).toContain("= 0"); // negation
779
+ expect(conditions[0]).toContain("NOT EXISTS"); // negation
780
780
  expect(conditions[0]).toContain("archived");
781
781
  });
782
782
 
package/src/model/sdna.ts CHANGED
@@ -89,7 +89,7 @@ export function buildSDNA(
89
89
  // Optional properties (required: false) are excluded — they should
90
90
  // remain unset (undefined) until explicitly assigned.
91
91
  const effectiveInitial = initial
92
- ?? (required && writable && !flag && through ? "literal://string:" : undefined);
92
+ ?? (required && writable && !flag && through ? "literal:string:" : undefined);
93
93
 
94
94
  if (effectiveInitial) {
95
95
  constructorActions.push({
@@ -8,8 +8,8 @@
8
8
  */
9
9
  import { SHACLShape } from "../shacl/SHACLShape";
10
10
  import type { SHACLPropertyShape, ConformanceCondition } from "../shacl/SHACLShape";
11
- import { escapeSurrealString } from "../utils";
12
- import { compileWhereClause } from "./surreal-utils";
11
+ import { escapeQueryString } from "../utils";
12
+ import { compileWhereClause } from "./query-utils";
13
13
  import { propertyNameToSetterName } from "./util";
14
14
  import type { PropertyMetadataEntry, RelationMetadataEntry, Ad4mModelLike } from "./decorators";
15
15
 
@@ -163,7 +163,7 @@ export function buildSHACL(
163
163
  // ── Constructor / Destructor entries ────────────────────────────
164
164
  const effectiveInitial = propMeta.initial
165
165
  ?? (propMeta.required && propMeta.writable && !propMeta.flag && propMeta.through
166
- ? "literal://string:" : undefined);
166
+ ? "literal:string:" : undefined);
167
167
 
168
168
  if (effectiveInitial) {
169
169
  constructorActions.push({
@@ -224,7 +224,7 @@ export function buildSHACL(
224
224
  // ── Build Getter (conformance filter) ───────────────────────────
225
225
  // Priority chain:
226
226
  // 1. Explicit getter string → use verbatim
227
- // 2. `where` clause → compile DSL to SurrealQL getter
227
+ // 2. `where` clause → compile DSL to SPARQL getter
228
228
  // 3. target + filter !== false → auto-derive from shape
229
229
  if (relMeta.getter) {
230
230
  relShape.getter = relMeta.getter;
@@ -241,24 +241,49 @@ export function buildSHACL(
241
241
  );
242
242
 
243
243
  if (conditions.length > 0) {
244
- const escapedPredicate = escapeSurrealString(relMeta.predicate);
245
- relShape.getter = `(->link[WHERE predicate = '${escapedPredicate}'].out[WHERE ${conditions.join(' AND ')}].uri)`;
244
+ const escapedPredicate = escapeQueryString(relMeta.predicate);
245
+ relShape.getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;
246
246
  }
247
247
  } catch (e) {
248
248
  // Target metadata may not be available yet
249
249
  }
250
250
  } else if (relMeta.target && relMeta.filter !== false) {
251
- try {
252
- const TargetClass = relMeta.target();
253
- const filter = conformanceFilterFn(relMeta.predicate, TargetClass);
254
- if (filter) {
255
- relShape.getter = filter.getter;
256
- relShape.conformanceConditions = filter.conformanceConditions;
251
+ // Lazy conformance filter: store deferred reference,
252
+ // resolve on first access via a getter on relShape
253
+ const targetThunk = relMeta.target;
254
+ const predicate = relMeta.predicate;
255
+ let resolved = false;
256
+ let cachedGetter: string | undefined;
257
+ let cachedConditions: ConformanceCondition[] | undefined;
258
+
259
+ const resolveFilter = () => {
260
+ if (resolved) return;
261
+ resolved = true;
262
+ try {
263
+ const TargetClass = targetThunk();
264
+ const filter = conformanceFilterFn(predicate, TargetClass);
265
+ if (filter) {
266
+ cachedGetter = filter.getter;
267
+ cachedConditions = filter.conformanceConditions;
268
+ }
269
+ } catch (e) {
270
+ // Target class may not be available yet
257
271
  }
258
- } catch (e) {
259
- // Target class may not be available yet — getter will be
260
- // absent and runtime will fall back to unfiltered get_links
261
- }
272
+ };
273
+
274
+ // Define lazy getters that resolve on first access
275
+ Object.defineProperty(relShape, 'getter', {
276
+ get() { resolveFilter(); return cachedGetter; },
277
+ set(v: string) { resolved = true; cachedGetter = v; },
278
+ enumerable: true,
279
+ configurable: true,
280
+ });
281
+ Object.defineProperty(relShape, 'conformanceConditions', {
282
+ get() { resolveFilter(); return cachedConditions; },
283
+ set(v: ConformanceCondition[]) { resolved = true; cachedConditions = v; },
284
+ enumerable: true,
285
+ configurable: true,
286
+ });
262
287
  }
263
288
 
264
289
  // ── sh:class — target shape reference ───────────────────────────
@@ -278,7 +303,7 @@ export function buildSHACL(
278
303
  }
279
304
 
280
305
  // Always set constructor and destructor actions on the shape, even
281
- // when empty. An empty array serialises to `literal://string:[]`
306
+ // when empty. An empty array serialises to `literal:string:[]`
282
307
  // which the Rust executor parses as a valid (no-op) command list,
283
308
  // avoiding "No SHACL constructor found" errors for models whose
284
309
  // properties are all optional and have no @Flag.
@@ -0,0 +1,207 @@
1
+ /**
2
+ * Tests for the delta fast-path logic used in subscription-pool.ts.
3
+ *
4
+ * The delta optimisation in pooledSubscribe's onResult handler:
5
+ * 1. Checks if new rows are a strict superset of previous rows
6
+ * 2. Extracts added rows (new triples not in prev set)
7
+ * 3. Verifies ALL added rows have source URIs not already in previous results
8
+ * 4. If condition 3 fails (existing source got new links), falls back to full rehydration
9
+ *
10
+ * These tests validate the detection logic in isolation.
11
+ */
12
+
13
+ type Row = { source: string; predicate: string; target: string };
14
+
15
+ /**
16
+ * Replicates the delta-path eligibility check from subscription-pool.ts
17
+ */
18
+ function detectDeltaPath(prevArr: Row[], newArr: Row[]): {
19
+ useDelta: boolean;
20
+ addedRows: Row[];
21
+ reason?: string;
22
+ } {
23
+ if (newArr.length <= prevArr.length) {
24
+ return { useDelta: false, addedRows: [], reason: 'no growth' };
25
+ }
26
+ if (newArr.length - prevArr.length > 5) {
27
+ return { useDelta: false, addedRows: [], reason: 'delta too large' };
28
+ }
29
+
30
+ const prevSources = new Set(prevArr.map(r => `${r.source}|${r.predicate}|${r.target}`));
31
+ const addedRows = newArr.filter(r => !prevSources.has(`${r.source}|${r.predicate}|${r.target}`));
32
+
33
+ const newSources = new Set(newArr.map(r => `${r.source}|${r.predicate}|${r.target}`));
34
+ const removedRows = prevArr.filter(r => !newSources.has(`${r.source}|${r.predicate}|${r.target}`));
35
+
36
+ if (removedRows.length > 0) {
37
+ return { useDelta: false, addedRows, reason: 'rows removed' };
38
+ }
39
+
40
+ // Key check: all added rows must have NEW source URIs
41
+ const prevSourceIds = new Set(prevArr.map(r => r.source));
42
+ const allNewSources = addedRows.every(r => !prevSourceIds.has(r.source));
43
+
44
+ if (!allNewSources) {
45
+ return { useDelta: false, addedRows, reason: 'existing source got new links' };
46
+ }
47
+
48
+ return { useDelta: true, addedRows };
49
+ }
50
+
51
+ describe('delta fast-path detection', () => {
52
+ const prev: Row[] = [
53
+ { source: 'a', predicate: 'p1', target: 't1' },
54
+ { source: 'a', predicate: 'p2', target: 't2' },
55
+ { source: 'b', predicate: 'p1', target: 't3' },
56
+ ];
57
+
58
+ it('appends genuinely new items via delta path', () => {
59
+ const next: Row[] = [
60
+ ...prev,
61
+ { source: 'c', predicate: 'p1', target: 't4' },
62
+ ];
63
+ const result = detectDeltaPath(prev, next);
64
+ expect(result.useDelta).toBe(true);
65
+ expect(result.addedRows).toHaveLength(1);
66
+ expect(result.addedRows[0].source).toBe('c');
67
+ });
68
+
69
+ it('falls back when existing source gets new links', () => {
70
+ const next: Row[] = [
71
+ ...prev,
72
+ { source: 'a', predicate: 'p3', target: 't5' }, // source 'a' already exists
73
+ ];
74
+ const result = detectDeltaPath(prev, next);
75
+ expect(result.useDelta).toBe(false);
76
+ expect(result.reason).toBe('existing source got new links');
77
+ });
78
+
79
+ it('falls back when rows are removed (even if new ones added)', () => {
80
+ const next: Row[] = [
81
+ { source: 'a', predicate: 'p1', target: 't1' },
82
+ { source: 'a', predicate: 'p2', target: 't2' },
83
+ // source 'b' row removed, two new sources added so length grows
84
+ { source: 'c', predicate: 'p1', target: 't4' },
85
+ { source: 'd', predicate: 'p1', target: 't5' },
86
+ ];
87
+ const result = detectDeltaPath(prev, next);
88
+ expect(result.useDelta).toBe(false);
89
+ expect(result.reason).toBe('rows removed');
90
+ });
91
+
92
+ it('falls back when delta is too large (>5 new rows)', () => {
93
+ const next: Row[] = [
94
+ ...prev,
95
+ ...Array.from({ length: 6 }, (_, i) => ({
96
+ source: `new${i}`, predicate: 'p1', target: `t${10 + i}`,
97
+ })),
98
+ ];
99
+ const result = detectDeltaPath(prev, next);
100
+ expect(result.useDelta).toBe(false);
101
+ expect(result.reason).toBe('delta too large');
102
+ });
103
+
104
+ it('falls back when no growth', () => {
105
+ const result = detectDeltaPath(prev, prev);
106
+ expect(result.useDelta).toBe(false);
107
+ expect(result.reason).toBe('no growth');
108
+ });
109
+
110
+ it('handles multiple new sources in one delta', () => {
111
+ const next: Row[] = [
112
+ ...prev,
113
+ { source: 'c', predicate: 'p1', target: 't4' },
114
+ { source: 'd', predicate: 'p1', target: 't5' },
115
+ ];
116
+ const result = detectDeltaPath(prev, next);
117
+ expect(result.useDelta).toBe(true);
118
+ expect(result.addedRows).toHaveLength(2);
119
+ });
120
+
121
+ // ── Test #8: Rapid successive additions ──
122
+ it('handles 10 items added in quick succession without duplicates', () => {
123
+ let current = [...prev];
124
+ for (let i = 0; i < 10; i++) {
125
+ const next = [...current, { source: `rapid-${i}`, predicate: 'p1', target: `t-rapid-${i}` }];
126
+ const result = detectDeltaPath(current, next);
127
+ // Each individual addition should be eligible for delta
128
+ expect(result.useDelta).toBe(true);
129
+ expect(result.addedRows).toHaveLength(1);
130
+ expect(result.addedRows[0].source).toBe(`rapid-${i}`);
131
+ current = next;
132
+ }
133
+ });
134
+
135
+ // ── Test #9: Addition + removal in same batch ──
136
+ it('falls back when one item added and another removed simultaneously', () => {
137
+ const next: Row[] = [
138
+ { source: 'a', predicate: 'p1', target: 't1' },
139
+ { source: 'a', predicate: 'p2', target: 't2' },
140
+ // source 'b' removed, source 'c' added
141
+ { source: 'c', predicate: 'p1', target: 't4' },
142
+ { source: 'd', predicate: 'p1', target: 't5' },
143
+ ];
144
+ const result = detectDeltaPath(prev, next);
145
+ expect(result.useDelta).toBe(false);
146
+ expect(result.reason).toBe('rows removed');
147
+ });
148
+
149
+ // ── Test #10: Delta with nested relations (detection only) ──
150
+ it('delta path detects new items correctly even when sources have complex URIs', () => {
151
+ const next: Row[] = [
152
+ ...prev,
153
+ { source: 'flux://post/123/comment/456', predicate: 'flux://belongs_to', target: 'flux://post/123' },
154
+ ];
155
+ const result = detectDeltaPath(prev, next);
156
+ expect(result.useDelta).toBe(true);
157
+ expect(result.addedRows).toHaveLength(1);
158
+ expect(result.addedRows[0].source).toBe('flux://post/123/comment/456');
159
+ });
160
+
161
+ // ── Test #11: Empty previous result + new items ──
162
+ it('handles empty previous array with new items arriving', () => {
163
+ const empty: Row[] = [];
164
+ const next: Row[] = [
165
+ { source: 'x', predicate: 'p1', target: 't1' },
166
+ ];
167
+ const result = detectDeltaPath(empty, next);
168
+ expect(result.useDelta).toBe(true);
169
+ expect(result.addedRows).toHaveLength(1);
170
+ });
171
+
172
+ it('handles empty previous with no new items', () => {
173
+ const result = detectDeltaPath([], []);
174
+ expect(result.useDelta).toBe(false);
175
+ expect(result.reason).toBe('no growth');
176
+ });
177
+
178
+ // ── Test #12: Source URI with special characters ──
179
+ it('handles URIs with encoded characters, fragments, and query params', () => {
180
+ const specialPrev: Row[] = [
181
+ { source: 'flux://item%20one', predicate: 'p1', target: 't1' },
182
+ { source: 'flux://item#section', predicate: 'p2', target: 't2' },
183
+ { source: 'flux://item?key=val&foo=bar', predicate: 'p3', target: 't3' },
184
+ ];
185
+ const specialNext: Row[] = [
186
+ ...specialPrev,
187
+ { source: 'flux://new%C3%A9item', predicate: 'p1', target: 't4' },
188
+ ];
189
+ const result = detectDeltaPath(specialPrev, specialNext);
190
+ expect(result.useDelta).toBe(true);
191
+ expect(result.addedRows).toHaveLength(1);
192
+ expect(result.addedRows[0].source).toBe('flux://new%C3%A9item');
193
+ });
194
+
195
+ it('correctly identifies existing source with special chars getting new links', () => {
196
+ const specialPrev: Row[] = [
197
+ { source: 'flux://item#section', predicate: 'p1', target: 't1' },
198
+ ];
199
+ const specialNext: Row[] = [
200
+ ...specialPrev,
201
+ { source: 'flux://item#section', predicate: 'p2', target: 't2' },
202
+ ];
203
+ const result = detectDeltaPath(specialPrev, specialNext);
204
+ expect(result.useDelta).toBe(false);
205
+ expect(result.reason).toBe('existing source got new links');
206
+ });
207
+ });