@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
package/lib/index.cjs CHANGED
@@ -1345,6 +1345,41 @@ class SHACLShape {
1345
1345
  target: `literal:string:${JSON.stringify(prop.in)}`
1346
1346
  });
1347
1347
  }
1348
+ if (prop.relationKind) {
1349
+ links.push({
1350
+ source: propShapeId,
1351
+ predicate: "ad4m://relationKind",
1352
+ target: `literal:string:${prop.relationKind}`
1353
+ });
1354
+ }
1355
+ if (prop.targetClassName) {
1356
+ links.push({
1357
+ source: propShapeId,
1358
+ predicate: "ad4m://targetClassName",
1359
+ target: `literal:string:${prop.targetClassName}`
1360
+ });
1361
+ }
1362
+ if (prop.whereFilter !== undefined && prop.whereFilter !== null) {
1363
+ links.push({
1364
+ source: propShapeId,
1365
+ predicate: "ad4m://whereFilter",
1366
+ target: `literal:string:${JSON.stringify(prop.whereFilter)}`
1367
+ });
1368
+ }
1369
+ if (prop.wherePredicates && Object.keys(prop.wherePredicates).length > 0) {
1370
+ links.push({
1371
+ source: propShapeId,
1372
+ predicate: "ad4m://wherePredicates",
1373
+ target: `literal:string:${JSON.stringify(prop.wherePredicates)}`
1374
+ });
1375
+ }
1376
+ if (prop.filter !== undefined) {
1377
+ links.push({
1378
+ source: propShapeId,
1379
+ predicate: "ad4m://filter",
1380
+ target: `literal:${prop.filter}`
1381
+ });
1382
+ }
1348
1383
  }
1349
1384
  return links;
1350
1385
  }
@@ -1526,6 +1561,44 @@ class SHACLShape {
1526
1561
  // Ignore parse errors
1527
1562
  }
1528
1563
  }
1564
+ const relationKindLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://relationKind");
1565
+ if (relationKindLink) {
1566
+ const val = relationKindLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1567
+ if (val === 'hasMany' || val === 'hasOne' || val === 'belongsToOne' || val === 'belongsToMany') {
1568
+ prop.relationKind = val;
1569
+ }
1570
+ }
1571
+ const targetClassNameLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://targetClassName");
1572
+ if (targetClassNameLink) {
1573
+ prop.targetClassName = targetClassNameLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1574
+ }
1575
+ const whereFilterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://whereFilter");
1576
+ if (whereFilterLink) {
1577
+ try {
1578
+ const jsonStr = whereFilterLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1579
+ prop.whereFilter = JSON.parse(jsonStr);
1580
+ }
1581
+ catch (e) {
1582
+ // Ignore parse errors
1583
+ }
1584
+ }
1585
+ const wherePredicatesLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://wherePredicates");
1586
+ if (wherePredicatesLink) {
1587
+ try {
1588
+ const jsonStr = wherePredicatesLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1589
+ prop.wherePredicates = JSON.parse(jsonStr);
1590
+ }
1591
+ catch (e) {
1592
+ // Ignore parse errors
1593
+ }
1594
+ }
1595
+ const filterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://filter");
1596
+ if (filterLink) {
1597
+ let val = filterLink.target.replace(/^literal:\/\/|^literal:/, '');
1598
+ if (val.startsWith('boolean:'))
1599
+ val = val.substring(8);
1600
+ prop.filter = val === 'true';
1601
+ }
1529
1602
  shape.addProperty(prop);
1530
1603
  }
1531
1604
  return shape;
@@ -1562,6 +1635,11 @@ class SHACLShape {
1562
1635
  conformance_conditions: p.conformanceConditions,
1563
1636
  class: p.class,
1564
1637
  in: p.in,
1638
+ relation_kind: p.relationKind,
1639
+ target_class_name: p.targetClassName,
1640
+ where_filter: p.whereFilter,
1641
+ where_predicates: p.wherePredicates,
1642
+ filter: p.filter,
1565
1643
  })),
1566
1644
  constructor_actions: this.constructor_actions,
1567
1645
  destructor_actions: this.destructor_actions,
@@ -1596,6 +1674,11 @@ class SHACLShape {
1596
1674
  conformanceConditions: p.conformance_conditions,
1597
1675
  class: p.class,
1598
1676
  in: p.in,
1677
+ relationKind: p.relation_kind,
1678
+ targetClassName: p.target_class_name,
1679
+ whereFilter: p.where_filter,
1680
+ wherePredicates: p.where_predicates,
1681
+ filter: p.filter,
1599
1682
  });
1600
1683
  }
1601
1684
  if (json.constructor_actions) {
@@ -1613,247 +1696,6 @@ class SHACLShape {
1613
1696
  }
1614
1697
  }
1615
1698
 
