@coasys/ad4m 0.13.0-postmessage-ws-proxy.0 → 0.13.0-postmessage-ws-proxy.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/index.cjs +825 -653
- package/lib/index.js +812 -654
- package/lib/src/Ad4mClient.d.ts +1 -0
- package/lib/src/Ad4mClient.js +1 -1
- package/lib/src/ai/AIClient.js +1 -1
- package/lib/src/apiClient.d.ts +4 -1
- package/lib/src/apiClient.js +6 -1
- package/lib/src/index.d.ts +4 -0
- package/lib/src/index.js +4 -0
- package/lib/src/model/Ad4mModel.d.ts +9 -32
- package/lib/src/model/Ad4mModel.js +36 -266
- package/lib/src/model/ModelQueryBuilder.d.ts +5 -10
- package/lib/src/model/ModelQueryBuilder.js +20 -36
- package/lib/src/model/decorators.d.ts +7 -4
- package/lib/src/model/shacl-gen.js +120 -47
- package/lib/src/model/types.d.ts +140 -4
- package/lib/src/perspectives/PerspectiveClient.d.ts +4 -4
- package/lib/src/perspectives/PerspectiveClient.js +5 -6
- package/lib/src/perspectives/PerspectiveProxy.d.ts +8 -7
- package/lib/src/perspectives/PerspectiveProxy.js +10 -9
- package/lib/src/perspectives/SparqlBindings.d.ts +47 -0
- package/lib/src/perspectives/SparqlBindings.js +65 -0
- package/lib/src/shacl/NodeExpression.d.ts +44 -0
- package/lib/src/shacl/NodeExpression.js +39 -0
- package/lib/src/shacl/SHACLShape.d.ts +23 -0
- package/lib/src/shacl/SHACLShape.js +115 -1
- package/lib/src/shacl/builders.d.ts +58 -0
- package/lib/src/shacl/builders.js +76 -0
- package/lib/src/shacl/index.d.ts +36 -0
- package/lib/src/shacl/index.js +33 -0
- package/package.json +8 -11
- package/src/Ad4mClient.ts +2 -2
- package/src/ai/AIClient.ts +1 -1
- package/src/apiClient.ts +8 -1
- package/src/index.ts +4 -0
- package/src/model/Ad4mModel.test.ts +33 -74
- package/src/model/Ad4mModel.ts +54 -272
- package/src/model/ModelQueryBuilder.ts +29 -46
- package/src/model/decorators.ts +7 -4
- package/src/model/relation-filtering.test.ts +46 -39
- package/src/model/shacl-gen.ts +128 -54
- package/src/model/shacl-roundtrip.test.ts +197 -0
- package/src/model/types-typed-query.test.ts +360 -0
- package/src/model/types.ts +196 -4
- package/src/perspectives/PerspectiveClient.ts +6 -8
- package/src/perspectives/PerspectiveProxy.ts +13 -13
- package/src/perspectives/SparqlBindings.ts +79 -0
- package/src/shacl/NodeExpression.ts +54 -0
- package/src/shacl/SHACLShape.test.ts +172 -0
- package/src/shacl/SHACLShape.ts +173 -1
- package/src/shacl/builders.ts +86 -0
- package/src/shacl/index.ts +72 -0
package/lib/index.cjs
CHANGED
|
@@ -23,7 +23,7 @@ function nextId() {
|
|
|
23
23
|
return String(++_idCounter);
|
|
24
24
|
}
|
|
25
25
|
class ApiClient {
|
|
26
|
-
constructor(baseUrl, token, webSocketImpl) {
|
|
26
|
+
constructor(baseUrl, token, webSocketImpl, fetchImpl) {
|
|
27
27
|
// ── WebSocket RPC core ──────────────────────────────────────────────────
|
|
28
28
|
this._ws = null;
|
|
29
29
|
this._wsCallbacks = new Set();
|
|
@@ -37,9 +37,14 @@ class ApiClient {
|
|
|
37
37
|
this.baseUrl = baseUrl;
|
|
38
38
|
this.token = token;
|
|
39
39
|
this._webSocketImpl = webSocketImpl;
|
|
40
|
+
this._fetchImpl = fetchImpl;
|
|
40
41
|
}
|
|
41
42
|
getBaseUrl() { return this.baseUrl; }
|
|
42
43
|
getToken() { return this.token; }
|
|
44
|
+
/** Perform an HTTP request, using an injected fetch implementation if provided. */
|
|
45
|
+
doFetch(url, init) {
|
|
46
|
+
return this._fetchImpl ? this._fetchImpl(url, init) : fetch(url, init);
|
|
47
|
+
}
|
|
43
48
|
setToken(token) {
|
|
44
49
|
this.token = token;
|
|
45
50
|
}
|
|
@@ -958,6 +963,46 @@ function buildSDNA(subjectName, obj, properties, allRelationsMeta) {
|
|
|
958
963
|
};
|
|
959
964
|
}
|
|
960
965
|
|
|
966
|
+
/**
|
|
967
|
+
* SHACL-AF Node Expressions for property transforms.
|
|
968
|
+
*
|
|
969
|
+
* A `NodeExpression` is a JSON-serializable tree that describes how to transform
|
|
970
|
+
* a resolved property value. Unlike JS lambdas, these are portable, inspectable,
|
|
971
|
+
* and can be executed in the Rust model query engine.
|
|
972
|
+
*
|
|
973
|
+
* Each expression is a tagged union that evaluates to a `Value` (JSON-compatible).
|
|
974
|
+
*/
|
|
975
|
+
/**
|
|
976
|
+
* Type guard to check if a value is a valid NodeExpression.
|
|
977
|
+
*/
|
|
978
|
+
function isNodeExpression(v) {
|
|
979
|
+
if (typeof v !== 'object' || v === null)
|
|
980
|
+
return false;
|
|
981
|
+
const obj = v;
|
|
982
|
+
const type = obj.type;
|
|
983
|
+
switch (type) {
|
|
984
|
+
case 'focus':
|
|
985
|
+
return typeof obj.type === 'string';
|
|
986
|
+
case 'literal':
|
|
987
|
+
return typeof obj.value === 'string' || typeof obj.value === 'number' || typeof obj.value === 'boolean';
|
|
988
|
+
case 'path':
|
|
989
|
+
return typeof obj.predicate === 'string';
|
|
990
|
+
case 'exists':
|
|
991
|
+
return isNodeExpression(obj.expr);
|
|
992
|
+
case 'if':
|
|
993
|
+
return isNodeExpression(obj.cond) && isNodeExpression(obj.then) &&
|
|
994
|
+
(obj.else === undefined || isNodeExpression(obj.else));
|
|
995
|
+
case 'concat':
|
|
996
|
+
return Array.isArray(obj.args) && obj.args.every(isNodeExpression);
|
|
997
|
+
case 'coalesce':
|
|
998
|
+
return Array.isArray(obj.args) && obj.args.every(isNodeExpression);
|
|
999
|
+
case 'function':
|
|
1000
|
+
return typeof obj.iri === 'string' && Array.isArray(obj.args) && obj.args.every(isNodeExpression);
|
|
1001
|
+
default:
|
|
1002
|
+
return false;
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
|
|
961
1006
|
/**
|
|
962
1007
|
* Extract namespace from a URI
|
|
963
1008
|
* Examples:
|
|
@@ -1288,7 +1333,7 @@ class SHACLShape {
|
|
|
1288
1333
|
target: `literal:${prop.writable}`
|
|
1289
1334
|
});
|
|
1290
1335
|
}
|
|
1291
|
-
if (prop.resolveLanguage) {
|
|
1336
|
+
if (prop.resolveLanguage != null) {
|
|
1292
1337
|
links.push({
|
|
1293
1338
|
source: propShapeId,
|
|
1294
1339
|
predicate: "ad4m://resolveLanguage",
|
|
@@ -1345,6 +1390,48 @@ class SHACLShape {
|
|
|
1345
1390
|
target: `literal:string:${JSON.stringify(prop.in)}`
|
|
1346
1391
|
});
|
|
1347
1392
|
}
|
|
1393
|
+
if (prop.relationKind) {
|
|
1394
|
+
links.push({
|
|
1395
|
+
source: propShapeId,
|
|
1396
|
+
predicate: "ad4m://relationKind",
|
|
1397
|
+
target: `literal:string:${prop.relationKind}`
|
|
1398
|
+
});
|
|
1399
|
+
}
|
|
1400
|
+
if (prop.targetClassName) {
|
|
1401
|
+
links.push({
|
|
1402
|
+
source: propShapeId,
|
|
1403
|
+
predicate: "ad4m://targetClassName",
|
|
1404
|
+
target: `literal:string:${prop.targetClassName}`
|
|
1405
|
+
});
|
|
1406
|
+
}
|
|
1407
|
+
if (prop.whereFilter !== undefined && prop.whereFilter !== null) {
|
|
1408
|
+
links.push({
|
|
1409
|
+
source: propShapeId,
|
|
1410
|
+
predicate: "ad4m://whereFilter",
|
|
1411
|
+
target: `literal:string:${JSON.stringify(prop.whereFilter)}`
|
|
1412
|
+
});
|
|
1413
|
+
}
|
|
1414
|
+
if (prop.wherePredicates && Object.keys(prop.wherePredicates).length > 0) {
|
|
1415
|
+
links.push({
|
|
1416
|
+
source: propShapeId,
|
|
1417
|
+
predicate: "ad4m://wherePredicates",
|
|
1418
|
+
target: `literal:string:${JSON.stringify(prop.wherePredicates)}`
|
|
1419
|
+
});
|
|
1420
|
+
}
|
|
1421
|
+
if (prop.filter !== undefined) {
|
|
1422
|
+
links.push({
|
|
1423
|
+
source: propShapeId,
|
|
1424
|
+
predicate: "ad4m://filter",
|
|
1425
|
+
target: `literal:${prop.filter}`
|
|
1426
|
+
});
|
|
1427
|
+
}
|
|
1428
|
+
if (prop.transform && typeof prop.transform === 'object') {
|
|
1429
|
+
links.push({
|
|
1430
|
+
source: propShapeId,
|
|
1431
|
+
predicate: "ad4m://transform",
|
|
1432
|
+
target: `literal:string:${JSON.stringify(prop.transform)}`
|
|
1433
|
+
});
|
|
1434
|
+
}
|
|
1348
1435
|
}
|
|
1349
1436
|
return links;
|
|
1350
1437
|
}
|
|
@@ -1526,6 +1613,60 @@ class SHACLShape {
|
|
|
1526
1613
|
// Ignore parse errors
|
|
1527
1614
|
}
|
|
1528
1615
|
}
|
|
1616
|
+
const relationKindLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://relationKind");
|
|
1617
|
+
if (relationKindLink) {
|
|
1618
|
+
const val = relationKindLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
1619
|
+
if (val === 'hasMany' || val === 'hasOne' || val === 'belongsToOne' || val === 'belongsToMany') {
|
|
1620
|
+
prop.relationKind = val;
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
const targetClassNameLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://targetClassName");
|
|
1624
|
+
if (targetClassNameLink) {
|
|
1625
|
+
prop.targetClassName = targetClassNameLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
1626
|
+
}
|
|
1627
|
+
const whereFilterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://whereFilter");
|
|
1628
|
+
if (whereFilterLink) {
|
|
1629
|
+
try {
|
|
1630
|
+
const jsonStr = whereFilterLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
1631
|
+
prop.whereFilter = JSON.parse(jsonStr);
|
|
1632
|
+
}
|
|
1633
|
+
catch (e) {
|
|
1634
|
+
// Ignore parse errors
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
const wherePredicatesLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://wherePredicates");
|
|
1638
|
+
if (wherePredicatesLink) {
|
|
1639
|
+
try {
|
|
1640
|
+
const jsonStr = wherePredicatesLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
1641
|
+
prop.wherePredicates = JSON.parse(jsonStr);
|
|
1642
|
+
}
|
|
1643
|
+
catch (e) {
|
|
1644
|
+
// Ignore parse errors
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
const filterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://filter");
|
|
1648
|
+
if (filterLink) {
|
|
1649
|
+
let val = filterLink.target.replace(/^literal:\/\/|^literal:/, '');
|
|
1650
|
+
if (val.startsWith('boolean:'))
|
|
1651
|
+
val = val.substring(8);
|
|
1652
|
+
prop.filter = val === 'true';
|
|
1653
|
+
}
|
|
1654
|
+
const transformLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://transform");
|
|
1655
|
+
if (transformLink) {
|
|
1656
|
+
const jsonStr = transformLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
1657
|
+
try {
|
|
1658
|
+
const parsed = JSON.parse(jsonStr);
|
|
1659
|
+
if (!isNodeExpression(parsed)) {
|
|
1660
|
+
throw new Error(`Invalid transform for property ${propShapeId}: ` +
|
|
1661
|
+
`payload is not a valid NodeExpression. Received: ${jsonStr}`);
|
|
1662
|
+
}
|
|
1663
|
+
prop.transform = parsed;
|
|
1664
|
+
}
|
|
1665
|
+
catch (e) {
|
|
1666
|
+
throw new Error(`Failed to deserialize transform for property ${propShapeId}: ` +
|
|
1667
|
+
`${e instanceof Error ? e.message : String(e)}. Payload: ${jsonStr}`);
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1529
1670
|
shape.addProperty(prop);
|
|
1530
1671
|
}
|
|
1531
1672
|
return shape;
|
|
@@ -1562,6 +1703,12 @@ class SHACLShape {
|
|
|
1562
1703
|
conformance_conditions: p.conformanceConditions,
|
|
1563
1704
|
class: p.class,
|
|
1564
1705
|
in: p.in,
|
|
1706
|
+
relation_kind: p.relationKind,
|
|
1707
|
+
target_class_name: p.targetClassName,
|
|
1708
|
+
where_filter: p.whereFilter,
|
|
1709
|
+
where_predicates: p.wherePredicates,
|
|
1710
|
+
filter: p.filter,
|
|
1711
|
+
transform: p.transform,
|
|
1565
1712
|
})),
|
|
1566
1713
|
constructor_actions: this.constructor_actions,
|
|
1567
1714
|
destructor_actions: this.destructor_actions,
|
|
@@ -1575,6 +1722,11 @@ class SHACLShape {
|
|
|
1575
1722
|
? new SHACLShape(json.node_shape_uri, json.target_class)
|
|
1576
1723
|
: new SHACLShape(json.target_class);
|
|
1577
1724
|
for (const p of json.properties || []) {
|
|
1725
|
+
// Validate transform if present
|
|
1726
|
+
if (p.transform && !isNodeExpression(p.transform)) {
|
|
1727
|
+
throw new Error(`Invalid transform for property ${p.name}: ` +
|
|
1728
|
+
`payload is not a valid NodeExpression. Received: ${JSON.stringify(p.transform)}`);
|
|
1729
|
+
}
|
|
1578
1730
|
shape.addProperty({
|
|
1579
1731
|
path: p.path,
|
|
1580
1732
|
name: p.name,
|
|
@@ -1596,6 +1748,12 @@ class SHACLShape {
|
|
|
1596
1748
|
conformanceConditions: p.conformance_conditions,
|
|
1597
1749
|
class: p.class,
|
|
1598
1750
|
in: p.in,
|
|
1751
|
+
relationKind: p.relation_kind,
|
|
1752
|
+
targetClassName: p.target_class_name,
|
|
1753
|
+
whereFilter: p.where_filter,
|
|
1754
|
+
wherePredicates: p.where_predicates,
|
|
1755
|
+
filter: p.filter,
|
|
1756
|
+
transform: p.transform,
|
|
1599
1757
|
});
|
|
1600
1758
|
}
|
|
1601
1759
|
if (json.constructor_actions) {
|
|
@@ -1613,303 +1771,61 @@ class SHACLShape {
|
|
|
1613
1771
|
}
|
|
1614
1772
|
}
|
|
1615
1773
|
|
|
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
1774
|
/**
|
|
1677
|
-
*
|
|
1775
|
+
* SHACL shape generation for AD4M model classes.
|
|
1678
1776
|
*
|
|
1679
|
-
*
|
|
1680
|
-
*
|
|
1681
|
-
*
|
|
1777
|
+
* Builds a W3C SHACL `SHACLShape` (with AD4M-specific action extensions)
|
|
1778
|
+
* from a model's property and relation metadata. The heavy lifting used
|
|
1779
|
+
* to live inside the `@Model` decorator closure — it is extracted here so
|
|
1780
|
+
* decorators.ts stays focused on decorator registration logic.
|
|
1682
1781
|
*/
|
|
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
1782
|
/**
|
|
1706
|
-
*
|
|
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 }`
|
|
1783
|
+
* Build a SHACL shape for a model class.
|
|
1712
1784
|
*
|
|
1713
|
-
* @param
|
|
1714
|
-
* @param
|
|
1715
|
-
*
|
|
1716
|
-
* @
|
|
1785
|
+
* @param subjectName - The model's registered name (from `@Model({ name })`)
|
|
1786
|
+
* @param target - The class constructor (used for prototype access,
|
|
1787
|
+
* inheritance chain, and relation target resolution)
|
|
1788
|
+
* @param properties - Merged property metadata (from `getPropertiesMetadata`)
|
|
1789
|
+
* @param allRelationsMeta - Merged relation metadata (from `getRelationsMetadata`)
|
|
1790
|
+
* @param conformanceFilterFn - Injected conformance-filter builder
|
|
1791
|
+
* (avoids circular dependency back into decorators.ts)
|
|
1717
1792
|
*/
|
|
1718
|
-
function
|
|
1719
|
-
const
|
|
1720
|
-
//
|
|
1721
|
-
|
|
1722
|
-
//
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
: `<${escapeQueryString(v)}>`;
|
|
1793
|
+
function buildSHACL(subjectName, target, properties, allRelationsMeta, conformanceFilterFn) {
|
|
1794
|
+
const obj = target.prototype;
|
|
1795
|
+
// ── Determine namespace from first property or relation ─────────────
|
|
1796
|
+
let namespace = "ad4m://";
|
|
1797
|
+
// Try properties first
|
|
1798
|
+
if (Object.keys(properties).length > 0) {
|
|
1799
|
+
const firstProp = properties[Object.keys(properties)[0]];
|
|
1800
|
+
if (firstProp.through) {
|
|
1801
|
+
const match = firstProp.through.match(/^([^:]+:\/\/)/);
|
|
1802
|
+
if (match) {
|
|
1803
|
+
namespace = match[1];
|
|
1804
|
+
}
|
|
1731
1805
|
}
|
|
1732
|
-
// Numbers/booleans — also stored as literal:string: in AD4M
|
|
1733
|
-
return `<literal:string:${v}>`;
|
|
1734
1806
|
}
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
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}")`;
|
|
1807
|
+
// Fall back to relations if no properties
|
|
1808
|
+
else if (Object.keys(allRelationsMeta).length > 0) {
|
|
1809
|
+
const firstRel = allRelationsMeta[Object.keys(allRelationsMeta)[0]];
|
|
1810
|
+
if (firstRel.predicate) {
|
|
1811
|
+
const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
|
|
1812
|
+
if (match) {
|
|
1813
|
+
namespace = match[1];
|
|
1814
|
+
}
|
|
1759
1815
|
}
|
|
1760
|
-
return `FILTER(STR(${varName}) = "${raw}")`;
|
|
1761
1816
|
}
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
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
|
-
/**
|
|
1858
|
-
* SHACL shape generation for AD4M model classes.
|
|
1859
|
-
*
|
|
1860
|
-
* Builds a W3C SHACL `SHACLShape` (with AD4M-specific action extensions)
|
|
1861
|
-
* from a model's property and relation metadata. The heavy lifting used
|
|
1862
|
-
* to live inside the `@Model` decorator closure — it is extracted here so
|
|
1863
|
-
* decorators.ts stays focused on decorator registration logic.
|
|
1864
|
-
*/
|
|
1865
|
-
/**
|
|
1866
|
-
* Build a SHACL shape for a model class.
|
|
1867
|
-
*
|
|
1868
|
-
* @param subjectName - The model's registered name (from `@Model({ name })`)
|
|
1869
|
-
* @param target - The class constructor (used for prototype access,
|
|
1870
|
-
* inheritance chain, and relation target resolution)
|
|
1871
|
-
* @param properties - Merged property metadata (from `getPropertiesMetadata`)
|
|
1872
|
-
* @param allRelationsMeta - Merged relation metadata (from `getRelationsMetadata`)
|
|
1873
|
-
* @param conformanceFilterFn - Injected conformance-filter builder
|
|
1874
|
-
* (avoids circular dependency back into decorators.ts)
|
|
1875
|
-
*/
|
|
1876
|
-
function buildSHACL(subjectName, target, properties, allRelationsMeta, conformanceFilterFn) {
|
|
1877
|
-
const obj = target.prototype;
|
|
1878
|
-
// ── Determine namespace from first property or relation ─────────────
|
|
1879
|
-
let namespace = "ad4m://";
|
|
1880
|
-
const relations = Object.fromEntries(Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));
|
|
1881
|
-
// Try properties first
|
|
1882
|
-
if (Object.keys(properties).length > 0) {
|
|
1883
|
-
const firstProp = properties[Object.keys(properties)[0]];
|
|
1884
|
-
if (firstProp.through) {
|
|
1885
|
-
const match = firstProp.through.match(/^([^:]+:\/\/)/);
|
|
1886
|
-
if (match) {
|
|
1887
|
-
namespace = match[1];
|
|
1888
|
-
}
|
|
1889
|
-
}
|
|
1890
|
-
}
|
|
1891
|
-
// Fall back to relations if no properties
|
|
1892
|
-
else if (Object.keys(relations).length > 0) {
|
|
1893
|
-
const firstRel = relations[Object.keys(relations)[0]];
|
|
1894
|
-
if (firstRel.predicate) {
|
|
1895
|
-
const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
|
|
1896
|
-
if (match) {
|
|
1897
|
-
namespace = match[1];
|
|
1898
|
-
}
|
|
1899
|
-
}
|
|
1900
|
-
}
|
|
1901
|
-
// ── Create SHACL shape ──────────────────────────────────────────────
|
|
1902
|
-
const shapeUri = `${namespace}${subjectName}Shape`;
|
|
1903
|
-
const targetClass = `${namespace}${subjectName}`;
|
|
1904
|
-
const shape = new SHACLShape(shapeUri, targetClass);
|
|
1905
|
-
// Detect @Model inheritance — if the parent class also has
|
|
1906
|
-
// generateSHACL it is itself a @Model and we reference its shape
|
|
1907
|
-
// via sh:node so SHACL validators can walk the hierarchy.
|
|
1908
|
-
const parentCtor = Object.getPrototypeOf(target);
|
|
1909
|
-
if (parentCtor && typeof parentCtor.generateSHACL === 'function') {
|
|
1910
|
-
const parentSHACL = parentCtor.generateSHACL();
|
|
1911
|
-
if (parentSHACL?.shape?.nodeShapeUri) {
|
|
1912
|
-
shape.addParentShape(parentSHACL.shape.nodeShapeUri);
|
|
1817
|
+
// ── Create SHACL shape ──────────────────────────────────────────────
|
|
1818
|
+
const shapeUri = `${namespace}${subjectName}Shape`;
|
|
1819
|
+
const targetClass = `${namespace}${subjectName}`;
|
|
1820
|
+
const shape = new SHACLShape(shapeUri, targetClass);
|
|
1821
|
+
// Detect @Model inheritance — if the parent class also has
|
|
1822
|
+
// generateSHACL it is itself a @Model and we reference its shape
|
|
1823
|
+
// via sh:node so SHACL validators can walk the hierarchy.
|
|
1824
|
+
const parentCtor = Object.getPrototypeOf(target);
|
|
1825
|
+
if (parentCtor && typeof parentCtor.generateSHACL === 'function') {
|
|
1826
|
+
const parentSHACL = parentCtor.generateSHACL();
|
|
1827
|
+
if (parentSHACL?.shape?.nodeShapeUri) {
|
|
1828
|
+
shape.addParentShape(parentSHACL.shape.nodeShapeUri);
|
|
1913
1829
|
}
|
|
1914
1830
|
}
|
|
1915
1831
|
// ── Constructor / Destructor actions ────────────────────────────────
|
|
@@ -1964,9 +1880,19 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
|
|
|
1964
1880
|
if (propMeta.writable !== undefined) {
|
|
1965
1881
|
propShape.writable = propMeta.writable;
|
|
1966
1882
|
}
|
|
1967
|
-
if (propMeta.resolveLanguage) {
|
|
1883
|
+
if (propMeta.resolveLanguage != null) {
|
|
1968
1884
|
propShape.resolveLanguage = propMeta.resolveLanguage;
|
|
1969
1885
|
}
|
|
1886
|
+
// Explicit getter SPARQL — the executor evaluates this when
|
|
1887
|
+
// hydrating the property, in addition to (or instead of)
|
|
1888
|
+
// reading raw links via `propMeta.through`.
|
|
1889
|
+
if (propMeta.getter) {
|
|
1890
|
+
propShape.getter = propMeta.getter;
|
|
1891
|
+
}
|
|
1892
|
+
// Serializable transform expression (SHACL-AF Node Expression)
|
|
1893
|
+
if (propMeta.transform) {
|
|
1894
|
+
propShape.transform = propMeta.transform;
|
|
1895
|
+
}
|
|
1970
1896
|
// ── Setter actions ──────────────────────────────────────────────
|
|
1971
1897
|
if (propMeta.prologSetter) {
|
|
1972
1898
|
console.warn(`[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
|
|
@@ -2005,63 +1931,82 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
|
|
|
2005
1931
|
shape.addProperty(propShape);
|
|
2006
1932
|
}
|
|
2007
1933
|
// ── Convert relations to SHACL property shapes ─────────────────────
|
|
2008
|
-
for (const relName in
|
|
2009
|
-
const relMeta =
|
|
2010
|
-
|
|
1934
|
+
for (const relName in allRelationsMeta) {
|
|
1935
|
+
const relMeta = allRelationsMeta[relName];
|
|
1936
|
+
// Getter-only relations (no `through`) have no real link predicate
|
|
1937
|
+
// but still need a SHACL property entry so the executor can find
|
|
1938
|
+
// the getter expression. Synthesize a deterministic IRI so the
|
|
1939
|
+
// SHACL graph is well-formed; the predicate is never used to match
|
|
1940
|
+
// links because the getter is the sole source of values. Use
|
|
1941
|
+
// slash separators so the result is a valid IRI (colons in the
|
|
1942
|
+
// authority confuse strict SPARQL IRI parsers).
|
|
1943
|
+
if (!relMeta.predicate && !relMeta.getter)
|
|
2011
1944
|
continue;
|
|
1945
|
+
const synthesizedPath = relMeta.predicate
|
|
1946
|
+
|| `ad4m://getter/${subjectName}/${relName}`;
|
|
2012
1947
|
const relShape = {
|
|
2013
1948
|
name: relName,
|
|
2014
|
-
path:
|
|
1949
|
+
path: synthesizedPath,
|
|
2015
1950
|
};
|
|
2016
1951
|
// Relations typically contain IRIs
|
|
2017
1952
|
relShape.nodeKind = 'IRI';
|
|
1953
|
+
// Encode relation kind so the executor can derive direction and
|
|
1954
|
+
// scalar-vs-collection rendering without consulting the JS class.
|
|
1955
|
+
relShape.relationKind = relMeta.kind;
|
|
1956
|
+
// Scalar relations cap at 1.
|
|
1957
|
+
if (relMeta.kind === 'hasOne' || relMeta.kind === 'belongsToOne') {
|
|
1958
|
+
relShape.maxCount = 1;
|
|
1959
|
+
}
|
|
1960
|
+
else if (relMeta.maxCount !== undefined) {
|
|
1961
|
+
relShape.maxCount = relMeta.maxCount;
|
|
1962
|
+
}
|
|
1963
|
+
// Encode opt-out of type filtering (default true; only emit when false).
|
|
1964
|
+
if (relMeta.filter === false) {
|
|
1965
|
+
relShape.filter = false;
|
|
1966
|
+
}
|
|
2018
1967
|
// AD4M-specific metadata
|
|
2019
1968
|
if (relMeta.local !== undefined) {
|
|
2020
1969
|
relShape.local = relMeta.local;
|
|
2021
1970
|
}
|
|
2022
|
-
// Adder
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
1971
|
+
// Adder / Remover actions — only meaningful for relations backed
|
|
1972
|
+
// by a real link predicate. Getter-only relations are read-only.
|
|
1973
|
+
if (relMeta.predicate) {
|
|
1974
|
+
relShape.adder = [{
|
|
1975
|
+
action: "addLink",
|
|
1976
|
+
source: "this",
|
|
1977
|
+
predicate: relMeta.predicate,
|
|
1978
|
+
target: "value",
|
|
1979
|
+
...(relMeta.local && { local: true })
|
|
1980
|
+
}];
|
|
1981
|
+
relShape.remover = [{
|
|
1982
|
+
action: "removeLink",
|
|
1983
|
+
source: "this",
|
|
1984
|
+
predicate: relMeta.predicate,
|
|
1985
|
+
target: "value",
|
|
1986
|
+
...(relMeta.local && { local: true })
|
|
1987
|
+
}];
|
|
1988
|
+
}
|
|
2038
1989
|
// ── Build Getter (conformance filter) ───────────────────────────
|
|
2039
1990
|
// Priority chain:
|
|
2040
1991
|
// 1. Explicit getter string → use verbatim
|
|
2041
|
-
// 2.
|
|
2042
|
-
//
|
|
1992
|
+
// 2. target + filter !== false → auto-derive conformance getter
|
|
1993
|
+
// from the shape. Where-clause filtering is applied as a
|
|
1994
|
+
// post-getter pass via `whereFilter` / `wherePredicates`, which
|
|
1995
|
+
// use `parse_literal_value` and so transparently handle
|
|
1996
|
+
// `literal:json:` envelopes that simple FILTER(STR(?x) = ...)
|
|
1997
|
+
// comparisons can't.
|
|
2043
1998
|
if (relMeta.getter) {
|
|
2044
1999
|
relShape.getter = relMeta.getter;
|
|
2045
2000
|
}
|
|
2046
|
-
else if (relMeta.
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
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) {
|
|
2001
|
+
else if (relMeta.target
|
|
2002
|
+
&& relMeta.filter !== false
|
|
2003
|
+
&& relMeta.kind !== 'belongsToOne'
|
|
2004
|
+
&& relMeta.kind !== 'belongsToMany') {
|
|
2063
2005
|
// Lazy conformance filter: store deferred reference,
|
|
2064
|
-
// resolve on first access via a getter on relShape
|
|
2006
|
+
// resolve on first access via a getter on relShape.
|
|
2007
|
+
// Skipped for reverse relations (belongsTo*) because the
|
|
2008
|
+
// auto-derived getter assumes forward direction; the executor's
|
|
2009
|
+
// `resolve_reverse_relations` already populates these correctly.
|
|
2065
2010
|
const targetThunk = relMeta.target;
|
|
2066
2011
|
const predicate = relMeta.predicate;
|
|
2067
2012
|
let resolved = false;
|
|
@@ -2098,6 +2043,8 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
|
|
|
2098
2043
|
});
|
|
2099
2044
|
}
|
|
2100
2045
|
// ── sh:class — target shape reference ───────────────────────────
|
|
2046
|
+
// Also emit ad4m:targetClassName so the executor can look up the
|
|
2047
|
+
// target class shape through its in-memory cache by bare name.
|
|
2101
2048
|
if (relMeta.target) {
|
|
2102
2049
|
try {
|
|
2103
2050
|
const TargetClass = relMeta.target();
|
|
@@ -2105,9 +2052,54 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
|
|
|
2105
2052
|
if (targetSHACL?.shape?.nodeShapeUri) {
|
|
2106
2053
|
relShape.class = targetSHACL.shape.nodeShapeUri;
|
|
2107
2054
|
}
|
|
2055
|
+
if (targetSHACL?.name) {
|
|
2056
|
+
relShape.targetClassName = targetSHACL.name;
|
|
2057
|
+
}
|
|
2058
|
+
else {
|
|
2059
|
+
const targetProto = TargetClass.prototype;
|
|
2060
|
+
if (targetProto?.className) {
|
|
2061
|
+
relShape.targetClassName = targetProto.className;
|
|
2062
|
+
}
|
|
2063
|
+
}
|
|
2064
|
+
}
|
|
2065
|
+
catch (e) {
|
|
2066
|
+
// Target class resolution failed (typically a circular
|
|
2067
|
+
// decorator dependency). Since the executor no longer
|
|
2068
|
+
// receives target metadata over the wire, dropping the
|
|
2069
|
+
// reference here would turn a transient build-time issue
|
|
2070
|
+
// into a permanent broken-include at query time. Log
|
|
2071
|
+
// loudly so the failure is discoverable.
|
|
2072
|
+
console.warn(`[shacl-gen] Failed to resolve target class for relation `
|
|
2073
|
+
+ `"${subjectName}.${relName}": ${e instanceof Error ? e.message : String(e)}`);
|
|
2074
|
+
}
|
|
2075
|
+
}
|
|
2076
|
+
// ── Where-clause metadata for post-getter filtering ─────────────
|
|
2077
|
+
// The executor uses these to apply where conditions against the
|
|
2078
|
+
// target class without needing the target's ModelMetadata at query time.
|
|
2079
|
+
if (relMeta.where) {
|
|
2080
|
+
relShape.whereFilter = relMeta.where;
|
|
2081
|
+
try {
|
|
2082
|
+
const TargetClass = relMeta.target?.();
|
|
2083
|
+
const targetMetadata = TargetClass
|
|
2084
|
+
? TargetClass.getModelMetadata?.() ?? null
|
|
2085
|
+
: null;
|
|
2086
|
+
if (targetMetadata?.properties) {
|
|
2087
|
+
const predicates = {};
|
|
2088
|
+
for (const propName of Object.keys(relMeta.where)) {
|
|
2089
|
+
if (['id', 'author', 'timestamp'].includes(propName))
|
|
2090
|
+
continue;
|
|
2091
|
+
const propMeta = targetMetadata.properties[propName];
|
|
2092
|
+
if (propMeta?.predicate) {
|
|
2093
|
+
predicates[propName] = propMeta.predicate;
|
|
2094
|
+
}
|
|
2095
|
+
}
|
|
2096
|
+
if (Object.keys(predicates).length > 0) {
|
|
2097
|
+
relShape.wherePredicates = predicates;
|
|
2098
|
+
}
|
|
2099
|
+
}
|
|
2108
2100
|
}
|
|
2109
2101
|
catch (e) {
|
|
2110
|
-
// Target
|
|
2102
|
+
// Target metadata may not be available yet
|
|
2111
2103
|
}
|
|
2112
2104
|
}
|
|
2113
2105
|
shape.addProperty(relShape);
|
|
@@ -2125,6 +2117,58 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
|
|
|
2125
2117
|
};
|
|
2126
2118
|
}
|
|
2127
2119
|
|
|
2120
|
+
function formatList(list) {
|
|
2121
|
+
if (!list?.length) {
|
|
2122
|
+
return "";
|
|
2123
|
+
}
|
|
2124
|
+
if (list.length === 1) {
|
|
2125
|
+
return list.toString();
|
|
2126
|
+
}
|
|
2127
|
+
if (list.length === 2) {
|
|
2128
|
+
return list.join(' and ');
|
|
2129
|
+
}
|
|
2130
|
+
return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);
|
|
2131
|
+
}
|
|
2132
|
+
function capSentence(cap) {
|
|
2133
|
+
const can = cap.can.includes("*") ? ["READ", "WRITE", "UPDATE"] : cap.can;
|
|
2134
|
+
const domain = cap.with.domain === "*" ? "" : cap.with.domain;
|
|
2135
|
+
const pointers = cap.with.pointers.includes("*")
|
|
2136
|
+
? ["all AD4M data"]
|
|
2137
|
+
: cap.with.pointers;
|
|
2138
|
+
return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
|
|
2139
|
+
}
|
|
2140
|
+
/**
|
|
2141
|
+
* Escapes a string value for safe use in query strings.
|
|
2142
|
+
*
|
|
2143
|
+
* @description
|
|
2144
|
+
* Prevents SQL injection by properly escaping special characters in string values
|
|
2145
|
+
* that will be interpolated into query strings. This handles the most common
|
|
2146
|
+
* special characters that could break SQL queries or enable injection attacks.
|
|
2147
|
+
*
|
|
2148
|
+
* Single quotes, backslashes, and other special characters are escaped using
|
|
2149
|
+
* backslash notation, which is the standard escaping mechanism for query.
|
|
2150
|
+
*
|
|
2151
|
+
* @param value - The string value to escape
|
|
2152
|
+
* @returns The escaped string safe for query interpolation (without surrounding quotes)
|
|
2153
|
+
*
|
|
2154
|
+
* @example
|
|
2155
|
+
* ```typescript
|
|
2156
|
+
* const userInput = "user's input with 'quotes'";
|
|
2157
|
+
* const escaped = escapeQueryString(userInput);
|
|
2158
|
+
* const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
|
|
2159
|
+
* // Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''
|
|
2160
|
+
* ```
|
|
2161
|
+
*/
|
|
2162
|
+
function escapeQueryString(value) {
|
|
2163
|
+
return value
|
|
2164
|
+
.replace(/\\/g, '\\\\') // Backslash -> \\
|
|
2165
|
+
.replace(/'/g, "\\'") // Single quote -> \'
|
|
2166
|
+
.replace(/"/g, '\\"') // Double quote -> \"
|
|
2167
|
+
.replace(/\n/g, '\\n') // Newline -> \n
|
|
2168
|
+
.replace(/\r/g, '\\r') // Carriage return -> \r
|
|
2169
|
+
.replace(/\t/g, '\\t'); // Tab -> \t
|
|
2170
|
+
}
|
|
2171
|
+
|
|
2128
2172
|
/** Registry of property metadata keyed by constructor → { propName → metadata } */
|
|
2129
2173
|
const propertyRegistry = new WeakMap();
|
|
2130
2174
|
/** Registry of relation metadata keyed by constructor → { propName → metadata } */
|
|
@@ -3741,13 +3785,16 @@ class PerspectiveProxy {
|
|
|
3741
3785
|
/**
|
|
3742
3786
|
* Execute a model query — the executor-side replacement for SPARQL query building + JS hydration.
|
|
3743
3787
|
*
|
|
3788
|
+
* The executor resolves the model's shape from the perspective's SHACL
|
|
3789
|
+
* triples (written by `addSdna`). Callers no longer ship shape
|
|
3790
|
+
* metadata with the query; the perspective is the source of truth.
|
|
3791
|
+
*
|
|
3744
3792
|
* @param className - The model class name (e.g. "Recipe")
|
|
3745
3793
|
* @param queryJson - Structured query as JSON string
|
|
3746
|
-
* @param shapeJson - Optional shape metadata JSON from the model class
|
|
3747
3794
|
* @returns Object with `instances` array and `totalCount`
|
|
3748
3795
|
*/
|
|
3749
|
-
async modelQuery(className, queryJson
|
|
3750
|
-
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson
|
|
3796
|
+
async modelQuery(className, queryJson) {
|
|
3797
|
+
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
|
|
3751
3798
|
}
|
|
3752
3799
|
/**
|
|
3753
3800
|
* Evaluate property getters for a batch of instances in a single RPC call.
|
|
@@ -3758,12 +3805,11 @@ class PerspectiveProxy {
|
|
|
3758
3805
|
*
|
|
3759
3806
|
* @param className - The model class name (e.g. "Message")
|
|
3760
3807
|
* @param instanceIds - Array of instance base expression URIs
|
|
3761
|
-
* @param shapeJson - Shape metadata JSON from the model class
|
|
3762
3808
|
* @param propertyNames - Optional subset of property names to evaluate
|
|
3763
3809
|
* @returns Map of instance ID → evaluated property values
|
|
3764
3810
|
*/
|
|
3765
|
-
async evaluateGetters(className, instanceIds,
|
|
3766
|
-
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds,
|
|
3811
|
+
async evaluateGetters(className, instanceIds, propertyNames) {
|
|
3812
|
+
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds, propertyNames);
|
|
3767
3813
|
}
|
|
3768
3814
|
/**
|
|
3769
3815
|
* Subscribe to model query changes. Builds trigger SPARQL from the model shape
|
|
@@ -3775,11 +3821,10 @@ class PerspectiveProxy {
|
|
|
3775
3821
|
*
|
|
3776
3822
|
* @param className - The model class name
|
|
3777
3823
|
* @param queryJson - JSON-serialized query parameters (same as modelQuery)
|
|
3778
|
-
* @param shapeJson - Optional shape metadata JSON from the model class
|
|
3779
3824
|
* @returns Object with `subscriptionId` and initial `result`
|
|
3780
3825
|
*/
|
|
3781
|
-
async modelSubscribe(className, queryJson
|
|
3782
|
-
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelSubscribe(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson
|
|
3826
|
+
async modelSubscribe(className, queryJson) {
|
|
3827
|
+
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelSubscribe(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
|
|
3783
3828
|
}
|
|
3784
3829
|
/**
|
|
3785
3830
|
* Adds a new link to the perspective.
|
|
@@ -5421,22 +5466,21 @@ class PerspectiveClient {
|
|
|
5421
5466
|
}
|
|
5422
5467
|
return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.disposeQuery', { uuid, subscriptionId });
|
|
5423
5468
|
}
|
|
5424
|
-
async modelQuery(uuid, className, queryJson
|
|
5425
|
-
const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson
|
|
5469
|
+
async modelQuery(uuid, className, queryJson) {
|
|
5470
|
+
const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson });
|
|
5426
5471
|
return JSON.parse(resultJson);
|
|
5427
5472
|
}
|
|
5428
|
-
async evaluateGetters(uuid, className, instanceIds,
|
|
5473
|
+
async evaluateGetters(uuid, className, instanceIds, propertyNames) {
|
|
5429
5474
|
const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.evaluateGetters', {
|
|
5430
5475
|
uuid,
|
|
5431
5476
|
class_name: className,
|
|
5432
5477
|
instance_ids: instanceIds,
|
|
5433
|
-
shape_json: shapeJson,
|
|
5434
5478
|
...(propertyNames && { property_names: propertyNames }),
|
|
5435
5479
|
});
|
|
5436
5480
|
return JSON.parse(resultJson);
|
|
5437
5481
|
}
|
|
5438
|
-
async modelSubscribe(uuid, className, queryJson
|
|
5439
|
-
const response = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson
|
|
5482
|
+
async modelSubscribe(uuid, className, queryJson) {
|
|
5483
|
+
const response = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson });
|
|
5440
5484
|
return {
|
|
5441
5485
|
subscriptionId: response.subscription_id,
|
|
5442
5486
|
result: JSON.parse(response.result)
|
|
@@ -13831,7 +13875,7 @@ class AIClient {
|
|
|
13831
13875
|
// Use slice to get only the relevant portion of the underlying ArrayBuffer
|
|
13832
13876
|
// (Float32Array may be a view over a larger buffer)
|
|
13833
13877
|
const bodyBuffer = typedAudio.buffer.slice(typedAudio.byteOffset, typedAudio.byteOffset + typedAudio.byteLength);
|
|
13834
|
-
const response = await
|
|
13878
|
+
const response = await __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").doFetch(`${baseUrl}/api/v1/ai/transcription/feed`, {
|
|
13835
13879
|
method: 'POST',
|
|
13836
13880
|
headers: {
|
|
13837
13881
|
'Content-Type': 'application/octet-stream',
|
|
@@ -14907,13 +14951,6 @@ class ModelQueryBuilder {
|
|
|
14907
14951
|
this.modelClassName = className;
|
|
14908
14952
|
return this;
|
|
14909
14953
|
}
|
|
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
14954
|
/**
|
|
14918
14955
|
* Executes the query once and returns the results.
|
|
14919
14956
|
*
|
|
@@ -14995,23 +15032,18 @@ class ModelQueryBuilder {
|
|
|
14995
15032
|
// Clean up any existing subscription
|
|
14996
15033
|
this.dispose();
|
|
14997
15034
|
const ctor = this.ctor;
|
|
14998
|
-
// Build the model query params (className, queryJson
|
|
14999
|
-
|
|
15035
|
+
// Build the model query params (className, queryJson). The executor
|
|
15036
|
+
// resolves the shape from the perspective's SHACL triples.
|
|
15037
|
+
const { className, queryJson } = ctor.prepareModelQueryParams(this.queryParams, this.modelClassName);
|
|
15000
15038
|
// Register model subscription via Rust — this builds trigger SPARQL internally,
|
|
15001
15039
|
// registers the subscription, and runs the initial query in one call.
|
|
15002
|
-
const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson
|
|
15040
|
+
const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson);
|
|
15003
15041
|
// Convert JSON instances to model class instances
|
|
15004
15042
|
const parseResults = (raw) => {
|
|
15005
15043
|
return ctor.parseModelResult(this.perspective, raw, this.queryParams.include, this.queryParams.properties);
|
|
15006
15044
|
};
|
|
15007
|
-
//
|
|
15008
|
-
|
|
15009
|
-
const resolveAndReturn = async (instances) => {
|
|
15010
|
-
await ctor.resolveNonLiteralProps(this.perspective, instances);
|
|
15011
|
-
return instances;
|
|
15012
|
-
};
|
|
15013
|
-
// Parse initial results (with non-literal resolution)
|
|
15014
|
-
const initialResults = await resolveAndReturn(parseResults(initialModelResult));
|
|
15045
|
+
// Transforms are now applied by the Rust executor during hydration
|
|
15046
|
+
const initialResults = parseResults(initialModelResult);
|
|
15015
15047
|
// Track last emitted result fingerprint to suppress duplicate callbacks
|
|
15016
15048
|
let lastResultFingerprint = null;
|
|
15017
15049
|
const buildFingerprint = (results) => {
|
|
@@ -15024,20 +15056,16 @@ class ModelQueryBuilder {
|
|
|
15024
15056
|
// When Rust re-runs the model query and finds changed results, it pushes them.
|
|
15025
15057
|
const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
|
|
15026
15058
|
try {
|
|
15027
|
-
const
|
|
15028
|
-
console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${
|
|
15029
|
-
|
|
15030
|
-
|
|
15031
|
-
|
|
15032
|
-
|
|
15033
|
-
|
|
15034
|
-
|
|
15035
|
-
|
|
15036
|
-
|
|
15037
|
-
callback(results);
|
|
15038
|
-
}).catch((e) => {
|
|
15039
|
-
console.error('Model subscription update resolve error:', e);
|
|
15040
|
-
});
|
|
15059
|
+
const results = parseResults(rawResult);
|
|
15060
|
+
console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${results.length} instances`);
|
|
15061
|
+
const fp = buildFingerprint(results);
|
|
15062
|
+
if (fp === lastResultFingerprint) {
|
|
15063
|
+
console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);
|
|
15064
|
+
return;
|
|
15065
|
+
}
|
|
15066
|
+
console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);
|
|
15067
|
+
lastResultFingerprint = fp;
|
|
15068
|
+
callback(results);
|
|
15041
15069
|
}
|
|
15042
15070
|
catch (e) {
|
|
15043
15071
|
console.error('Model subscription update parse error:', e);
|
|
@@ -15159,8 +15187,8 @@ class ModelQueryBuilder {
|
|
|
15159
15187
|
// Clean up any existing subscription
|
|
15160
15188
|
this.dispose();
|
|
15161
15189
|
const countParams = { ...this.queryParams, limit: 0 };
|
|
15162
|
-
const { className, queryJson
|
|
15163
|
-
const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson
|
|
15190
|
+
const { className, queryJson } = this.ctor.prepareModelQueryParams(countParams, this.modelClassName);
|
|
15191
|
+
const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson);
|
|
15164
15192
|
const parseCount = (raw) => {
|
|
15165
15193
|
const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
|
|
15166
15194
|
return data.totalCount ?? 0;
|
|
@@ -15295,8 +15323,8 @@ class ModelQueryBuilder {
|
|
|
15295
15323
|
const subscriptionParams = { ...(this.queryParams || {}) };
|
|
15296
15324
|
delete subscriptionParams.limit;
|
|
15297
15325
|
delete subscriptionParams.offset;
|
|
15298
|
-
const { className, queryJson
|
|
15299
|
-
const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson
|
|
15326
|
+
const { className, queryJson } = ctor.prepareModelQueryParams(subscriptionParams, this.modelClassName);
|
|
15327
|
+
const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson);
|
|
15300
15328
|
// Build the paginated query for Rust endpoint (count: true fetches both results and totalCount in one call)
|
|
15301
15329
|
const paginatedQuery = {
|
|
15302
15330
|
...(this.queryParams || {}),
|
|
@@ -15393,94 +15421,12 @@ function normalizeValue(value) {
|
|
|
15393
15421
|
}
|
|
15394
15422
|
|
|
15395
15423
|
// ---------------------------------------------------------------------------
|
|
15396
|
-
//
|
|
15424
|
+
// Helpers for Rust-side include resolution
|
|
15397
15425
|
// ---------------------------------------------------------------------------
|
|
15398
15426
|
/**
|
|
15399
|
-
*
|
|
15400
|
-
*
|
|
15401
|
-
*
|
|
15402
|
-
* (e.g. it was synthesised from a SHACL shape at runtime) we still want to
|
|
15403
|
-
* decode the content rather than passing raw `FileData` to callers.
|
|
15404
|
-
*
|
|
15405
|
-
* Decoding rules (mirrors the JS `decodeFileAsJson` / `decodeFileAsString` helpers):
|
|
15406
|
-
* - `application/json` (default when `file_type` is absent) → JSON.parse
|
|
15407
|
-
* - anything else → raw decoded string
|
|
15408
|
-
*
|
|
15409
|
-
* If `resolved` is not a `FileData` object the value is returned unchanged so
|
|
15410
|
-
* that callers can use this as a safe unconditional fallback.
|
|
15411
|
-
*/
|
|
15412
|
-
function defaultFileDecode(resolved) {
|
|
15413
|
-
if (resolved !== null &&
|
|
15414
|
-
typeof resolved === 'object' &&
|
|
15415
|
-
'data_base64' in resolved) {
|
|
15416
|
-
const fd = resolved;
|
|
15417
|
-
let raw;
|
|
15418
|
-
try {
|
|
15419
|
-
raw = atob(fd.data_base64);
|
|
15420
|
-
}
|
|
15421
|
-
catch {
|
|
15422
|
-
return resolved; // malformed base64 — keep as-is
|
|
15423
|
-
}
|
|
15424
|
-
const isJson = !fd.file_type || fd.file_type === 'application/json';
|
|
15425
|
-
if (isJson) {
|
|
15426
|
-
try {
|
|
15427
|
-
return JSON.parse(raw);
|
|
15428
|
-
}
|
|
15429
|
-
catch {
|
|
15430
|
-
return raw;
|
|
15431
|
-
}
|
|
15432
|
-
}
|
|
15433
|
-
return raw;
|
|
15434
|
-
}
|
|
15435
|
-
return resolved;
|
|
15436
|
-
}
|
|
15437
|
-
// ---------------------------------------------------------------------------
|
|
15438
|
-
// Helpers for Rust-side include resolution
|
|
15439
|
-
// ---------------------------------------------------------------------------
|
|
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
|
-
/**
|
|
15481
|
-
* Construct a model class instance from a plain JSON object returned by the
|
|
15482
|
-
* Rust endpoint. Recursively converts included relation values (which come
|
|
15483
|
-
* back as plain JSON objects) into proper model class instances.
|
|
15427
|
+
* Construct a model class instance from a plain JSON object returned by the
|
|
15428
|
+
* Rust endpoint. Recursively converts included relation values (which come
|
|
15429
|
+
* back as plain JSON objects) into proper model class instances.
|
|
15484
15430
|
*/
|
|
15485
15431
|
function jsonToModelInstance(ModelClass, perspective, json, include, properties) {
|
|
15486
15432
|
const instance = new ModelClass(perspective, json.id || json.baseExpression);
|
|
@@ -15521,24 +15467,6 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
|
|
|
15521
15467
|
}
|
|
15522
15468
|
instance[key] = value;
|
|
15523
15469
|
}
|
|
15524
|
-
// Apply property transform functions from decorators (only for literal-resolved
|
|
15525
|
-
// or no-resolveLanguage properties; non-literal properties are resolved + transformed
|
|
15526
|
-
// asynchronously in executeModelQuery).
|
|
15527
|
-
try {
|
|
15528
|
-
const propsMeta = getPropertiesMetadata(ModelClass);
|
|
15529
|
-
for (const [propName, opts] of Object.entries(propsMeta)) {
|
|
15530
|
-
const o = opts;
|
|
15531
|
-
if (typeof o.transform !== 'function' || !(propName in json))
|
|
15532
|
-
continue;
|
|
15533
|
-
// Skip non-literal resolveLanguage props — they need async expression resolution first
|
|
15534
|
-
if (o.resolveLanguage != null && o.resolveLanguage !== 'literal')
|
|
15535
|
-
continue;
|
|
15536
|
-
instance[propName] = o.transform(instance[propName]);
|
|
15537
|
-
}
|
|
15538
|
-
}
|
|
15539
|
-
catch (e) {
|
|
15540
|
-
console.debug('jsonToModelInstance: transform metadata unavailable:', e);
|
|
15541
|
-
}
|
|
15542
15470
|
// Recursively convert included relation values to class instances
|
|
15543
15471
|
if (include) {
|
|
15544
15472
|
const relMeta = getRelationsMetadata(ModelClass);
|
|
@@ -15776,8 +15704,8 @@ class Ad4mModel {
|
|
|
15776
15704
|
...(options.getter !== undefined && { getter: options.getter }),
|
|
15777
15705
|
...(options.prologSetter !== undefined && { prologSetter: options.prologSetter }),
|
|
15778
15706
|
...(options.local !== undefined && { local: options.local }),
|
|
15779
|
-
...(options.
|
|
15780
|
-
...(options.
|
|
15707
|
+
...(options.flag !== undefined && { flag: options.flag }),
|
|
15708
|
+
...(options.transform !== undefined && { transform: options.transform })
|
|
15781
15709
|
};
|
|
15782
15710
|
}
|
|
15783
15711
|
// Extract relations (relations) from WeakMap registry
|
|
@@ -16158,7 +16086,8 @@ class Ad4mModel {
|
|
|
16158
16086
|
}
|
|
16159
16087
|
/**
|
|
16160
16088
|
* Build the JSON parameters needed for a model query/subscription endpoint.
|
|
16161
|
-
* Returns the className
|
|
16089
|
+
* Returns the className and queryJson that the Rust executor expects.
|
|
16090
|
+
* Shape resolution happens server-side from the perspective's SHACL triples.
|
|
16162
16091
|
* @internal
|
|
16163
16092
|
*/
|
|
16164
16093
|
static prepareModelQueryParams(query = {}, classNameOverride) {
|
|
@@ -16198,16 +16127,18 @@ class Ad4mModel {
|
|
|
16198
16127
|
if (Object.keys(normalIncludes).length > 0)
|
|
16199
16128
|
queryInput.include = normalIncludes;
|
|
16200
16129
|
if (Object.keys(projections).length > 0) {
|
|
16201
|
-
//
|
|
16130
|
+
// Tag each projection with its target class name so the executor can
|
|
16131
|
+
// resolve the target shape through its in-memory cache when applying
|
|
16132
|
+
// projection where-clause filters.
|
|
16202
16133
|
const allRelMeta = getRelationsMetadata(this);
|
|
16203
16134
|
for (const [, proj] of Object.entries(projections)) {
|
|
16204
16135
|
const relMeta = allRelMeta[proj.from];
|
|
16205
|
-
if (!proj.
|
|
16136
|
+
if (!proj.targetClassName && relMeta?.target) {
|
|
16206
16137
|
try {
|
|
16207
16138
|
const TargetClass = relMeta.target();
|
|
16208
16139
|
const targetMeta = TargetClass.getModelMetadata?.();
|
|
16209
|
-
if (targetMeta) {
|
|
16210
|
-
proj.
|
|
16140
|
+
if (targetMeta?.className) {
|
|
16141
|
+
proj.targetClassName = targetMeta.className;
|
|
16211
16142
|
}
|
|
16212
16143
|
}
|
|
16213
16144
|
catch (e) {
|
|
@@ -16230,64 +16161,12 @@ class Ad4mModel {
|
|
|
16230
16161
|
if (query.count !== undefined)
|
|
16231
16162
|
queryInput.count = query.count;
|
|
16232
16163
|
queryInput.deepQuery = query.deepQuery ?? true;
|
|
16233
|
-
|
|
16234
|
-
|
|
16235
|
-
|
|
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
|
-
}
|
|
16164
|
+
// Conformance getters, where filters, and target shapes for includes
|
|
16165
|
+
// are all resolved by the executor from the perspective's SHACL triples
|
|
16166
|
+
// — no client-side pre-computation is needed any more.
|
|
16287
16167
|
return {
|
|
16288
16168
|
className,
|
|
16289
16169
|
queryJson: JSON.stringify(queryInput),
|
|
16290
|
-
shapeJson: JSON.stringify(metadata),
|
|
16291
16170
|
metadata,
|
|
16292
16171
|
};
|
|
16293
16172
|
}
|
|
@@ -16303,57 +16182,6 @@ class Ad4mModel {
|
|
|
16303
16182
|
return [];
|
|
16304
16183
|
return arr.map((json) => jsonToModelInstance(this, perspective, json, include, properties));
|
|
16305
16184
|
}
|
|
16306
|
-
/**
|
|
16307
|
-
* Resolve non-literal (file-language) properties on an array of already-constructed
|
|
16308
|
-
* model instances. Handles two cases:
|
|
16309
|
-
*
|
|
16310
|
-
* 1. The Rust executor returned a raw URI string → fetch via `getExpression` then apply transform.
|
|
16311
|
-
* 2. The Rust executor already resolved the expression and returned a `FileData` object
|
|
16312
|
-
* (happens when the perspective backend eagerly fetches file content) → apply transform
|
|
16313
|
-
* (or `defaultFileDecode` if no transform is registered on the class, e.g. for SHACL-
|
|
16314
|
-
* synthesised model classes).
|
|
16315
|
-
*
|
|
16316
|
-
* Extracted as a public static so `ModelQueryBuilder.subscribe()` can reuse it without
|
|
16317
|
-
* duplicating logic or introducing a circular dependency.
|
|
16318
|
-
* @internal
|
|
16319
|
-
*/
|
|
16320
|
-
static async resolveNonLiteralProps(perspective, instances) {
|
|
16321
|
-
const propsMeta = getPropertiesMetadata(this);
|
|
16322
|
-
const resolveProps = Object.entries(propsMeta).filter(([, opts]) => opts.resolveLanguage != null &&
|
|
16323
|
-
opts.resolveLanguage !== 'literal');
|
|
16324
|
-
if (resolveProps.length === 0)
|
|
16325
|
-
return;
|
|
16326
|
-
await Promise.all(instances.map(async (inst) => {
|
|
16327
|
-
for (const [propName, opts] of resolveProps) {
|
|
16328
|
-
const val = inst[propName];
|
|
16329
|
-
const transform = opts.transform;
|
|
16330
|
-
const applyTransform = (resolved) => typeof transform === 'function' ? transform(resolved) : defaultFileDecode(resolved);
|
|
16331
|
-
if (typeof val === 'string' && val && !val.startsWith('literal:')) {
|
|
16332
|
-
// Case 1: raw URI — fetch from language runtime
|
|
16333
|
-
try {
|
|
16334
|
-
const expression = await perspective.getExpression(val);
|
|
16335
|
-
if (expression) {
|
|
16336
|
-
let resolved;
|
|
16337
|
-
try {
|
|
16338
|
-
resolved = JSON.parse(expression.data);
|
|
16339
|
-
}
|
|
16340
|
-
catch {
|
|
16341
|
-
resolved = expression.data;
|
|
16342
|
-
}
|
|
16343
|
-
inst[propName] = applyTransform(resolved);
|
|
16344
|
-
}
|
|
16345
|
-
}
|
|
16346
|
-
catch (e) {
|
|
16347
|
-
console.debug(`resolveNonLiteralProps: resolution failed for '${propName}':`, e);
|
|
16348
|
-
}
|
|
16349
|
-
}
|
|
16350
|
-
else if (val !== null && val !== undefined && typeof val === 'object') {
|
|
16351
|
-
// Case 2: already resolved by Rust — apply transform / default decode
|
|
16352
|
-
inst[propName] = applyTransform(val);
|
|
16353
|
-
}
|
|
16354
|
-
}
|
|
16355
|
-
}));
|
|
16356
|
-
}
|
|
16357
16185
|
// instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
|
|
16358
16186
|
/**
|
|
16359
16187
|
* Execute a model query via the executor-side endpoint.
|
|
@@ -16364,20 +16192,15 @@ class Ad4mModel {
|
|
|
16364
16192
|
* @internal
|
|
16365
16193
|
*/
|
|
16366
16194
|
static async executeModelQuery(perspective, query = {}, classNameOverride) {
|
|
16367
|
-
// Delegate
|
|
16368
|
-
//
|
|
16369
|
-
const { className, queryJson
|
|
16370
|
-
const result = await perspective.modelQuery(className, queryJson
|
|
16195
|
+
// Delegate query input building to the shared prepareModelQueryParams
|
|
16196
|
+
// helper. The executor resolves the shape from SHACL server-side.
|
|
16197
|
+
const { className, queryJson } = this.prepareModelQueryParams(query, classNameOverride);
|
|
16198
|
+
const result = await perspective.modelQuery(className, queryJson);
|
|
16371
16199
|
// Convert JSON instances to model class instances, recursively constructing
|
|
16372
16200
|
// class instances for any included relations resolved by Rust.
|
|
16373
16201
|
const instances = result.instances.map((json) => {
|
|
16374
16202
|
return jsonToModelInstance(this, perspective, json, query.include, query.properties);
|
|
16375
16203
|
});
|
|
16376
|
-
// Resolve non-literal expressions (e.g. file languages where the stored
|
|
16377
|
-
// value is a content-addressed hash that must be fetched from the language
|
|
16378
|
-
// runtime). The Rust endpoint may return either a raw target URI (string)
|
|
16379
|
-
// or an already-resolved FileData object — both cases are handled here.
|
|
16380
|
-
await this.resolveNonLiteralProps(perspective, instances);
|
|
16381
16204
|
// Take snapshots for dirty tracking (exclude $-prefixed projection keys)
|
|
16382
16205
|
const snapshotRelations = query.include
|
|
16383
16206
|
? Object.fromEntries(Object.entries(query.include).filter(([k]) => !k.startsWith('$')))
|
|
@@ -16413,13 +16236,12 @@ class Ad4mModel {
|
|
|
16413
16236
|
* });
|
|
16414
16237
|
* ```
|
|
16415
16238
|
*/
|
|
16416
|
-
static async findAll(perspective, query
|
|
16417
|
-
|
|
16418
|
-
|
|
16419
|
-
if (query.properties && query.properties.length === 0) {
|
|
16239
|
+
static async findAll(perspective, query) {
|
|
16240
|
+
const q = (query ?? {});
|
|
16241
|
+
if (q.properties && q.properties.length === 0) {
|
|
16420
16242
|
throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
|
|
16421
16243
|
}
|
|
16422
|
-
const { results } = await this.executeModelQuery(perspective,
|
|
16244
|
+
const { results } = await this.executeModelQuery(perspective, q);
|
|
16423
16245
|
return results;
|
|
16424
16246
|
}
|
|
16425
16247
|
/**
|
|
@@ -16442,10 +16264,8 @@ class Ad4mModel {
|
|
|
16442
16264
|
* }
|
|
16443
16265
|
* ```
|
|
16444
16266
|
*/
|
|
16445
|
-
static async findOne(perspective, query
|
|
16446
|
-
|
|
16447
|
-
_engine) {
|
|
16448
|
-
const limitedQuery = { ...query, limit: 1 };
|
|
16267
|
+
static async findOne(perspective, query) {
|
|
16268
|
+
const limitedQuery = { ...(query ?? {}), limit: 1 };
|
|
16449
16269
|
const results = await this.findAll(perspective, limitedQuery);
|
|
16450
16270
|
return results[0] ?? null;
|
|
16451
16271
|
}
|
|
@@ -16466,10 +16286,9 @@ class Ad4mModel {
|
|
|
16466
16286
|
* console.log(`Showing 10 of ${totalCount} dessert recipes`);
|
|
16467
16287
|
* ```
|
|
16468
16288
|
*/
|
|
16469
|
-
static async findAllAndCount(perspective, query
|
|
16470
|
-
|
|
16471
|
-
|
|
16472
|
-
return await this.executeModelQuery(perspective, query);
|
|
16289
|
+
static async findAllAndCount(perspective, query) {
|
|
16290
|
+
const out = await this.executeModelQuery(perspective, (query ?? {}));
|
|
16291
|
+
return out;
|
|
16473
16292
|
}
|
|
16474
16293
|
/**
|
|
16475
16294
|
* Helper function for pagination with explicit page size and number.
|
|
@@ -16488,12 +16307,10 @@ class Ad4mModel {
|
|
|
16488
16307
|
* console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
|
|
16489
16308
|
* ```
|
|
16490
16309
|
*/
|
|
16491
|
-
static async paginate(perspective, pageSize, pageNumber, query
|
|
16492
|
-
|
|
16493
|
-
_engine) {
|
|
16494
|
-
const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
16310
|
+
static async paginate(perspective, pageSize, pageNumber, query) {
|
|
16311
|
+
const paginationQuery = { ...(query ?? {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
16495
16312
|
const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
|
|
16496
|
-
return { results, totalCount, pageSize, pageNumber };
|
|
16313
|
+
return { results: results, totalCount, pageSize, pageNumber };
|
|
16497
16314
|
}
|
|
16498
16315
|
/**
|
|
16499
16316
|
* Generates a SPARQL COUNT query for the model.
|
|
@@ -16520,8 +16337,8 @@ class Ad4mModel {
|
|
|
16520
16337
|
* });
|
|
16521
16338
|
* ```
|
|
16522
16339
|
*/
|
|
16523
|
-
static async count(perspective, query
|
|
16524
|
-
const { totalCount } = await this.executeModelQuery(perspective, { ...query, limit: 0 });
|
|
16340
|
+
static async count(perspective, query) {
|
|
16341
|
+
const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 });
|
|
16525
16342
|
return totalCount;
|
|
16526
16343
|
}
|
|
16527
16344
|
async setProperty(key, value, batchId) {
|
|
@@ -16832,29 +16649,10 @@ class Ad4mModel {
|
|
|
16832
16649
|
if (instances.length === 0)
|
|
16833
16650
|
return;
|
|
16834
16651
|
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
16652
|
const instanceIds = instances.map(inst => inst.id || inst._baseExpression);
|
|
16856
|
-
//
|
|
16857
|
-
|
|
16653
|
+
// The executor reads getter SPARQL from the perspective's SHACL triples
|
|
16654
|
+
// (written by `addSdna`), so no shape JSON is shipped with the call.
|
|
16655
|
+
const result = await perspective.evaluateGetters(metadata.className, instanceIds, propertyNames);
|
|
16858
16656
|
// Determine which property names were evaluated for snapshot sync
|
|
16859
16657
|
const evaluatedPropertyNames = [];
|
|
16860
16658
|
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
@@ -17218,7 +17016,7 @@ class Ad4mModel {
|
|
|
17218
17016
|
* ```
|
|
17219
17017
|
*/
|
|
17220
17018
|
static query(perspective, query) {
|
|
17221
|
-
return new ModelQueryBuilder(perspective, this, query);
|
|
17019
|
+
return new ModelQueryBuilder(perspective, this, (query ?? {}));
|
|
17222
17020
|
}
|
|
17223
17021
|
/**
|
|
17224
17022
|
* Creates an Ad4mModel class from a JSON Schema definition.
|
|
@@ -17418,7 +17216,7 @@ class Ad4mClient {
|
|
|
17418
17216
|
_Ad4mClient_aiClient.set(this, void 0);
|
|
17419
17217
|
__classPrivateFieldSet$1(this, _Ad4mClient_baseUrl, baseUrl, "f");
|
|
17420
17218
|
__classPrivateFieldSet$1(this, _Ad4mClient_token, token, "f");
|
|
17421
|
-
__classPrivateFieldSet$1(this, _Ad4mClient_apiClient, new ApiClient(baseUrl, token, options?.webSocketImpl), "f");
|
|
17219
|
+
__classPrivateFieldSet$1(this, _Ad4mClient_apiClient, new ApiClient(baseUrl, token, options?.webSocketImpl, options?.fetchImpl), "f");
|
|
17422
17220
|
__classPrivateFieldSet$1(this, _Ad4mClient_agentClient, new AgentClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
|
|
17423
17221
|
__classPrivateFieldSet$1(this, _Ad4mClient_expressionClient, new ExpressionClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
|
|
17424
17222
|
__classPrivateFieldSet$1(this, _Ad4mClient_languageClient, new LanguageClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
|
|
@@ -17627,6 +17425,71 @@ class PerspectiveHandle {
|
|
|
17627
17425
|
}
|
|
17628
17426
|
}
|
|
17629
17427
|
|
|
17428
|
+
/**
|
|
17429
|
+
* SPARQL binding helpers — typed shapes and parsers for `querySparql<T>()`.
|
|
17430
|
+
*
|
|
17431
|
+
* AD4M stores non-string property values as URL-encoded `Literal` payloads
|
|
17432
|
+
* (see {@link Literal}). When raw SPARQL queries pull these values out of the
|
|
17433
|
+
* RDF store the bindings are still in encoded form; consumers must decode
|
|
17434
|
+
* before use. The helpers here centralise that decode step so each call site
|
|
17435
|
+
* can pick the variant matching its declared binding type.
|
|
17436
|
+
*
|
|
17437
|
+
* @example
|
|
17438
|
+
* ```ts
|
|
17439
|
+
* interface MessageBinding {
|
|
17440
|
+
* id: string;
|
|
17441
|
+
* timestamp: string; // raw literal — decode with parseLitNumber
|
|
17442
|
+
* body?: string; // raw literal — decode with parseLit
|
|
17443
|
+
* }
|
|
17444
|
+
* const rows = await perspective.querySparql<MessageBinding[]>(query);
|
|
17445
|
+
* const ts = parseLitNumber(rows[0].timestamp); // number
|
|
17446
|
+
* const body = rows[0].body ? parseLit(rows[0].body) : '';
|
|
17447
|
+
* ```
|
|
17448
|
+
*/
|
|
17449
|
+
/** Sum a SPARQL COUNT(?x) result down to a plain number (returns 0 on empty). */
|
|
17450
|
+
function parseSparqlCount(result) {
|
|
17451
|
+
if (!result || result.length === 0)
|
|
17452
|
+
return 0;
|
|
17453
|
+
const raw = result[0].count;
|
|
17454
|
+
const n = parseInt(raw, 10);
|
|
17455
|
+
return Number.isNaN(n) ? 0 : n;
|
|
17456
|
+
}
|
|
17457
|
+
/**
|
|
17458
|
+
* Decode a `Literal`-encoded SPARQL binding back to a plain string.
|
|
17459
|
+
*
|
|
17460
|
+
* Mirrors Flux's local `parseLit` helper. Returns `''` for `undefined`/empty
|
|
17461
|
+
* input. Falls through to the raw value if decoding fails (defensive — the
|
|
17462
|
+
* binding may already be a plain string for unwrapped properties).
|
|
17463
|
+
*/
|
|
17464
|
+
function parseLit(val) {
|
|
17465
|
+
if (val === undefined || val === null || val === '')
|
|
17466
|
+
return '';
|
|
17467
|
+
try {
|
|
17468
|
+
const result = Literal.fromUrl(val).get();
|
|
17469
|
+
if (result && typeof result === 'object') {
|
|
17470
|
+
return result.data ?? JSON.stringify(result);
|
|
17471
|
+
}
|
|
17472
|
+
return String(result);
|
|
17473
|
+
}
|
|
17474
|
+
catch {
|
|
17475
|
+
return val;
|
|
17476
|
+
}
|
|
17477
|
+
}
|
|
17478
|
+
/** Decode a `Literal`-encoded binding to a number. Returns 0 on empty/invalid input. */
|
|
17479
|
+
function parseLitNumber(val) {
|
|
17480
|
+
if (val === undefined || val === null || val === '')
|
|
17481
|
+
return 0;
|
|
17482
|
+
const decoded = parseLit(val);
|
|
17483
|
+
const n = Number(decoded);
|
|
17484
|
+
return Number.isNaN(n) ? 0 : n;
|
|
17485
|
+
}
|
|
17486
|
+
/** Decode a `Literal`-encoded binding to a boolean. Returns false on empty input. */
|
|
17487
|
+
function parseLitBoolean(val) {
|
|
17488
|
+
if (val === undefined || val === null || val === '')
|
|
17489
|
+
return false;
|
|
17490
|
+
return parseLit(val) === 'true';
|
|
17491
|
+
}
|
|
17492
|
+
|
|
17630
17493
|
/**
|
|
17631
17494
|
* WakerSubscriptionManager — manages live query subscriptions for the waker.
|
|
17632
17495
|
*
|
|
@@ -17913,6 +17776,195 @@ function isIncludeProjection(val) {
|
|
|
17913
17776
|
return typeof val === 'object' && val !== null && 'from' in val;
|
|
17914
17777
|
}
|
|
17915
17778
|
|
|
17779
|
+
/**
|
|
17780
|
+
* Shared query compilation utilities.
|
|
17781
|
+
*
|
|
17782
|
+
* These functions are used by both the runtime query builder (`Ad4mModel`) and
|
|
17783
|
+
* the compile-time SHACL generator (`decorators.ts`).
|
|
17784
|
+
*
|
|
17785
|
+
* All output uses native SPARQL syntax.
|
|
17786
|
+
*/
|
|
17787
|
+
/**
|
|
17788
|
+
* Format a JavaScript value for embedding in a query expression.
|
|
17789
|
+
*
|
|
17790
|
+
* - Strings are single-quoted with backslash / quote / newline escaping
|
|
17791
|
+
* - Numbers and booleans are passed through as-is
|
|
17792
|
+
* - Arrays are recursed
|
|
17793
|
+
*/
|
|
17794
|
+
function formatQueryValue(value) {
|
|
17795
|
+
if (typeof value === 'string') {
|
|
17796
|
+
// Escape backslashes first, then single quotes and other special characters
|
|
17797
|
+
const escaped = value
|
|
17798
|
+
.replace(/\\/g, '\\\\') // Backslash -> \\
|
|
17799
|
+
.replace(/'/g, "\\'") // Single quote -> \'
|
|
17800
|
+
.replace(/"/g, '\\"') // Double quote -> \"
|
|
17801
|
+
.replace(/\n/g, '\\n') // Newline -> \n
|
|
17802
|
+
.replace(/\r/g, '\\r') // Carriage return -> \r
|
|
17803
|
+
.replace(/\t/g, '\\t'); // Tab -> \t
|
|
17804
|
+
return `'${escaped}'`;
|
|
17805
|
+
}
|
|
17806
|
+
else if (typeof value === 'number' || typeof value === 'boolean') {
|
|
17807
|
+
return String(value);
|
|
17808
|
+
}
|
|
17809
|
+
else if (Array.isArray(value)) {
|
|
17810
|
+
return `[${value.map(v => formatQueryValue(v)).join(', ')}]`;
|
|
17811
|
+
}
|
|
17812
|
+
else {
|
|
17813
|
+
return String(value);
|
|
17814
|
+
}
|
|
17815
|
+
}
|
|
17816
|
+
/**
|
|
17817
|
+
* Compile a single Where condition for a property into a SPARQL triple pattern
|
|
17818
|
+
* that can be embedded in a getter's WHERE clause.
|
|
17819
|
+
*
|
|
17820
|
+
* The generated pattern operates on `?target` — e.g.:
|
|
17821
|
+
* `?target <pred> <value> .`
|
|
17822
|
+
* `FILTER EXISTS { ?target <pred> ?_v0 }`
|
|
17823
|
+
*
|
|
17824
|
+
* @param predicate - The predicate URI for the property
|
|
17825
|
+
* @param condition - The Where condition value
|
|
17826
|
+
* @param opts - Optional settings (e.g. `resolveLanguage`)
|
|
17827
|
+
* @returns A single SPARQL condition string
|
|
17828
|
+
*/
|
|
17829
|
+
function buildWhereCondition(predicate, condition, opts) {
|
|
17830
|
+
const escapedPredicate = escapeQueryString(predicate);
|
|
17831
|
+
// For literal-resolved properties, we match against the raw IRI (which is a literal: URI)
|
|
17832
|
+
// For language-resolved properties, we match against the plain URI
|
|
17833
|
+
// For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>
|
|
17834
|
+
// For language-resolved properties, values are plain URIs
|
|
17835
|
+
const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
|
|
17836
|
+
const varSuffix = opts?.varIndex ?? 0;
|
|
17837
|
+
function formatValue(v) {
|
|
17838
|
+
if (typeof v === 'string') {
|
|
17839
|
+
return isLiteral
|
|
17840
|
+
? `<literal:string:${escapeQueryString(v)}>`
|
|
17841
|
+
: `<${escapeQueryString(v)}>`;
|
|
17842
|
+
}
|
|
17843
|
+
// Numbers/booleans — also stored as literal:string: in AD4M
|
|
17844
|
+
return `<literal:string:${v}>`;
|
|
17845
|
+
}
|
|
17846
|
+
/**
|
|
17847
|
+
* For literal properties, generate a FILTER-based match that handles both
|
|
17848
|
+
* the raw value and the literal-encoded value. This mirrors the Rust
|
|
17849
|
+
* `build_projection_where_patterns` approach which uses:
|
|
17850
|
+
* FILTER(STR(?var) = "value" || STR(?var) = "literal:string:encodedValue")
|
|
17851
|
+
* This is more robust than exact IRI matching because it handles edge cases
|
|
17852
|
+
* where the stored format might vary.
|
|
17853
|
+
*/
|
|
17854
|
+
function formatLiteralFilter(varName, v) {
|
|
17855
|
+
const raw = escapeQueryString(String(v));
|
|
17856
|
+
const encoded = encodeURIComponent(String(v))
|
|
17857
|
+
.replace(/!/g, '%21')
|
|
17858
|
+
.replace(/'/g, '%27')
|
|
17859
|
+
.replace(/\(/g, '%28')
|
|
17860
|
+
.replace(/\)/g, '%29')
|
|
17861
|
+
.replace(/\*/g, '%2A');
|
|
17862
|
+
if (typeof v === 'string') {
|
|
17863
|
+
return `FILTER(STR(${varName}) = "${raw}" || STR(${varName}) = "literal:string:${encoded}")`;
|
|
17864
|
+
}
|
|
17865
|
+
else if (typeof v === 'number') {
|
|
17866
|
+
return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:number:${v}")`;
|
|
17867
|
+
}
|
|
17868
|
+
else if (typeof v === 'boolean') {
|
|
17869
|
+
return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:boolean:${v}")`;
|
|
17870
|
+
}
|
|
17871
|
+
return `FILTER(STR(${varName}) = "${raw}")`;
|
|
17872
|
+
}
|
|
17873
|
+
if (Array.isArray(condition)) {
|
|
17874
|
+
// Array values → FILTER IN
|
|
17875
|
+
if (isLiteral) {
|
|
17876
|
+
const varName = `?_wc${varSuffix}`;
|
|
17877
|
+
const inValues = condition.flatMap(v => {
|
|
17878
|
+
const raw = escapeQueryString(String(v));
|
|
17879
|
+
const encoded = encodeURIComponent(String(v))
|
|
17880
|
+
.replace(/!/g, '%21').replace(/'/g, '%27')
|
|
17881
|
+
.replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
|
|
17882
|
+
return [`"${raw}"`, `"literal:string:${encoded}"`];
|
|
17883
|
+
}).join(', ');
|
|
17884
|
+
return `?target <${escapedPredicate}> ${varName} . FILTER(STR(${varName}) IN (${inValues}))`;
|
|
17885
|
+
}
|
|
17886
|
+
const formattedValues = condition.map(formatValue).join(', ');
|
|
17887
|
+
return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;
|
|
17888
|
+
}
|
|
17889
|
+
else if (typeof condition === 'object' && condition !== null) {
|
|
17890
|
+
// Operator object
|
|
17891
|
+
const ops = condition;
|
|
17892
|
+
const parts = [];
|
|
17893
|
+
if (ops.not !== undefined) {
|
|
17894
|
+
if (Array.isArray(ops.not)) {
|
|
17895
|
+
const formattedValues = ops.not.map((v) => formatValue(v)).join(', ');
|
|
17896
|
+
// FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
|
|
17897
|
+
// so O(N²) behavior is bounded by the number of values for this property.
|
|
17898
|
+
parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ?_nval . FILTER(?_nval IN (${formattedValues})) }`);
|
|
17899
|
+
}
|
|
17900
|
+
else {
|
|
17901
|
+
// FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
|
|
17902
|
+
// so O(N²) behavior is bounded by the number of values for this property.
|
|
17903
|
+
parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ${formatValue(ops.not)} }`);
|
|
17904
|
+
}
|
|
17905
|
+
}
|
|
17906
|
+
// Comparison operators — ensure property exists
|
|
17907
|
+
const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
|
|
17908
|
+
ops.lt !== undefined || ops.lte !== undefined ||
|
|
17909
|
+
ops.between !== undefined || ops.contains !== undefined;
|
|
17910
|
+
if (hasComparisonOps) {
|
|
17911
|
+
parts.push(`FILTER EXISTS { ?target <${escapedPredicate}> ?_cmp }`);
|
|
17912
|
+
}
|
|
17913
|
+
return parts.join(' ');
|
|
17914
|
+
}
|
|
17915
|
+
else {
|
|
17916
|
+
// Simple equality
|
|
17917
|
+
if (isLiteral) {
|
|
17918
|
+
// Use FILTER matching (mirrors Rust build_projection_where_patterns)
|
|
17919
|
+
// to handle both raw values and literal-encoded IRIs robustly.
|
|
17920
|
+
const varName = `?_wc${varSuffix}`;
|
|
17921
|
+
return `?target <${escapedPredicate}> ${varName} . ${formatLiteralFilter(varName, condition)}`;
|
|
17922
|
+
}
|
|
17923
|
+
return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
|
|
17924
|
+
}
|
|
17925
|
+
}
|
|
17926
|
+
/**
|
|
17927
|
+
* Compile a full `Where` clause to an array of SPARQL condition strings.
|
|
17928
|
+
*
|
|
17929
|
+
* When `metadata` is provided, property names are resolved to predicates
|
|
17930
|
+
* using the model's property metadata. When `metadata` is `null`, property
|
|
17931
|
+
* names are treated as raw predicate URIs.
|
|
17932
|
+
*
|
|
17933
|
+
* Only handles **regular properties** — special fields (`id`, `author`,
|
|
17934
|
+
* `timestamp`) and relation fields are skipped (they are only relevant at
|
|
17935
|
+
* runtime query time, not for compile-time getter generation).
|
|
17936
|
+
*/
|
|
17937
|
+
function compileWhereClause(where, metadata) {
|
|
17938
|
+
const conditions = [];
|
|
17939
|
+
for (const [propertyName, condition] of Object.entries(where)) {
|
|
17940
|
+
// Skip special fields that don't apply at compile time
|
|
17941
|
+
if (['id', 'author', 'timestamp'].includes(propertyName))
|
|
17942
|
+
continue;
|
|
17943
|
+
let predicate;
|
|
17944
|
+
let resolveLanguage;
|
|
17945
|
+
if (metadata) {
|
|
17946
|
+
const propMeta = metadata.properties[propertyName];
|
|
17947
|
+
if (propMeta) {
|
|
17948
|
+
predicate = propMeta.predicate;
|
|
17949
|
+
resolveLanguage = propMeta.resolveLanguage;
|
|
17950
|
+
}
|
|
17951
|
+
else {
|
|
17952
|
+
// Property not found in metadata — treat name as raw predicate URI
|
|
17953
|
+
predicate = propertyName;
|
|
17954
|
+
}
|
|
17955
|
+
}
|
|
17956
|
+
else {
|
|
17957
|
+
// No metadata — treat name as raw predicate URI
|
|
17958
|
+
predicate = propertyName;
|
|
17959
|
+
}
|
|
17960
|
+
const cond = buildWhereCondition(predicate, condition, { resolveLanguage, varIndex: conditions.length });
|
|
17961
|
+
if (cond) {
|
|
17962
|
+
conditions.push(cond);
|
|
17963
|
+
}
|
|
17964
|
+
}
|
|
17965
|
+
return conditions;
|
|
17966
|
+
}
|
|
17967
|
+
|
|
17916
17968
|
class Neighbourhood {
|
|
17917
17969
|
constructor(linkLanguage, meta) {
|
|
17918
17970
|
this.linkLanguage = linkLanguage;
|
|
@@ -17945,6 +17997,112 @@ class ModelInput {
|
|
|
17945
17997
|
class VoiceActivityParamsInput {
|
|
17946
17998
|
}
|
|
17947
17999
|
|
|
18000
|
+
/**
|
|
18001
|
+
* Builder functions for SHACL-AF Node Expressions.
|
|
18002
|
+
*
|
|
18003
|
+
* These functions construct JSON-serializable expression trees for property transforms.
|
|
18004
|
+
* All builders return frozen objects to prevent accidental mutation.
|
|
18005
|
+
*/
|
|
18006
|
+
/**
|
|
18007
|
+
* Identity expression: pass the focus node through unchanged.
|
|
18008
|
+
*/
|
|
18009
|
+
function focus() {
|
|
18010
|
+
return Object.freeze({ type: 'focus' });
|
|
18011
|
+
}
|
|
18012
|
+
/**
|
|
18013
|
+
* Literal constant expression.
|
|
18014
|
+
*/
|
|
18015
|
+
function literal(value) {
|
|
18016
|
+
return Object.freeze({ type: 'literal', value });
|
|
18017
|
+
}
|
|
18018
|
+
/**
|
|
18019
|
+
* Path expression: navigate to a property on the resolved object.
|
|
18020
|
+
* The predicate can be a full IRI (e.g., "file_storage://data_base64")
|
|
18021
|
+
* or a simple property name. The Rust evaluator will strip the namespace.
|
|
18022
|
+
*/
|
|
18023
|
+
function path(predicate) {
|
|
18024
|
+
return Object.freeze({ type: 'path', predicate });
|
|
18025
|
+
}
|
|
18026
|
+
/**
|
|
18027
|
+
* Existence check: returns true if the inner expression is non-null and non-empty.
|
|
18028
|
+
*/
|
|
18029
|
+
function exists(expr) {
|
|
18030
|
+
return Object.freeze({ type: 'exists', expr });
|
|
18031
|
+
}
|
|
18032
|
+
/**
|
|
18033
|
+
* Conditional expression with optional else branch.
|
|
18034
|
+
* Returns a chainable builder that supports `.then()` and `.else()`.
|
|
18035
|
+
*/
|
|
18036
|
+
function ifExpr(cond) {
|
|
18037
|
+
return {
|
|
18038
|
+
then: (thenExpr) => ({
|
|
18039
|
+
else: (elseExpr) => {
|
|
18040
|
+
return Object.freeze({
|
|
18041
|
+
type: 'if',
|
|
18042
|
+
cond,
|
|
18043
|
+
then: thenExpr,
|
|
18044
|
+
...(elseExpr !== undefined && { else: elseExpr }),
|
|
18045
|
+
});
|
|
18046
|
+
},
|
|
18047
|
+
// Allow chaining without explicit else()
|
|
18048
|
+
toExpression: () => Object.freeze({
|
|
18049
|
+
type: 'if',
|
|
18050
|
+
cond,
|
|
18051
|
+
then: thenExpr,
|
|
18052
|
+
}),
|
|
18053
|
+
}),
|
|
18054
|
+
};
|
|
18055
|
+
}
|
|
18056
|
+
/**
|
|
18057
|
+
* String concatenation: joins evaluated arguments as strings.
|
|
18058
|
+
* Null/undefined arguments are skipped.
|
|
18059
|
+
*/
|
|
18060
|
+
function concat(...args) {
|
|
18061
|
+
return Object.freeze({ type: 'concat', args });
|
|
18062
|
+
}
|
|
18063
|
+
/**
|
|
18064
|
+
* Coalesce: returns the first non-null evaluated argument.
|
|
18065
|
+
*/
|
|
18066
|
+
function coalesce(...args) {
|
|
18067
|
+
return Object.freeze({ type: 'coalesce', args });
|
|
18068
|
+
}
|
|
18069
|
+
/**
|
|
18070
|
+
* Function call: invoke a named transform function by IRI.
|
|
18071
|
+
* Primarily used for built-in functions like "ad4m://fn/defaultFileDecode".
|
|
18072
|
+
*/
|
|
18073
|
+
function fn(iri, args = []) {
|
|
18074
|
+
return Object.freeze({ type: 'function', iri, args });
|
|
18075
|
+
}
|
|
18076
|
+
|
|
18077
|
+
/**
|
|
18078
|
+
* SHACL-AF Transform DSL — public API
|
|
18079
|
+
*
|
|
18080
|
+
* Re-exports builder functions and provides common built-in transforms.
|
|
18081
|
+
*/
|
|
18082
|
+
/**
|
|
18083
|
+
* Built-in transform: FileData → data: URI
|
|
18084
|
+
*
|
|
18085
|
+
* Converts a file stored via FILE_STORAGE_LANGUAGE into a data: URL.
|
|
18086
|
+
* If the object has a `data_base64` field, returns:
|
|
18087
|
+
* `data:{file_type};base64,{data_base64}`
|
|
18088
|
+
* Otherwise passes through the input unchanged.
|
|
18089
|
+
*
|
|
18090
|
+
* This is the Rust equivalent of the JS `defaultFileDecode` function.
|
|
18091
|
+
*
|
|
18092
|
+
* Usage:
|
|
18093
|
+
* ```typescript
|
|
18094
|
+
* @Property({
|
|
18095
|
+
* through: 'we://image',
|
|
18096
|
+
* resolveLanguage: FILE_STORAGE_LANGUAGE,
|
|
18097
|
+
* transform: fileToDataUri,
|
|
18098
|
+
* })
|
|
18099
|
+
* avatar?: string;
|
|
18100
|
+
* ```
|
|
18101
|
+
*/
|
|
18102
|
+
const fileToDataUri = ifExpr(exists(path('file_storage://data_base64')))
|
|
18103
|
+
.then(concat(literal('data:'), coalesce(path('file_storage://file_type'), literal('image/png')), literal(';base64,'), path('file_storage://data_base64')))
|
|
18104
|
+
.else(focus());
|
|
18105
|
+
|
|
17948
18106
|
exports.AIClient = AIClient;
|
|
17949
18107
|
exports.AIModel = Model;
|
|
17950
18108
|
exports.AIModelLoadingStatus = AIModelLoadingStatus;
|
|
@@ -18058,12 +18216,18 @@ exports.buildSPARQLQuery = buildSPARQLQuery;
|
|
|
18058
18216
|
exports.buildWhereCondition = buildWhereCondition;
|
|
18059
18217
|
exports.capSentence = capSentence;
|
|
18060
18218
|
exports.clearQueryCache = clearQueryCache;
|
|
18219
|
+
exports.coalesce = coalesce;
|
|
18061
18220
|
exports.compileWhereClause = compileWhereClause;
|
|
18221
|
+
exports.concat = concat;
|
|
18062
18222
|
exports.createPersistentCache = createPersistentCache;
|
|
18063
18223
|
exports.determineNamespace = determineNamespace;
|
|
18064
18224
|
exports.determinePredicate = determinePredicate;
|
|
18065
18225
|
exports.escapeQueryString = escapeQueryString;
|
|
18226
|
+
exports.exists = exists;
|
|
18066
18227
|
exports.exprRef2String = exprRef2String;
|
|
18228
|
+
exports.fileToDataUri = fileToDataUri;
|
|
18229
|
+
exports.fn = fn;
|
|
18230
|
+
exports.focus = focus;
|
|
18067
18231
|
exports.formatList = formatList;
|
|
18068
18232
|
exports.formatQueryValue = formatQueryValue;
|
|
18069
18233
|
exports.formatSPARQLValue = formatSPARQLValue;
|
|
@@ -18074,19 +18238,27 @@ exports.getPropertiesMetadata = getPropertiesMetadata;
|
|
|
18074
18238
|
exports.getPropertyOption = getPropertyOption;
|
|
18075
18239
|
exports.getRelationsMetadata = getRelationsMetadata;
|
|
18076
18240
|
exports.hasJsOnlyWhereFilters = hasJsOnlyWhereFilters;
|
|
18241
|
+
exports.ifExpr = ifExpr;
|
|
18077
18242
|
exports.invalidatePerspectiveCache = invalidatePerspectiveCache;
|
|
18078
18243
|
exports.isArrayType = isArrayType;
|
|
18079
18244
|
exports.isExpression = isExpression;
|
|
18080
18245
|
exports.isIncludeProjection = isIncludeProjection;
|
|
18081
18246
|
exports.isLink = isLink;
|
|
18247
|
+
exports.isNodeExpression = isNodeExpression;
|
|
18082
18248
|
exports.isNumericType = isNumericType;
|
|
18083
18249
|
exports.isObjectType = isObjectType;
|
|
18084
18250
|
exports.isSchemaType = isSchemaType;
|
|
18085
18251
|
exports.linkEqual = linkEqual;
|
|
18252
|
+
exports.literal = literal;
|
|
18086
18253
|
exports.normalizeNamespaceString = normalizeNamespaceString;
|
|
18087
18254
|
exports.normalizeSchemaType = normalizeSchemaType;
|
|
18088
18255
|
exports.normalizeValue = normalizeValue;
|
|
18089
18256
|
exports.parseExprUrl = parseExprUrl;
|
|
18257
|
+
exports.parseLit = parseLit;
|
|
18258
|
+
exports.parseLitBoolean = parseLitBoolean;
|
|
18259
|
+
exports.parseLitNumber = parseLitNumber;
|
|
18260
|
+
exports.parseSparqlCount = parseSparqlCount;
|
|
18261
|
+
exports.path = path;
|
|
18090
18262
|
exports.queryCacheSize = queryCacheSize;
|
|
18091
18263
|
exports.resolveParentPredicate = resolveParentPredicate;
|
|
18092
18264
|
exports.setCachedResult = setCachedResult;
|