1616
- function formatList(list) {
1617
- if (!list?.length) {
1618
- return "";
1619
- }
1620
- if (list.length === 1) {
1621
- return list.toString();
1622
- }
1623
- if (list.length === 2) {
1624
- return list.join(' and ');
1625
- }
1626
- return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);
1627
- }
1628
- function capSentence(cap) {
1629
- const can = cap.can.includes("*") ? ["READ", "WRITE", "UPDATE"] : cap.can;
1630
- const domain = cap.with.domain === "*" ? "" : cap.with.domain;
1631
- const pointers = cap.with.pointers.includes("*")
1632
- ? ["all AD4M data"]
1633
- : cap.with.pointers;
1634
- return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
1635
- }
1636
- /**
1637
- * Escapes a string value for safe use in query strings.
1638
- *
1639
- * @description
1640
- * Prevents SQL injection by properly escaping special characters in string values
1641
- * that will be interpolated into query strings. This handles the most common
1642
- * special characters that could break SQL queries or enable injection attacks.
1643
- *
1644
- * Single quotes, backslashes, and other special characters are escaped using
1645
- * backslash notation, which is the standard escaping mechanism for query.
1646
- *
1647
- * @param value - The string value to escape
1648
- * @returns The escaped string safe for query interpolation (without surrounding quotes)
1649
- *
1650
- * @example
1651
- * ```typescript
1652
- * const userInput = "user's input with 'quotes'";
1653
- * const escaped = escapeQueryString(userInput);
1654
- * const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
1655
- * // Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''
1656
- * ```
1657
- */
1658
- function escapeQueryString(value) {
1659
- return value
1660
- .replace(/\\/g, '\\\\') // Backslash -> \\
1661
- .replace(/'/g, "\\'") // Single quote -> \'
1662
- .replace(/"/g, '\\"') // Double quote -> \"
1663
- .replace(/\n/g, '\\n') // Newline -> \n
1664
- .replace(/\r/g, '\\r') // Carriage return -> \r
1665
- .replace(/\t/g, '\\t'); // Tab -> \t
1666
- }
1667
-
1668
- /**
1669
- * Shared query compilation utilities.
1670
- *
1671
- * These functions are used by both the runtime query builder (`Ad4mModel`) and
1672
- * the compile-time SHACL generator (`decorators.ts`).
1673
- *
1674
- * All output uses native SPARQL syntax.
1675
- */
1676
- /**
1677
- * Format a JavaScript value for embedding in a query expression.
1678
- *
1679
- * - Strings are single-quoted with backslash / quote / newline escaping
1680
- * - Numbers and booleans are passed through as-is
1681
- * - Arrays are recursed
1682
- */
1683
- function formatQueryValue(value) {
1684
- if (typeof value === 'string') {
1685
- // Escape backslashes first, then single quotes and other special characters
1686
- const escaped = value
1687
- .replace(/\\/g, '\\\\') // Backslash -> \\
1688
- .replace(/'/g, "\\'") // Single quote -> \'
1689
- .replace(/"/g, '\\"') // Double quote -> \"
1690
- .replace(/\n/g, '\\n') // Newline -> \n
1691
- .replace(/\r/g, '\\r') // Carriage return -> \r
1692
- .replace(/\t/g, '\\t'); // Tab -> \t
1693
- return `'${escaped}'`;
1694
- }
1695
- else if (typeof value === 'number' || typeof value === 'boolean') {
1696
- return String(value);
1697
- }
1698
- else if (Array.isArray(value)) {
1699
- return `[${value.map(v => formatQueryValue(v)).join(', ')}]`;
1700
- }
1701
- else {
1702
- return String(value);
1703
- }
1704
- }
1705
- /**
1706
- * Compile a single Where condition for a property into a SPARQL triple pattern
1707
- * that can be embedded in a getter's WHERE clause.
1708
- *
1709
- * The generated pattern operates on `?target` — e.g.:
1710
- * `?target <pred> <value> .`
1711
- * `FILTER EXISTS { ?target <pred> ?_v0 }`
1712
- *
1713
- * @param predicate - The predicate URI for the property
1714
- * @param condition - The Where condition value
1715
- * @param opts - Optional settings (e.g. `resolveLanguage`)
1716
- * @returns A single SPARQL condition string
1717
- */
1718
- function buildWhereCondition(predicate, condition, opts) {
1719
- const escapedPredicate = escapeQueryString(predicate);
1720
- // For literal-resolved properties, we match against the raw IRI (which is a literal: URI)
1721
- // For language-resolved properties, we match against the plain URI
1722
- // For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>
1723
- // For language-resolved properties, values are plain URIs
1724
- const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
1725
- const varSuffix = opts?.varIndex ?? 0;
1726
- function formatValue(v) {
1727
- if (typeof v === 'string') {
1728
- return isLiteral
1729
- ? `<literal:string:${escapeQueryString(v)}>`
1730
- : `<${escapeQueryString(v)}>`;
1731
- }
1732
- // Numbers/booleans — also stored as literal:string: in AD4M
1733
- return `<literal:string:${v}>`;
1734
- }
1735
- /**
1736
- * For literal properties, generate a FILTER-based match that handles both
1737
- * the raw value and the literal-encoded value. This mirrors the Rust
1738
- * `build_projection_where_patterns` approach which uses:
1739
- * FILTER(STR(?var) = "value" || STR(?var) = "literal:string:encodedValue")
1740
- * This is more robust than exact IRI matching because it handles edge cases
1741
- * where the stored format might vary.
1742
- */
1743
- function formatLiteralFilter(varName, v) {
1744
- const raw = escapeQueryString(String(v));
1745
- const encoded = encodeURIComponent(String(v))
1746
- .replace(/!/g, '%21')
1747
- .replace(/'/g, '%27')
1748
- .replace(/\(/g, '%28')
1749
- .replace(/\)/g, '%29')
1750
- .replace(/\*/g, '%2A');
1751
- if (typeof v === 'string') {
1752
- return `FILTER(STR(${varName}) = "${raw}" || STR(${varName}) = "literal:string:${encoded}")`;
1753
- }
1754
- else if (typeof v === 'number') {
1755
- return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:number:${v}")`;
1756
- }
1757
- else if (typeof v === 'boolean') {
1758
- return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:boolean:${v}")`;
1759
- }
1760
- return `FILTER(STR(${varName}) = "${raw}")`;
1761
- }
1762
- if (Array.isArray(condition)) {
1763
- // Array values → FILTER IN
1764
- if (isLiteral) {
1765
- const varName = `?_wc${varSuffix}`;
1766
- const inValues = condition.flatMap(v => {
1767
- const raw = escapeQueryString(String(v));
1768
- const encoded = encodeURIComponent(String(v))
1769
- .replace(/!/g, '%21').replace(/'/g, '%27')
1770
- .replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
1771
- return [`"${raw}"`, `"literal:string:${encoded}"`];
1772
- }).join(', ');
1773
- return `?target <${escapedPredicate}> ${varName} . FILTER(STR(${varName}) IN (${inValues}))`;
1774
- }
1775
- const formattedValues = condition.map(formatValue).join(', ');
1776
- return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;
1777
- }
1778
- else if (typeof condition === 'object' && condition !== null) {
1779
- // Operator object
1780
- const ops = condition;
1781
- const parts = [];
1782
- if (ops.not !== undefined) {
1783
- if (Array.isArray(ops.not)) {
1784
- const formattedValues = ops.not.map((v) => formatValue(v)).join(', ');
1785
- // FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
1786
- // so O(N²) behavior is bounded by the number of values for this property.
1787
- parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ?_nval . FILTER(?_nval IN (${formattedValues})) }`);
1788
- }
1789
- else {
1790
- // FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
1791
- // so O(N²) behavior is bounded by the number of values for this property.
1792
- parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ${formatValue(ops.not)} }`);
1793
- }
1794
- }
1795
- // Comparison operators — ensure property exists
1796
- const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
1797
- ops.lt !== undefined || ops.lte !== undefined ||
1798
- ops.between !== undefined || ops.contains !== undefined;
1799
- if (hasComparisonOps) {
1800
- parts.push(`FILTER EXISTS { ?target <${escapedPredicate}> ?_cmp }`);
1801
- }
1802
- return parts.join(' ');
1803
- }
1804
- else {
1805
- // Simple equality
1806
- if (isLiteral) {
1807
- // Use FILTER matching (mirrors Rust build_projection_where_patterns)
1808
- // to handle both raw values and literal-encoded IRIs robustly.
1809
- const varName = `?_wc${varSuffix}`;
1810
- return `?target <${escapedPredicate}> ${varName} . ${formatLiteralFilter(varName, condition)}`;
1811
- }
1812
- return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
1813
- }
1814
- }
1815
- /**
1816
- * Compile a full `Where` clause to an array of SPARQL condition strings.
1817
- *
1818
- * When `metadata` is provided, property names are resolved to predicates
1819
- * using the model's property metadata. When `metadata` is `null`, property
1820
- * names are treated as raw predicate URIs.
1821
- *
1822
- * Only handles **regular properties** — special fields (`id`, `author`,
1823
- * `timestamp`) and relation fields are skipped (they are only relevant at
1824
- * runtime query time, not for compile-time getter generation).
1825
- */
1826
- function compileWhereClause(where, metadata) {
1827
- const conditions = [];
1828
- for (const [propertyName, condition] of Object.entries(where)) {
1829
- // Skip special fields that don't apply at compile time
1830
- if (['id', 'author', 'timestamp'].includes(propertyName))
1831
- continue;
1832
- let predicate;
1833
- let resolveLanguage;
1834
- if (metadata) {
1835
- const propMeta = metadata.properties[propertyName];
1836
- if (propMeta) {
1837
- predicate = propMeta.predicate;
1838
- resolveLanguage = propMeta.resolveLanguage;
1839
- }
1840
- else {
1841
- // Property not found in metadata — treat name as raw predicate URI
1842
- predicate = propertyName;
1843
- }
1844
- }
1845
- else {
1846
- // No metadata — treat name as raw predicate URI
1847
- predicate = propertyName;
1848
- }
1849
- const cond = buildWhereCondition(predicate, condition, { resolveLanguage, varIndex: conditions.length });
1850
- if (cond) {
1851
- conditions.push(cond);
1852
- }
1853
- }
1854
- return conditions;
1855
- }
1856
-
1857
1699
  /**
1858
1700
  * SHACL shape generation for AD4M model classes.
1859
1701
  *
@@ -1877,7 +1719,6 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
1877
1719
  const obj = target.prototype;
1878
1720
  // ── Determine namespace from first property or relation ─────────────
1879
1721
  let namespace = "ad4m://";
1880
- const relations = Object.fromEntries(Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));
1881
1722
  // Try properties first
1882
1723
  if (Object.keys(properties).length > 0) {
1883
1724
  const firstProp = properties[Object.keys(properties)[0]];
@@ -1889,8 +1730,8 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
1889
1730
  }
1890
1731
  }
1891
1732
  // Fall back to relations if no properties
1892
- else if (Object.keys(relations).length > 0) {
1893
- const firstRel = relations[Object.keys(relations)[0]];
1733
+ else if (Object.keys(allRelationsMeta).length > 0) {
1734
+ const firstRel = allRelationsMeta[Object.keys(allRelationsMeta)[0]];
1894
1735
  if (firstRel.predicate) {
1895
1736
  const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
1896
1737
  if (match) {
@@ -1967,6 +1808,12 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
1967
1808
  if (propMeta.resolveLanguage) {
1968
1809
  propShape.resolveLanguage = propMeta.resolveLanguage;
1969
1810
  }
1811
+ // Explicit getter SPARQL — the executor evaluates this when
1812
+ // hydrating the property, in addition to (or instead of)
1813
+ // reading raw links via `propMeta.through`.
1814
+ if (propMeta.getter) {
1815
+ propShape.getter = propMeta.getter;
1816
+ }
1970
1817
  // ── Setter actions ──────────────────────────────────────────────
1971
1818
  if (propMeta.prologSetter) {
1972
1819
  console.warn(`[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
@@ -2005,63 +1852,82 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
2005
1852
  shape.addProperty(propShape);
2006
1853
  }
2007
1854
  // ── Convert relations to SHACL property shapes ─────────────────────
2008
- for (const relName in relations) {
2009
- const relMeta = relations[relName];
2010
- if (!relMeta.predicate)
1855
+ for (const relName in allRelationsMeta) {
1856
+ const relMeta = allRelationsMeta[relName];
1857
+ // Getter-only relations (no `through`) have no real link predicate
1858
+ // but still need a SHACL property entry so the executor can find
1859
+ // the getter expression. Synthesize a deterministic IRI so the
1860
+ // SHACL graph is well-formed; the predicate is never used to match
1861
+ // links because the getter is the sole source of values. Use
1862
+ // slash separators so the result is a valid IRI (colons in the
1863
+ // authority confuse strict SPARQL IRI parsers).
1864
+ if (!relMeta.predicate && !relMeta.getter)
2011
1865
  continue;
1866
+ const synthesizedPath = relMeta.predicate
1867
+ || `ad4m://getter/${subjectName}/${relName}`;
2012
1868
  const relShape = {
2013
1869
  name: relName,
2014
- path: relMeta.predicate,
1870
+ path: synthesizedPath,
2015
1871
  };
2016
1872
  // Relations typically contain IRIs
2017
1873
  relShape.nodeKind = 'IRI';
1874
+ // Encode relation kind so the executor can derive direction and
1875
+ // scalar-vs-collection rendering without consulting the JS class.
1876
+ relShape.relationKind = relMeta.kind;
1877
+ // Scalar relations cap at 1.
1878
+ if (relMeta.kind === 'hasOne' || relMeta.kind === 'belongsToOne') {
1879
+ relShape.maxCount = 1;
1880
+ }
1881
+ else if (relMeta.maxCount !== undefined) {
1882
+ relShape.maxCount = relMeta.maxCount;
1883
+ }
1884
+ // Encode opt-out of type filtering (default true; only emit when false).
1885
+ if (relMeta.filter === false) {
1886
+ relShape.filter = false;
1887
+ }
2018
1888
  // AD4M-specific metadata
2019
1889
  if (relMeta.local !== undefined) {
2020
1890
  relShape.local = relMeta.local;
2021
1891
  }
2022
- // Adder action
2023
- relShape.adder = [{
2024
- action: "addLink",
2025
- source: "this",
2026
- predicate: relMeta.predicate,
2027
- target: "value",
2028
- ...(relMeta.local && { local: true })
2029
- }];
2030
- // Remover action
2031
- relShape.remover = [{
2032
- action: "removeLink",
2033
- source: "this",
2034
- predicate: relMeta.predicate,
2035
- target: "value",
2036
- ...(relMeta.local && { local: true })
2037
- }];
1892
+ // Adder / Remover actions — only meaningful for relations backed
1893
+ // by a real link predicate. Getter-only relations are read-only.
1894
+ if (relMeta.predicate) {
1895
+ relShape.adder = [{
1896
+ action: "addLink",
1897
+ source: "this",
1898
+ predicate: relMeta.predicate,
1899
+ target: "value",
1900
+ ...(relMeta.local && { local: true })
1901
+ }];
1902
+ relShape.remover = [{
1903
+ action: "removeLink",
1904
+ source: "this",
1905
+ predicate: relMeta.predicate,
1906
+ target: "value",
1907
+ ...(relMeta.local && { local: true })
1908
+ }];
1909
+ }
2038
1910
  // ── Build Getter (conformance filter) ───────────────────────────
2039
1911
  // Priority chain:
2040
1912
  // 1. Explicit getter string → use verbatim
2041
- // 2. `where` clause → compile DSL to SPARQL getter
2042
- // 3. target + filter !== false → auto-derive from shape
1913
+ // 2. target + filter !== false → auto-derive conformance getter
1914
+ // from the shape. Where-clause filtering is applied as a
1915
+ // post-getter pass via `whereFilter` / `wherePredicates`, which
1916
+ // use `parse_literal_value` and so transparently handle
1917
+ // `literal:json:` envelopes that simple FILTER(STR(?x) = ...)
1918
+ // comparisons can't.
2043
1919
  if (relMeta.getter) {
2044
1920
  relShape.getter = relMeta.getter;
2045
1921
  }
2046
- else if (relMeta.where) {
2047
- try {
2048
- const TargetClass = relMeta.target?.();
2049
- const targetMetadata = TargetClass
2050
- ? TargetClass.getModelMetadata?.() ?? null
2051
- : null;
2052
- const conditions = compileWhereClause(relMeta.where, targetMetadata);
2053
- if (conditions.length > 0) {
2054
- const escapedPredicate = escapeQueryString(relMeta.predicate);
2055
- relShape.getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;
2056
- }
2057
- }
2058
- catch (e) {
2059
- // Target metadata may not be available yet
2060
- }
2061
- }
2062
- else if (relMeta.target && relMeta.filter !== false) {
1922
+ else if (relMeta.target
1923
+ && relMeta.filter !== false
1924
+ && relMeta.kind !== 'belongsToOne'
1925
+ && relMeta.kind !== 'belongsToMany') {
2063
1926
  // Lazy conformance filter: store deferred reference,
2064
- // resolve on first access via a getter on relShape
1927
+ // resolve on first access via a getter on relShape.
1928
+ // Skipped for reverse relations (belongsTo*) because the
1929
+ // auto-derived getter assumes forward direction; the executor's
1930
+ // `resolve_reverse_relations` already populates these correctly.
2065
1931
  const targetThunk = relMeta.target;
2066
1932
  const predicate = relMeta.predicate;
2067
1933
  let resolved = false;
@@ -2098,6 +1964,8 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
2098
1964
  });
2099
1965
  }
2100
1966
  // ── sh:class — target shape reference ───────────────────────────
1967
+ // Also emit ad4m:targetClassName so the executor can look up the
1968
+ // target class shape through its in-memory cache by bare name.
2101
1969
  if (relMeta.target) {
2102
1970
  try {
2103
1971
  const TargetClass = relMeta.target();
@@ -2105,9 +1973,54 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
2105
1973
  if (targetSHACL?.shape?.nodeShapeUri) {
2106
1974
  relShape.class = targetSHACL.shape.nodeShapeUri;
2107
1975
  }
1976
+ if (targetSHACL?.name) {
1977
+ relShape.targetClassName = targetSHACL.name;
1978
+ }
1979
+ else {
1980
+ const targetProto = TargetClass.prototype;
1981
+ if (targetProto?.className) {
1982
+ relShape.targetClassName = targetProto.className;
1983
+ }
1984
+ }
1985
+ }
1986
+ catch (e) {
1987
+ // Target class resolution failed (typically a circular
1988
+ // decorator dependency). Since the executor no longer
1989
+ // receives target metadata over the wire, dropping the
1990
+ // reference here would turn a transient build-time issue
1991
+ // into a permanent broken-include at query time. Log
1992
+ // loudly so the failure is discoverable.
1993
+ console.warn(`[shacl-gen] Failed to resolve target class for relation `
1994
+ + `"${subjectName}.${relName}": ${e instanceof Error ? e.message : String(e)}`);
1995
+ }
1996
+ }
1997
+ // ── Where-clause metadata for post-getter filtering ─────────────
1998
+ // The executor uses these to apply where conditions against the
1999
+ // target class without needing the target's ModelMetadata at query time.
2000
+ if (relMeta.where) {
2001
+ relShape.whereFilter = relMeta.where;
2002
+ try {
2003
+ const TargetClass = relMeta.target?.();
2004
+ const targetMetadata = TargetClass
2005
+ ? TargetClass.getModelMetadata?.() ?? null
2006
+ : null;
2007
+ if (targetMetadata?.properties) {
2008
+ const predicates = {};
2009
+ for (const propName of Object.keys(relMeta.where)) {
2010
+ if (['id', 'author', 'timestamp'].includes(propName))
2011
+ continue;
2012
+ const propMeta = targetMetadata.properties[propName];
2013
+ if (propMeta?.predicate) {
2014
+ predicates[propName] = propMeta.predicate;
2015
+ }
2016
+ }
2017
+ if (Object.keys(predicates).length > 0) {
2018
+ relShape.wherePredicates = predicates;
2019
+ }
2020
+ }
2108
2021
  }
2109
2022
  catch (e) {
2110
- // Target class may not be available yet
2023
+ // Target metadata may not be available yet
2111
2024
  }
2112
2025
  }
2113
2026
  shape.addProperty(relShape);
@@ -2125,6 +2038,58 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
2125
2038
  };
2126
2039
  }
2127
2040
 
2041
+ function formatList(list) {
2042
+ if (!list?.length) {
2043
+ return "";
2044
+ }
2045
+ if (list.length === 1) {
2046
+ return list.toString();
2047
+ }
2048
+ if (list.length === 2) {
2049
+ return list.join(' and ');
2050
+ }
2051
+ return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);
2052
+ }
2053
+ function capSentence(cap) {
2054
+ const can = cap.can.includes("*") ? ["READ", "WRITE", "UPDATE"] : cap.can;
2055
+ const domain = cap.with.domain === "*" ? "" : cap.with.domain;
2056
+ const pointers = cap.with.pointers.includes("*")
2057
+ ? ["all AD4M data"]
2058
+ : cap.with.pointers;
2059
+ return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
2060
+ }
2061
+ /**
2062
+ * Escapes a string value for safe use in query strings.
2063
+ *
2064
+ * @description
2065
+ * Prevents SQL injection by properly escaping special characters in string values
2066
+ * that will be interpolated into query strings. This handles the most common
2067
+ * special characters that could break SQL queries or enable injection attacks.
2068
+ *
2069
+ * Single quotes, backslashes, and other special characters are escaped using
2070
+ * backslash notation, which is the standard escaping mechanism for query.
2071
+ *
2072
+ * @param value - The string value to escape
2073
+ * @returns The escaped string safe for query interpolation (without surrounding quotes)
2074
+ *
2075
+ * @example
2076
+ * ```typescript
2077
+ * const userInput = "user's input with 'quotes'";
2078
+ * const escaped = escapeQueryString(userInput);
2079
+ * const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
2080
+ * // Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''
2081
+ * ```
2082
+ */
2083
+ function escapeQueryString(value) {
2084
+ return value
2085
+ .replace(/\\/g, '\\\\') // Backslash -> \\
2086
+ .replace(/'/g, "\\'") // Single quote -> \'
2087
+ .replace(/"/g, '\\"') // Double quote -> \"
2088
+ .replace(/\n/g, '\\n') // Newline -> \n
2089
+ .replace(/\r/g, '\\r') // Carriage return -> \r
2090
+ .replace(/\t/g, '\\t'); // Tab -> \t
2091
+ }
2092
+
2128
2093
  /** Registry of property metadata keyed by constructor → { propName → metadata } */
2129
2094
  const propertyRegistry = new WeakMap();
2130
2095
  /** Registry of relation metadata keyed by constructor → { propName → metadata } */
@@ -3741,13 +3706,16 @@ class PerspectiveProxy {
3741
3706
  /**
3742
3707
  * Execute a model query — the executor-side replacement for SPARQL query building + JS hydration.
3743
3708
  *
3709
+ * The executor resolves the model's shape from the perspective's SHACL
3710
+ * triples (written by `addSdna`). Callers no longer ship shape
3711
+ * metadata with the query; the perspective is the source of truth.
3712
+ *
3744
3713
  * @param className - The model class name (e.g. "Recipe")
3745
3714
  * @param queryJson - Structured query as JSON string
3746
- * @param shapeJson - Optional shape metadata JSON from the model class
3747
3715
  * @returns Object with `instances` array and `totalCount`
3748
3716
  */
3749
- async modelQuery(className, queryJson, shapeJson) {
3750
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, shapeJson);
3717
+ async modelQuery(className, queryJson) {
3718
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
3751
3719
  }
3752
3720
  /**
3753
3721
  * Evaluate property getters for a batch of instances in a single RPC call.
@@ -3758,12 +3726,11 @@ class PerspectiveProxy {
3758
3726
  *
3759
3727
  * @param className - The model class name (e.g. "Message")
3760
3728
  * @param instanceIds - Array of instance base expression URIs
3761
- * @param shapeJson - Shape metadata JSON from the model class
3762
3729
  * @param propertyNames - Optional subset of property names to evaluate
3763
3730
  * @returns Map of instance ID → evaluated property values
3764
3731
  */
3765
- async evaluateGetters(className, instanceIds, shapeJson, propertyNames) {
3766
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds, shapeJson, propertyNames);
3732
+ async evaluateGetters(className, instanceIds, propertyNames) {
3733
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds, propertyNames);
3767
3734
  }
3768
3735
  /**
3769
3736
  * Subscribe to model query changes. Builds trigger SPARQL from the model shape
@@ -3775,11 +3742,10 @@ class PerspectiveProxy {
3775
3742
  *
3776
3743
  * @param className - The model class name
3777
3744
  * @param queryJson - JSON-serialized query parameters (same as modelQuery)
3778
- * @param shapeJson - Optional shape metadata JSON from the model class
3779
3745
  * @returns Object with `subscriptionId` and initial `result`
3780
3746
  */
3781
- async modelSubscribe(className, queryJson, shapeJson) {
3782
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelSubscribe(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, shapeJson);
3747
+ async modelSubscribe(className, queryJson) {
3748
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelSubscribe(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
3783
3749
  }
3784
3750
  /**
3785
3751
  * Adds a new link to the perspective.
@@ -5421,22 +5387,21 @@ class PerspectiveClient {
5421
5387
  }
5422
5388
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.disposeQuery', { uuid, subscriptionId });
5423
5389
  }
5424
- async modelQuery(uuid, className, queryJson, shapeJson) {
5425
- const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson });
5390
+ async modelQuery(uuid, className, queryJson) {
5391
+ const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson });
5426
5392
  return JSON.parse(resultJson);
5427
5393
  }
5428
- async evaluateGetters(uuid, className, instanceIds, shapeJson, propertyNames) {
5394
+ async evaluateGetters(uuid, className, instanceIds, propertyNames) {
5429
5395
  const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.evaluateGetters', {
5430
5396
  uuid,
5431
5397
  class_name: className,
5432
5398
  instance_ids: instanceIds,
5433
- shape_json: shapeJson,
5434
5399
  ...(propertyNames && { property_names: propertyNames }),
5435
5400
  });
5436
5401
  return JSON.parse(resultJson);
5437
5402
  }
5438
- async modelSubscribe(uuid, className, queryJson, shapeJson) {
5439
- const response = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson });
5403
+ async modelSubscribe(uuid, className, queryJson) {
5404
+ const response = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson });
5440
5405
  return {
5441
5406
  subscriptionId: response.subscription_id,
5442
5407
  result: JSON.parse(response.result)
@@ -14907,13 +14872,6 @@ class ModelQueryBuilder {
14907
14872
  this.modelClassName = className;
14908
14873
  return this;
14909
14874
  }
14910
- /**
14911
- * Sets the query engine to use.
14912
- * @deprecated Prolog engine has been removed. All queries use SPARQL/Rust.
14913
- */
14914
- engine(_eng) {
14915
- return this;
14916
- }
14917
14875
  /**
14918
14876
  * Executes the query once and returns the results.
14919
14877
  *
@@ -14995,11 +14953,12 @@ class ModelQueryBuilder {
14995
14953
  // Clean up any existing subscription
14996
14954
  this.dispose();
14997
14955
  const ctor = this.ctor;
14998
- // Build the model query params (className, queryJson, shapeJson)
14999
- const { className, queryJson, shapeJson } = ctor.prepareModelQueryParams(this.queryParams, this.modelClassName);
14956
+ // Build the model query params (className, queryJson). The executor
14957
+ // resolves the shape from the perspective's SHACL triples.
14958
+ const { className, queryJson } = ctor.prepareModelQueryParams(this.queryParams, this.modelClassName);
15000
14959
  // Register model subscription via Rust — this builds trigger SPARQL internally,
15001
14960
  // registers the subscription, and runs the initial query in one call.
15002
- const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);
14961
+ const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson);
15003
14962
  // Convert JSON instances to model class instances
15004
14963
  const parseResults = (raw) => {
15005
14964
  return ctor.parseModelResult(this.perspective, raw, this.queryParams.include, this.queryParams.properties);
@@ -15159,8 +15118,8 @@ class ModelQueryBuilder {
15159
15118
  // Clean up any existing subscription
15160
15119
  this.dispose();
15161
15120
  const countParams = { ...this.queryParams, limit: 0 };
15162
- const { className, queryJson, shapeJson } = this.ctor.prepareModelQueryParams(countParams, this.modelClassName);
15163
- const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);
15121
+ const { className, queryJson } = this.ctor.prepareModelQueryParams(countParams, this.modelClassName);
15122
+ const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson);
15164
15123
  const parseCount = (raw) => {
15165
15124
  const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
15166
15125
  return data.totalCount ?? 0;
@@ -15295,8 +15254,8 @@ class ModelQueryBuilder {
15295
15254
  const subscriptionParams = { ...(this.queryParams || {}) };
15296
15255
  delete subscriptionParams.limit;
15297
15256
  delete subscriptionParams.offset;
15298
- const { className, queryJson, shapeJson } = ctor.prepareModelQueryParams(subscriptionParams, this.modelClassName);
15299
- const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);
15257
+ const { className, queryJson } = ctor.prepareModelQueryParams(subscriptionParams, this.modelClassName);
15258
+ const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson);
15300
15259
  // Build the paginated query for Rust endpoint (count: true fetches both results and totalCount in one call)
15301
15260
  const paginatedQuery = {
15302
15261
  ...(this.queryParams || {}),
@@ -15437,46 +15396,6 @@ function defaultFileDecode(resolved) {
15437
15396
  // ---------------------------------------------------------------------------
15438
15397
  // Helpers for Rust-side include resolution
15439
15398
  // ---------------------------------------------------------------------------
15440
- /**
15441
- * Recursively enrich relation metadata in the shape with target class shapes
15442
- * so the Rust endpoint can resolve includes in-process (no extra GraphQL
15443
- * round-trips per relation).
15444
- */
15445
- function enrichShapeForIncludes(metadata, include, allRelMeta) {
15446
- for (const [relName, includeVal] of Object.entries(include)) {
15447
- if (!includeVal)
15448
- continue;
15449
- const meta = allRelMeta[relName];
15450
- if (!meta?.target)
15451
- continue;
15452
- const TargetClass = meta.target();
15453
- // Deep-copy so we don't mutate the cached metadata
15454
- const targetMeta = JSON.parse(JSON.stringify(TargetClass.getModelMetadata()));
15455
- // Ensure the relation is in metadata.relations (fallback for edge cases)
15456
- if (!metadata.relations[relName]) {
15457
- metadata.relations[relName] = {
15458
- name: relName,
15459
- predicate: meta.predicate,
15460
- direction: meta.kind === 'belongsToMany' || meta.kind === 'belongsToOne'
15461
- ? 'reverse'
15462
- : 'forward',
15463
- };
15464
- }
15465
- const rel = metadata.relations[relName];
15466
- rel.kind = meta.kind;
15467
- rel.maxCount = meta.maxCount;
15468
- rel.targetShape = targetMeta;
15469
- rel.targetClassName = targetMeta.className;
15470
- // Recurse for nested includes
15471
- const nested = typeof includeVal === 'object' && includeVal !== null
15472
- ? includeVal.include
15473
- : undefined;
15474
- if (nested) {
15475
- const targetRelMeta = getRelationsMetadata(TargetClass);
15476
- enrichShapeForIncludes(targetMeta, nested, targetRelMeta);
15477
- }
15478
- }
15479
- }
15480
15399
  /**
15481
15400
  * Construct a model class instance from a plain JSON object returned by the
15482
15401
  * Rust endpoint. Recursively converts included relation values (which come
@@ -16158,7 +16077,8 @@ class Ad4mModel {
16158
16077
  }
16159
16078
  /**
16160
16079
  * Build the JSON parameters needed for a model query/subscription endpoint.
16161
- * Returns the className, queryJson, and shapeJson that the Rust executor expects.
16080
+ * Returns the className and queryJson that the Rust executor expects.
16081
+ * Shape resolution happens server-side from the perspective's SHACL triples.
16162
16082
  * @internal
16163
16083
  */
16164
16084
  static prepareModelQueryParams(query = {}, classNameOverride) {
@@ -16198,16 +16118,18 @@ class Ad4mModel {
16198
16118
  if (Object.keys(normalIncludes).length > 0)
16199
16119
  queryInput.include = normalIncludes;
16200
16120
  if (Object.keys(projections).length > 0) {
16201
- // Enrich projections with target shapes so Rust can apply where clause filtering
16121
+ // Tag each projection with its target class name so the executor can
16122
+ // resolve the target shape through its in-memory cache when applying
16123
+ // projection where-clause filters.
16202
16124
  const allRelMeta = getRelationsMetadata(this);
16203
16125
  for (const [, proj] of Object.entries(projections)) {
16204
16126
  const relMeta = allRelMeta[proj.from];
16205
- if (!proj.targetShape && relMeta?.target) {
16127
+ if (!proj.targetClassName && relMeta?.target) {
16206
16128
  try {
16207
16129
  const TargetClass = relMeta.target();
16208
16130
  const targetMeta = TargetClass.getModelMetadata?.();
16209
- if (targetMeta) {
16210
- proj.targetShape = targetMeta;
16131
+ if (targetMeta?.className) {
16132
+ proj.targetClassName = targetMeta.className;
16211
16133
  }
16212
16134
  }
16213
16135
  catch (e) {
@@ -16230,64 +16152,12 @@ class Ad4mModel {
16230
16152
  if (query.count !== undefined)
16231
16153
  queryInput.count = query.count;
16232
16154
  queryInput.deepQuery = query.deepQuery ?? true;
16233
- if (queryInput.include) {
16234
- const allRelMeta = getRelationsMetadata(this);
16235
- enrichShapeForIncludes(metadata, queryInput.include, allRelMeta);
16236
- }
16237
- // Pre-compute conformance getters for Rust-side evaluation.
16238
- // Where clauses are NOT compiled into getter SPARQL because stored
16239
- // property values are signed expression envelopes (literal:json:...),
16240
- // not simple literal:string:X values. Instead, where clauses are
16241
- // attached as metadata for Rust-side post-evaluation filtering.
16242
- {
16243
- const allRelMeta = getRelationsMetadata(this);
16244
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
16245
- const rel = relMeta;
16246
- if (rel.getter || rel.direction === 'reverse' || rel.filter === false)
16247
- continue;
16248
- const meta = allRelMeta[relName];
16249
- if (!meta?.target)
16250
- continue;
16251
- try {
16252
- const TargetClass = meta.target();
16253
- const filter = buildConformanceFilter(meta.predicate, TargetClass);
16254
- if (filter) {
16255
- rel.getter = filter.getter;
16256
- }
16257
- // Attach where-clause metadata for Rust-side post-getter filtering
16258
- if (rel.where) {
16259
- try {
16260
- const targetMetadata = TargetClass.getModelMetadata?.() ?? null;
16261
- if (targetMetadata) {
16262
- const predicates = {};
16263
- for (const propName of Object.keys(rel.where)) {
16264
- if (['id', 'author', 'timestamp'].includes(propName))
16265
- continue;
16266
- const propMeta = targetMetadata.properties[propName];
16267
- if (propMeta?.predicate) {
16268
- predicates[propName] = propMeta.predicate;
16269
- }
16270
- }
16271
- if (Object.keys(predicates).length > 0) {
16272
- rel.whereFilter = rel.where;
16273
- rel.wherePredicates = predicates;
16274
- }
16275
- }
16276
- }
16277
- catch (e) {
16278
- console.debug(`prepareModelQueryParams: target metadata unavailable for relation '${relName}':`, e);
16279
- }
16280
- }
16281
- }
16282
- catch (e) {
16283
- console.debug(`prepareModelQueryParams: target class unavailable for relation '${relName}':`, e);
16284
- }
16285
- }
16286
- }
16155
+ // Conformance getters, where filters, and target shapes for includes
16156
+ // are all resolved by the executor from the perspective's SHACL triples
16157
+ // — no client-side pre-computation is needed any more.
16287
16158
  return {
16288
16159
  className,
16289
16160
  queryJson: JSON.stringify(queryInput),
16290
- shapeJson: JSON.stringify(metadata),
16291
16161
  metadata,
16292
16162
  };
16293
16163
  }
@@ -16364,10 +16234,10 @@ class Ad4mModel {
16364
16234
  * @internal
16365
16235
  */
16366
16236
  static async executeModelQuery(perspective, query = {}, classNameOverride) {
16367
- // Delegate all query input building, shape enrichment, and getter
16368
- // pre-computation to the shared prepareModelQueryParams helper.
16369
- const { className, queryJson, shapeJson } = this.prepareModelQueryParams(query, classNameOverride);
16370
- const result = await perspective.modelQuery(className, queryJson, shapeJson);
16237
+ // Delegate query input building to the shared prepareModelQueryParams
16238
+ // helper. The executor resolves the shape from SHACL server-side.
16239
+ const { className, queryJson } = this.prepareModelQueryParams(query, classNameOverride);
16240
+ const result = await perspective.modelQuery(className, queryJson);
16371
16241
  // Convert JSON instances to model class instances, recursively constructing
16372
16242
  // class instances for any included relations resolved by Rust.
16373
16243
  const instances = result.instances.map((json) => {
@@ -16413,13 +16283,12 @@ class Ad4mModel {
16413
16283
  * });
16414
16284
  * ```
16415
16285
  */
16416
- static async findAll(perspective, query = {},
16417
- /** @deprecated Ignored — Prolog engine has been removed. */
16418
- _engine) {
16419
- if (query.properties && query.properties.length === 0) {
16286
+ static async findAll(perspective, query) {
16287
+ const q = (query ?? {});
16288
+ if (q.properties && q.properties.length === 0) {
16420
16289
  throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
16421
16290
  }
16422
- const { results } = await this.executeModelQuery(perspective, query);
16291
+ const { results } = await this.executeModelQuery(perspective, q);
16423
16292
  return results;
16424
16293
  }
16425
16294
  /**
@@ -16442,10 +16311,8 @@ class Ad4mModel {
16442
16311
  * }
16443
16312
  * ```
16444
16313
  */
16445
- static async findOne(perspective, query = {},
16446
- /** @deprecated Ignored — Prolog engine has been removed. */
16447
- _engine) {
16448
- const limitedQuery = { ...query, limit: 1 };
16314
+ static async findOne(perspective, query) {
16315
+ const limitedQuery = { ...(query ?? {}), limit: 1 };
16449
16316
  const results = await this.findAll(perspective, limitedQuery);
16450
16317
  return results[0] ?? null;
16451
16318
  }
@@ -16466,10 +16333,9 @@ class Ad4mModel {
16466
16333
  * console.log(`Showing 10 of ${totalCount} dessert recipes`);
16467
16334
  * ```
16468
16335
  */
16469
- static async findAllAndCount(perspective, query = {},
16470
- /** @deprecated Ignored — Prolog engine has been removed. */
16471
- _engine) {
16472
- return await this.executeModelQuery(perspective, query);
16336
+ static async findAllAndCount(perspective, query) {
16337
+ const out = await this.executeModelQuery(perspective, (query ?? {}));
16338
+ return out;
16473
16339
  }
16474
16340
  /**
16475
16341
  * Helper function for pagination with explicit page size and number.
@@ -16488,12 +16354,10 @@ class Ad4mModel {
16488
16354
  * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
16489
16355
  * ```
16490
16356
  */
16491
- static async paginate(perspective, pageSize, pageNumber, query,
16492
- /** @deprecated Ignored — Prolog engine has been removed. */
16493
- _engine) {
16494
- const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
16357
+ static async paginate(perspective, pageSize, pageNumber, query) {
16358
+ const paginationQuery = { ...(query ?? {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
16495
16359
  const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
16496
- return { results, totalCount, pageSize, pageNumber };
16360
+ return { results: results, totalCount, pageSize, pageNumber };
16497
16361
  }
16498
16362
  /**
16499
16363
  * Generates a SPARQL COUNT query for the model.
@@ -16520,8 +16384,8 @@ class Ad4mModel {
16520
16384
  * });
16521
16385
  * ```
16522
16386
  */
16523
- static async count(perspective, query = {}) {
16524
- const { totalCount } = await this.executeModelQuery(perspective, { ...query, limit: 0 });
16387
+ static async count(perspective, query) {
16388
+ const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 });
16525
16389
  return totalCount;
16526
16390
  }
16527
16391
  async setProperty(key, value, batchId) {
@@ -16832,29 +16696,10 @@ class Ad4mModel {
16832
16696
  if (instances.length === 0)
16833
16697
  return;
16834
16698
  const metadata = this.getModelMetadata();
16835
- // Pre-compute conformance getters so the shape sent to Rust includes them
16836
- const allRelMeta = getRelationsMetadata(this);
16837
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
16838
- const rel = relMeta;
16839
- if (rel.getter || rel.direction === 'reverse' || rel.filter === false)
16840
- continue;
16841
- const meta = allRelMeta[relName];
16842
- if (!meta?.target)
16843
- continue;
16844
- try {
16845
- const TargetClass = meta.target();
16846
- const filter = buildConformanceFilter(meta.predicate, TargetClass);
16847
- if (filter)
16848
- rel.getter = filter.getter;
16849
- }
16850
- catch (e) {
16851
- console.debug(`evaluateGetters: target class unavailable for relation '${relName}':`, e);
16852
- }
16853
- }
16854
- const shapeJson = JSON.stringify(metadata);
16855
16699
  const instanceIds = instances.map(inst => inst.id || inst._baseExpression);
16856
- // Single RPC call evaluates all getters in-process on the executor
16857
- const result = await perspective.evaluateGetters(metadata.className, instanceIds, shapeJson, propertyNames);
16700
+ // The executor reads getter SPARQL from the perspective's SHACL triples
16701
+ // (written by `addSdna`), so no shape JSON is shipped with the call.
16702
+ const result = await perspective.evaluateGetters(metadata.className, instanceIds, propertyNames);
16858
16703
  // Determine which property names were evaluated for snapshot sync
16859
16704
  const evaluatedPropertyNames = [];
16860
16705
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
@@ -17218,7 +17063,7 @@ class Ad4mModel {
17218
17063
  * ```
17219
17064
  */
17220
17065
  static query(perspective, query) {
17221
- return new ModelQueryBuilder(perspective, this, query);
17066
+ return new ModelQueryBuilder(perspective, this, (query ?? {}));
17222
17067
  }
17223
17068
  /**
17224
17069
  * Creates an Ad4mModel class from a JSON Schema definition.
@@ -17627,6 +17472,71 @@ class PerspectiveHandle {
17627
17472
  }
17628
17473
  }
17629
17474
 
17475
+ /**
17476
+ * SPARQL binding helpers — typed shapes and parsers for `querySparql<T>()`.
17477
+ *
17478
+ * AD4M stores non-string property values as URL-encoded `Literal` payloads
17479
+ * (see {@link Literal}). When raw SPARQL queries pull these values out of the
17480
+ * RDF store the bindings are still in encoded form; consumers must decode
17481
+ * before use. The helpers here centralise that decode step so each call site
17482
+ * can pick the variant matching its declared binding type.
17483
+ *
17484
+ * @example
17485
+ * ```ts
17486
+ * interface MessageBinding {
17487
+ * id: string;
17488
+ * timestamp: string; // raw literal — decode with parseLitNumber
17489
+ * body?: string; // raw literal — decode with parseLit
17490
+ * }
17491
+ * const rows = await perspective.querySparql<MessageBinding[]>(query);
17492
+ * const ts = parseLitNumber(rows[0].timestamp); // number
17493
+ * const body = rows[0].body ? parseLit(rows[0].body) : '';
17494
+ * ```
17495
+ */
17496
+ /** Sum a SPARQL COUNT(?x) result down to a plain number (returns 0 on empty). */
17497
+ function parseSparqlCount(result) {
17498
+ if (!result || result.length === 0)
17499
+ return 0;
17500
+ const raw = result[0].count;
17501
+ const n = parseInt(raw, 10);
17502
+ return Number.isNaN(n) ? 0 : n;
17503
+ }
17504
+ /**
17505
+ * Decode a `Literal`-encoded SPARQL binding back to a plain string.
17506
+ *
17507
+ * Mirrors Flux's local `parseLit` helper. Returns `''` for `undefined`/empty
17508
+ * input. Falls through to the raw value if decoding fails (defensive — the
17509
+ * binding may already be a plain string for unwrapped properties).
17510
+ */
17511
+ function parseLit(val) {
17512
+ if (val === undefined || val === null || val === '')
17513
+ return '';
17514
+ try {
17515
+ const result = Literal.fromUrl(val).get();
17516
+ if (result && typeof result === 'object') {
17517
+ return result.data ?? JSON.stringify(result);
17518
+ }
17519
+ return String(result);
17520
+ }
17521
+ catch {
17522
+ return val;
17523
+ }
17524
+ }
17525
+ /** Decode a `Literal`-encoded binding to a number. Returns 0 on empty/invalid input. */
17526
+ function parseLitNumber(val) {
17527
+ if (val === undefined || val === null || val === '')
17528
+ return 0;
17529
+ const decoded = parseLit(val);
17530
+ const n = Number(decoded);
17531
+ return Number.isNaN(n) ? 0 : n;
17532
+ }
17533
+ /** Decode a `Literal`-encoded binding to a boolean. Returns false on empty input. */
17534
+ function parseLitBoolean(val) {
17535
+ if (val === undefined || val === null || val === '')
17536
+ return false;
17537
+ return parseLit(val) === 'true';
17538
+ }
17539
+
17630
17540
  /**
17631
17541
  * WakerSubscriptionManager — manages live query subscriptions for the waker.
17632
17542
  *
@@ -17913,6 +17823,195 @@ function isIncludeProjection(val) {
17913
17823
  return typeof val === 'object' && val !== null && 'from' in val;
17914
17824
  }
17915
17825
 
17826
+ /**
17827
+ * Shared query compilation utilities.
17828
+ *
17829
+ * These functions are used by both the runtime query builder (`Ad4mModel`) and
17830
+ * the compile-time SHACL generator (`decorators.ts`).
17831
+ *
17832
+ * All output uses native SPARQL syntax.
17833
+ */
17834
+ /**
17835
+ * Format a JavaScript value for embedding in a query expression.
17836
+ *
17837
+ * - Strings are single-quoted with backslash / quote / newline escaping
17838
+ * - Numbers and booleans are passed through as-is
17839
+ * - Arrays are recursed
17840
+ */
17841
+ function formatQueryValue(value) {
17842
+ if (typeof value === 'string') {
17843
+ // Escape backslashes first, then single quotes and other special characters
17844
+ const escaped = value
17845
+ .replace(/\\/g, '\\\\') // Backslash -> \\
17846
+ .replace(/'/g, "\\'") // Single quote -> \'
17847
+ .replace(/"/g, '\\"') // Double quote -> \"
17848
+ .replace(/\n/g, '\\n') // Newline -> \n
17849
+ .replace(/\r/g, '\\r') // Carriage return -> \r
17850
+ .replace(/\t/g, '\\t'); // Tab -> \t
17851
+ return `'${escaped}'`;
17852
+ }
17853
+ else if (typeof value === 'number' || typeof value === 'boolean') {
17854
+ return String(value);
17855
+ }
17856
+ else if (Array.isArray(value)) {
17857
+ return `[${value.map(v => formatQueryValue(v)).join(', ')}]`;
17858
+ }
17859
+ else {
17860
+ return String(value);
17861
+ }
17862
+ }
17863
+ /**
17864
+ * Compile a single Where condition for a property into a SPARQL triple pattern
17865
+ * that can be embedded in a getter's WHERE clause.
17866
+ *
17867
+ * The generated pattern operates on `?target` — e.g.:
17868
+ * `?target <pred> <value> .`
17869
+ * `FILTER EXISTS { ?target <pred> ?_v0 }`
17870
+ *
17871
+ * @param predicate - The predicate URI for the property
17872
+ * @param condition - The Where condition value
17873
+ * @param opts - Optional settings (e.g. `resolveLanguage`)
17874
+ * @returns A single SPARQL condition string
17875
+ */
17876
+ function buildWhereCondition(predicate, condition, opts) {
17877
+ const escapedPredicate = escapeQueryString(predicate);
17878
+ // For literal-resolved properties, we match against the raw IRI (which is a literal: URI)
17879
+ // For language-resolved properties, we match against the plain URI
17880
+ // For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>
17881
+ // For language-resolved properties, values are plain URIs
17882
+ const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
17883
+ const varSuffix = opts?.varIndex ?? 0;
17884
+ function formatValue(v) {
17885
+ if (typeof v === 'string') {
17886
+ return isLiteral
17887
+ ? `<literal:string:${escapeQueryString(v)}>`
17888
+ : `<${escapeQueryString(v)}>`;
17889
+ }
17890
+ // Numbers/booleans — also stored as literal:string: in AD4M
17891
+ return `<literal:string:${v}>`;
17892
+ }
17893
+ /**
17894
+ * For literal properties, generate a FILTER-based match that handles both
17895
+ * the raw value and the literal-encoded value. This mirrors the Rust
17896
+ * `build_projection_where_patterns` approach which uses:
17897
+ * FILTER(STR(?var) = "value" || STR(?var) = "literal:string:encodedValue")
17898
+ * This is more robust than exact IRI matching because it handles edge cases
17899
+ * where the stored format might vary.
17900
+ */
17901
+ function formatLiteralFilter(varName, v) {
17902
+ const raw = escapeQueryString(String(v));
17903
+ const encoded = encodeURIComponent(String(v))
17904
+ .replace(/!/g, '%21')
17905
+ .replace(/'/g, '%27')
17906
+ .replace(/\(/g, '%28')
17907
+ .replace(/\)/g, '%29')
17908
+ .replace(/\*/g, '%2A');
17909
+ if (typeof v === 'string') {
17910
+ return `FILTER(STR(${varName}) = "${raw}" || STR(${varName}) = "literal:string:${encoded}")`;
17911
+ }
17912
+ else if (typeof v === 'number') {
17913
+ return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:number:${v}")`;
17914
+ }
17915
+ else if (typeof v === 'boolean') {
17916
+ return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:boolean:${v}")`;
17917
+ }
17918
+ return `FILTER(STR(${varName}) = "${raw}")`;
17919
+ }
17920
+ if (Array.isArray(condition)) {
17921
+ // Array values → FILTER IN
17922
+ if (isLiteral) {
17923
+ const varName = `?_wc${varSuffix}`;
17924
+ const inValues = condition.flatMap(v => {
17925
+ const raw = escapeQueryString(String(v));
17926
+ const encoded = encodeURIComponent(String(v))
17927
+ .replace(/!/g, '%21').replace(/'/g, '%27')
17928
+ .replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
17929
+ return [`"${raw}"`, `"literal:string:${encoded}"`];
17930
+ }).join(', ');
17931
+ return `?target <${escapedPredicate}> ${varName} . FILTER(STR(${varName}) IN (${inValues}))`;
17932
+ }
17933
+ const formattedValues = condition.map(formatValue).join(', ');
17934
+ return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;
17935
+ }
17936
+ else if (typeof condition === 'object' && condition !== null) {
17937
+ // Operator object
17938
+ const ops = condition;
17939
+ const parts = [];
17940
+ if (ops.not !== undefined) {
17941
+ if (Array.isArray(ops.not)) {
17942
+ const formattedValues = ops.not.map((v) => formatValue(v)).join(', ');
17943
+ // FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
17944
+ // so O(N²) behavior is bounded by the number of values for this property.
17945
+ parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ?_nval . FILTER(?_nval IN (${formattedValues})) }`);
17946
+ }
17947
+ else {
17948
+ // FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
17949
+ // so O(N²) behavior is bounded by the number of values for this property.
17950
+ parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ${formatValue(ops.not)} }`);
17951
+ }
17952
+ }
17953
+ // Comparison operators — ensure property exists
17954
+ const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
17955
+ ops.lt !== undefined || ops.lte !== undefined ||
17956
+ ops.between !== undefined || ops.contains !== undefined;
17957
+ if (hasComparisonOps) {
17958
+ parts.push(`FILTER EXISTS { ?target <${escapedPredicate}> ?_cmp }`);
17959
+ }
17960
+ return parts.join(' ');
17961
+ }
17962
+ else {
17963
+ // Simple equality
17964
+ if (isLiteral) {
17965
+ // Use FILTER matching (mirrors Rust build_projection_where_patterns)
17966
+ // to handle both raw values and literal-encoded IRIs robustly.
17967
+ const varName = `?_wc${varSuffix}`;
17968
+ return `?target <${escapedPredicate}> ${varName} . ${formatLiteralFilter(varName, condition)}`;
17969
+ }
17970
+ return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
17971
+ }
17972
+ }
17973
+ /**
17974
+ * Compile a full `Where` clause to an array of SPARQL condition strings.
17975
+ *
17976
+ * When `metadata` is provided, property names are resolved to predicates
17977
+ * using the model's property metadata. When `metadata` is `null`, property
17978
+ * names are treated as raw predicate URIs.
17979
+ *
17980
+ * Only handles **regular properties** — special fields (`id`, `author`,
17981
+ * `timestamp`) and relation fields are skipped (they are only relevant at
17982
+ * runtime query time, not for compile-time getter generation).
17983
+ */
17984
+ function compileWhereClause(where, metadata) {
17985
+ const conditions = [];
17986
+ for (const [propertyName, condition] of Object.entries(where)) {
17987
+ // Skip special fields that don't apply at compile time
17988
+ if (['id', 'author', 'timestamp'].includes(propertyName))
17989
+ continue;
17990
+ let predicate;
17991
+ let resolveLanguage;
17992
+ if (metadata) {
17993
+ const propMeta = metadata.properties[propertyName];
17994
+ if (propMeta) {
17995
+ predicate = propMeta.predicate;
17996
+ resolveLanguage = propMeta.resolveLanguage;
17997
+ }
17998
+ else {
17999
+ // Property not found in metadata — treat name as raw predicate URI
18000
+ predicate = propertyName;
18001
+ }
18002
+ }
18003
+ else {
18004
+ // No metadata — treat name as raw predicate URI
18005
+ predicate = propertyName;
18006
+ }
18007
+ const cond = buildWhereCondition(predicate, condition, { resolveLanguage, varIndex: conditions.length });
18008
+ if (cond) {
18009
+ conditions.push(cond);
18010
+ }
18011
+ }
18012
+ return conditions;
18013
+ }
18014
+
17916
18015
  class Neighbourhood {
17917
18016
  constructor(linkLanguage, meta) {
17918
18017
  this.linkLanguage = linkLanguage;
@@ -18087,6 +18186,10 @@ exports.normalizeNamespaceString = normalizeNamespaceString;
18087
18186
  exports.normalizeSchemaType = normalizeSchemaType;
18088
18187
  exports.normalizeValue = normalizeValue;
18089
18188
  exports.parseExprUrl = parseExprUrl;
18189
+ exports.parseLit = parseLit;
18190
+ exports.parseLitBoolean = parseLitBoolean;
18191
+ exports.parseLitNumber = parseLitNumber;
18192
+ exports.parseSparqlCount = parseSparqlCount;
18090
18193
  exports.queryCacheSize = queryCacheSize;
18091
18194
  exports.resolveParentPredicate = resolveParentPredicate;
18092
18195
  exports.setCachedResult = setCachedResult;