@coasys/ad4m 0.13.0-test-4 → 0.13.0-test-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 +833 -971
- package/lib/index.js +834 -969
- package/lib/src/Ad4mClient.js +10 -0
- package/lib/src/model/Ad4mModel.d.ts +20 -7
- package/lib/src/model/Ad4mModel.js +90 -68
- package/lib/src/model/ModelQueryBuilder.d.ts +6 -6
- package/lib/src/model/ModelQueryBuilder.js +29 -11
- package/lib/src/model/hydration.d.ts +2 -39
- package/lib/src/model/hydration.js +2 -260
- package/lib/src/model/query-utils.d.ts +1 -0
- package/lib/src/model/query-utils.js +46 -1
- package/lib/src/model/types.d.ts +4 -5
- package/lib/src/perspectives/PerspectiveClient.d.ts +1 -0
- package/lib/src/perspectives/PerspectiveClient.js +10 -0
- package/lib/src/perspectives/PerspectiveProxy.d.ts +14 -0
- package/lib/src/perspectives/PerspectiveProxy.js +16 -0
- package/package.json +11 -8
- package/src/Ad4mClient.ts +10 -0
- package/src/model/Ad4mModel.test.ts +58 -297
- package/src/model/Ad4mModel.ts +99 -69
- package/src/model/ModelQueryBuilder.ts +29 -11
- package/src/model/hydration.ts +2 -279
- package/src/model/query-utils.ts +47 -2
- package/src/model/types.ts +4 -5
- package/src/perspectives/PerspectiveClient.ts +19 -0
- package/src/perspectives/PerspectiveProxy.ts +24 -0
package/lib/index.cjs
CHANGED
|
@@ -1719,6 +1719,7 @@ function buildWhereCondition(predicate, condition, opts) {
|
|
|
1719
1719
|
// For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>
|
|
1720
1720
|
// For language-resolved properties, values are plain URIs
|
|
1721
1721
|
const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
|
|
1722
|
+
const varSuffix = opts?.varIndex ?? 0;
|
|
1722
1723
|
function formatValue(v) {
|
|
1723
1724
|
if (typeof v === 'string') {
|
|
1724
1725
|
return isLiteral
|
|
@@ -1728,8 +1729,46 @@ function buildWhereCondition(predicate, condition, opts) {
|
|
|
1728
1729
|
// Numbers/booleans — also stored as literal:string: in AD4M
|
|
1729
1730
|
return `<literal:string:${v}>`;
|
|
1730
1731
|
}
|
|
1732
|
+
/**
|
|
1733
|
+
* For literal properties, generate a FILTER-based match that handles both
|
|
1734
|
+
* the raw value and the literal-encoded value. This mirrors the Rust
|
|
1735
|
+
* `build_projection_where_patterns` approach which uses:
|
|
1736
|
+
* FILTER(STR(?var) = "value" || STR(?var) = "literal:string:encodedValue")
|
|
1737
|
+
* This is more robust than exact IRI matching because it handles edge cases
|
|
1738
|
+
* where the stored format might vary.
|
|
1739
|
+
*/
|
|
1740
|
+
function formatLiteralFilter(varName, v) {
|
|
1741
|
+
const raw = escapeQueryString(String(v));
|
|
1742
|
+
const encoded = encodeURIComponent(String(v))
|
|
1743
|
+
.replace(/!/g, '%21')
|
|
1744
|
+
.replace(/'/g, '%27')
|
|
1745
|
+
.replace(/\(/g, '%28')
|
|
1746
|
+
.replace(/\)/g, '%29')
|
|
1747
|
+
.replace(/\*/g, '%2A');
|
|
1748
|
+
if (typeof v === 'string') {
|
|
1749
|
+
return `FILTER(STR(${varName}) = "${raw}" || STR(${varName}) = "literal:string:${encoded}")`;
|
|
1750
|
+
}
|
|
1751
|
+
else if (typeof v === 'number') {
|
|
1752
|
+
return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:number:${v}")`;
|
|
1753
|
+
}
|
|
1754
|
+
else if (typeof v === 'boolean') {
|
|
1755
|
+
return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:boolean:${v}")`;
|
|
1756
|
+
}
|
|
1757
|
+
return `FILTER(STR(${varName}) = "${raw}")`;
|
|
1758
|
+
}
|
|
1731
1759
|
if (Array.isArray(condition)) {
|
|
1732
1760
|
// Array values → FILTER IN
|
|
1761
|
+
if (isLiteral) {
|
|
1762
|
+
const varName = `?_wc${varSuffix}`;
|
|
1763
|
+
const inValues = condition.flatMap(v => {
|
|
1764
|
+
const raw = escapeQueryString(String(v));
|
|
1765
|
+
const encoded = encodeURIComponent(String(v))
|
|
1766
|
+
.replace(/!/g, '%21').replace(/'/g, '%27')
|
|
1767
|
+
.replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
|
|
1768
|
+
return [`"${raw}"`, `"literal:string:${encoded}"`];
|
|
1769
|
+
}).join(', ');
|
|
1770
|
+
return `?target <${escapedPredicate}> ${varName} . FILTER(STR(${varName}) IN (${inValues}))`;
|
|
1771
|
+
}
|
|
1733
1772
|
const formattedValues = condition.map(formatValue).join(', ');
|
|
1734
1773
|
return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;
|
|
1735
1774
|
}
|
|
@@ -1761,6 +1800,12 @@ function buildWhereCondition(predicate, condition, opts) {
|
|
|
1761
1800
|
}
|
|
1762
1801
|
else {
|
|
1763
1802
|
// Simple equality
|
|
1803
|
+
if (isLiteral) {
|
|
1804
|
+
// Use FILTER matching (mirrors Rust build_projection_where_patterns)
|
|
1805
|
+
// to handle both raw values and literal-encoded IRIs robustly.
|
|
1806
|
+
const varName = `?_wc${varSuffix}`;
|
|
1807
|
+
return `?target <${escapedPredicate}> ${varName} . ${formatLiteralFilter(varName, condition)}`;
|
|
1808
|
+
}
|
|
1764
1809
|
return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
|
|
1765
1810
|
}
|
|
1766
1811
|
}
|
|
@@ -1798,7 +1843,7 @@ function compileWhereClause(where, metadata) {
|
|
|
1798
1843
|
// No metadata — treat name as raw predicate URI
|
|
1799
1844
|
predicate = propertyName;
|
|
1800
1845
|
}
|
|
1801
|
-
const cond = buildWhereCondition(predicate, condition, { resolveLanguage });
|
|
1846
|
+
const cond = buildWhereCondition(predicate, condition, { resolveLanguage, varIndex: conditions.length });
|
|
1802
1847
|
if (cond) {
|
|
1803
1848
|
conditions.push(cond);
|
|
1804
1849
|
}
|
|
@@ -3711,6 +3756,22 @@ class PerspectiveProxy {
|
|
|
3711
3756
|
async modelQuery(className, queryJson, shapeJson) {
|
|
3712
3757
|
return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, shapeJson);
|
|
3713
3758
|
}
|
|
3759
|
+
/**
|
|
3760
|
+
* Evaluate property getters for a batch of instances in a single RPC call.
|
|
3761
|
+
* Returns a map of `{ instanceId: { prop: value, ... } }`.
|
|
3762
|
+
*
|
|
3763
|
+
* Use this instead of `Ad4mModel.evaluateGetters()` for lazy-loading
|
|
3764
|
+
* getter-backed properties on visible items (e.g. `replyingTo` on messages).
|
|
3765
|
+
*
|
|
3766
|
+
* @param className - The model class name (e.g. "Message")
|
|
3767
|
+
* @param instanceIds - Array of instance base expression URIs
|
|
3768
|
+
* @param shapeJson - Shape metadata JSON from the model class
|
|
3769
|
+
* @param propertyNames - Optional subset of property names to evaluate
|
|
3770
|
+
* @returns Map of instance ID → evaluated property values
|
|
3771
|
+
*/
|
|
3772
|
+
async evaluateGetters(className, instanceIds, shapeJson, propertyNames) {
|
|
3773
|
+
return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds, shapeJson, propertyNames);
|
|
3774
|
+
}
|
|
3714
3775
|
/**
|
|
3715
3776
|
* Subscribe to model query changes. Builds trigger SPARQL from the model shape
|
|
3716
3777
|
* internally in Rust, registers a subscription, runs the initial query, and
|
|
@@ -5332,6 +5393,16 @@ class PerspectiveClient {
|
|
|
5332
5393
|
const resultJson = await __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson });
|
|
5333
5394
|
return JSON.parse(resultJson);
|
|
5334
5395
|
}
|
|
5396
|
+
async evaluateGetters(uuid, className, instanceIds, shapeJson, propertyNames) {
|
|
5397
|
+
const resultJson = await __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.evaluateGetters', {
|
|
5398
|
+
uuid,
|
|
5399
|
+
class_name: className,
|
|
5400
|
+
instance_ids: instanceIds,
|
|
5401
|
+
shape_json: shapeJson,
|
|
5402
|
+
...(propertyNames && { property_names: propertyNames }),
|
|
5403
|
+
});
|
|
5404
|
+
return JSON.parse(resultJson);
|
|
5405
|
+
}
|
|
5335
5406
|
async modelSubscribe(uuid, className, queryJson, shapeJson) {
|
|
5336
5407
|
const response = await __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson });
|
|
5337
5408
|
return {
|
|
@@ -13395,665 +13466,146 @@ class AIClient {
|
|
|
13395
13466
|
}
|
|
13396
13467
|
_AIClient_apiClient = new WeakMap(), _AIClient_transcriptionUnsubscribers = new WeakMap(), _AIClient_pendingStreamIds = new WeakMap();
|
|
13397
13468
|
|
|
13398
|
-
var __classPrivateFieldSet$1 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
13399
|
-
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
13400
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
13401
|
-
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
13402
|
-
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
13403
|
-
};
|
|
13404
|
-
var __classPrivateFieldGet$1 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
13405
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
13406
|
-
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
13407
|
-
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
13408
|
-
};
|
|
13409
|
-
var _Ad4mClient_baseUrl, _Ad4mClient_token, _Ad4mClient_apiClient, _Ad4mClient_agentClient, _Ad4mClient_expressionClient, _Ad4mClient_languageClient, _Ad4mClient_neighbourhoodClient, _Ad4mClient_perspectiveClient, _Ad4mClient_runtimeClient, _Ad4mClient_aiClient;
|
|
13410
13469
|
/**
|
|
13411
|
-
*
|
|
13412
|
-
|
|
13470
|
+
* Shared query helpers used by both the Prolog and SPARQL query pipelines.
|
|
13471
|
+
*/
|
|
13472
|
+
/**
|
|
13473
|
+
* Resolves the predicate for a parent query.
|
|
13413
13474
|
*
|
|
13414
|
-
*
|
|
13415
|
-
*
|
|
13416
|
-
*
|
|
13417
|
-
*
|
|
13475
|
+
* Uses TS discriminated union narrowing:
|
|
13476
|
+
* - Raw form (`{ id, predicate }`) → predicate used as-is
|
|
13477
|
+
* - Model form (`{ model, id, field? }`) → lookup from relation metadata
|
|
13478
|
+
* - With `field`: direct key lookup
|
|
13479
|
+
* - Without `field`: scan for a relation whose `target()` matches `childCtor`
|
|
13418
13480
|
*/
|
|
13419
|
-
|
|
13420
|
-
|
|
13421
|
-
|
|
13422
|
-
|
|
13423
|
-
|
|
13424
|
-
|
|
13425
|
-
|
|
13426
|
-
|
|
13427
|
-
|
|
13428
|
-
|
|
13429
|
-
|
|
13430
|
-
|
|
13431
|
-
|
|
13432
|
-
|
|
13433
|
-
__classPrivateFieldSet$1(this, _Ad4mClient_apiClient, new ApiClient(baseUrl, token), "f");
|
|
13434
|
-
__classPrivateFieldSet$1(this, _Ad4mClient_agentClient, new AgentClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
|
|
13435
|
-
__classPrivateFieldSet$1(this, _Ad4mClient_expressionClient, new ExpressionClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
|
|
13436
|
-
__classPrivateFieldSet$1(this, _Ad4mClient_languageClient, new LanguageClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
|
|
13437
|
-
__classPrivateFieldSet$1(this, _Ad4mClient_neighbourhoodClient, new NeighbourhoodClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
|
|
13438
|
-
__classPrivateFieldSet$1(this, _Ad4mClient_aiClient, new AIClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
|
|
13439
|
-
__classPrivateFieldSet$1(this, _Ad4mClient_perspectiveClient, new PerspectiveClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
|
|
13440
|
-
__classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, "f").setExpressionClient(__classPrivateFieldGet$1(this, _Ad4mClient_expressionClient, "f"));
|
|
13441
|
-
__classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, "f").setNeighbourhoodClient(__classPrivateFieldGet$1(this, _Ad4mClient_neighbourhoodClient, "f"));
|
|
13442
|
-
__classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, "f").setAIClient(__classPrivateFieldGet$1(this, _Ad4mClient_aiClient, "f"));
|
|
13443
|
-
__classPrivateFieldSet$1(this, _Ad4mClient_runtimeClient, new RuntimeClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
|
|
13444
|
-
}
|
|
13445
|
-
get agent() {
|
|
13446
|
-
return __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, "f");
|
|
13447
|
-
}
|
|
13448
|
-
get expression() {
|
|
13449
|
-
return __classPrivateFieldGet$1(this, _Ad4mClient_expressionClient, "f");
|
|
13450
|
-
}
|
|
13451
|
-
get languages() {
|
|
13452
|
-
return __classPrivateFieldGet$1(this, _Ad4mClient_languageClient, "f");
|
|
13453
|
-
}
|
|
13454
|
-
get neighbourhood() {
|
|
13455
|
-
return __classPrivateFieldGet$1(this, _Ad4mClient_neighbourhoodClient, "f");
|
|
13456
|
-
}
|
|
13457
|
-
get perspective() {
|
|
13458
|
-
return __classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, "f");
|
|
13459
|
-
}
|
|
13460
|
-
get runtime() {
|
|
13461
|
-
return __classPrivateFieldGet$1(this, _Ad4mClient_runtimeClient, "f");
|
|
13462
|
-
}
|
|
13463
|
-
get ai() {
|
|
13464
|
-
return __classPrivateFieldGet$1(this, _Ad4mClient_aiClient, "f");
|
|
13465
|
-
}
|
|
13466
|
-
/** Start event subscriptions (agent-updated, agent-status-changed, apps-changed).
|
|
13467
|
-
* Safe to call if subscriptions were deferred at construction (subscribe=false). */
|
|
13468
|
-
startSubscriptions() {
|
|
13469
|
-
__classPrivateFieldGet$1(this, _Ad4mClient_agentClient, "f").subscribeAgentUpdated();
|
|
13470
|
-
__classPrivateFieldGet$1(this, _Ad4mClient_agentClient, "f").subscribeAgentStatusChanged();
|
|
13471
|
-
__classPrivateFieldGet$1(this, _Ad4mClient_agentClient, "f").subscribeAppsChanged();
|
|
13472
|
-
}
|
|
13473
|
-
/** Close all event connections */
|
|
13474
|
-
close() {
|
|
13475
|
-
__classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f").closeAll();
|
|
13476
|
-
}
|
|
13477
|
-
}
|
|
13478
|
-
_Ad4mClient_baseUrl = new WeakMap(), _Ad4mClient_token = new WeakMap(), _Ad4mClient_apiClient = new WeakMap(), _Ad4mClient_agentClient = new WeakMap(), _Ad4mClient_expressionClient = new WeakMap(), _Ad4mClient_languageClient = new WeakMap(), _Ad4mClient_neighbourhoodClient = new WeakMap(), _Ad4mClient_perspectiveClient = new WeakMap(), _Ad4mClient_runtimeClient = new WeakMap(), _Ad4mClient_aiClient = new WeakMap();
|
|
13479
|
-
|
|
13480
|
-
exports.ExceptionType = void 0;
|
|
13481
|
-
(function (ExceptionType) {
|
|
13482
|
-
ExceptionType["LanguageIsNotLoaded"] = "LANGUAGE_IS_NOT_LOADED";
|
|
13483
|
-
ExceptionType["ExpressionIsNotVerified"] = "EXPRESSION_IS_NOT_VERIFIED";
|
|
13484
|
-
ExceptionType["AgentIsUntrusted"] = "AGENT_IS_UNTRUSTED";
|
|
13485
|
-
ExceptionType["CapabilityRequested"] = "CAPABILITY_REQUESTED";
|
|
13486
|
-
ExceptionType["InstallNotificationRequest"] = "INSTALL_NOTIFICATION_REQUEST";
|
|
13487
|
-
})(exports.ExceptionType || (exports.ExceptionType = {}));
|
|
13488
|
-
|
|
13489
|
-
// Unique Language ID with option type
|
|
13490
|
-
class LanguageRef {
|
|
13491
|
-
constructor(address, name) {
|
|
13492
|
-
this.address = address;
|
|
13493
|
-
this.name = name;
|
|
13494
|
-
}
|
|
13495
|
-
}
|
|
13496
|
-
|
|
13497
|
-
// Expression address + unique Language ID = global expression URL
|
|
13498
|
-
class ExpressionRef {
|
|
13499
|
-
constructor(lang, expr) {
|
|
13500
|
-
this.language = lang;
|
|
13501
|
-
this.expression = expr;
|
|
13502
|
-
}
|
|
13503
|
-
}
|
|
13504
|
-
// Creates unique expression URI like this:
|
|
13505
|
-
// expr:Qm3490gfwe489hf34:Qm90ghjoaw4iehioefwe4ort
|
|
13506
|
-
function exprRef2String(ref) {
|
|
13507
|
-
if (ref.language.address === 'did')
|
|
13508
|
-
return ref.expression.toString();
|
|
13509
|
-
else
|
|
13510
|
-
return `${ref.language.address}://${ref.expression}`;
|
|
13511
|
-
}
|
|
13512
|
-
function parseExprUrl(url) {
|
|
13513
|
-
if (url.startsWith("literal:")) {
|
|
13514
|
-
const languageRef = new LanguageRef();
|
|
13515
|
-
languageRef.address = 'literal';
|
|
13516
|
-
languageRef.name = 'literal';
|
|
13517
|
-
const content = url.substring(8);
|
|
13518
|
-
return new ExpressionRef(languageRef, content);
|
|
13519
|
-
}
|
|
13520
|
-
const URIregexp = /^([^:^\s]+):\/\/([\s\S]+)$/;
|
|
13521
|
-
const URImatches = URIregexp.exec(url);
|
|
13522
|
-
if (URImatches && URImatches.length == 3) {
|
|
13523
|
-
const language = URImatches[1];
|
|
13524
|
-
const expression = URImatches[2];
|
|
13525
|
-
const languageRef = new LanguageRef();
|
|
13526
|
-
languageRef.address = language;
|
|
13527
|
-
const ref = new ExpressionRef(languageRef, expression);
|
|
13528
|
-
return ref;
|
|
13529
|
-
}
|
|
13530
|
-
const DIDregexp = /^did:([^\s]+)$/;
|
|
13531
|
-
const DIDmatches = DIDregexp.exec(url);
|
|
13532
|
-
if (DIDmatches && DIDmatches.length == 2) {
|
|
13533
|
-
const languageRef = new LanguageRef();
|
|
13534
|
-
languageRef.address = 'did';
|
|
13535
|
-
const ref = new ExpressionRef(languageRef, url);
|
|
13536
|
-
return ref;
|
|
13481
|
+
function resolveParentPredicate(parent, childCtor) {
|
|
13482
|
+
// Raw form — explicit predicate
|
|
13483
|
+
if ('predicate' in parent)
|
|
13484
|
+
return parent.predicate;
|
|
13485
|
+
// Model form — resolve from relation metadata
|
|
13486
|
+
const { model } = parent;
|
|
13487
|
+
const relMeta = getRelationsMetadata(model);
|
|
13488
|
+
// Direct lookup by field name when provided
|
|
13489
|
+
if (parent.field) {
|
|
13490
|
+
const entry = relMeta[parent.field];
|
|
13491
|
+
if (!entry) {
|
|
13492
|
+
throw new Error(`parent(): field "${parent.field}" is not a registered relation on ${model.name}`);
|
|
13493
|
+
}
|
|
13494
|
+
return entry.predicate;
|
|
13537
13495
|
}
|
|
13538
|
-
|
|
13539
|
-
|
|
13540
|
-
|
|
13541
|
-
|
|
13542
|
-
|
|
13543
|
-
this.code = code;
|
|
13496
|
+
// Fallback: scan for a relation whose target matches the child class
|
|
13497
|
+
for (const [, entry] of Object.entries(relMeta)) {
|
|
13498
|
+
if (entry.target && entry.target() === childCtor) {
|
|
13499
|
+
return entry.predicate;
|
|
13500
|
+
}
|
|
13544
13501
|
}
|
|
13502
|
+
throw new Error(`parent(): could not resolve predicate — no relation on ${model.name} targets ${childCtor.name || 'the queried class'}`);
|
|
13545
13503
|
}
|
|
13546
13504
|
|
|
13547
13505
|
/**
|
|
13548
|
-
*
|
|
13549
|
-
*
|
|
13550
|
-
* This file only contains the client-visible types that the AD4M REST
|
|
13551
|
-
* API exposes on top of a running Language — interaction metadata, online
|
|
13552
|
-
* agent records, and the telepresence-signal callback shape.
|
|
13506
|
+
* JSON Schema → Ad4mModel class builder and related utilities.
|
|
13553
13507
|
*
|
|
13554
|
-
*
|
|
13555
|
-
*
|
|
13556
|
-
*
|
|
13557
|
-
*
|
|
13558
|
-
*
|
|
13508
|
+
* Contains:
|
|
13509
|
+
* - JSON Schema type definitions (JSONSchemaProperty, JSONSchema, JSONSchemaToModelOptions)
|
|
13510
|
+
* - Schema type helpers (normalizeNamespaceString, isArrayType, etc.)
|
|
13511
|
+
* - Predicate / namespace resolution helpers
|
|
13512
|
+
* - `buildModelFromJSONSchema()` — core implementation of `Ad4mModel.fromJSONSchema()`
|
|
13559
13513
|
*
|
|
13560
|
-
*
|
|
13561
|
-
* [`docs-src/ad4m-lang.wit`](https://github.com/coasys/ad4m/blob/dev/docs-src/ad4m-lang.wit).
|
|
13562
|
-
* The prose spec is
|
|
13563
|
-
* [`docs-src/language-interface-spec.md`](https://github.com/coasys/ad4m/blob/dev/docs-src/language-interface-spec.md).
|
|
13514
|
+
* @module
|
|
13564
13515
|
*/
|
|
13565
|
-
//
|
|
13566
|
-
|
|
13567
|
-
|
|
13568
|
-
|
|
13569
|
-
|
|
13570
|
-
|
|
13571
|
-
|
|
13572
|
-
|
|
13573
|
-
}
|
|
13574
|
-
class InteractionCall {
|
|
13575
|
-
get parameters() {
|
|
13576
|
-
return JSON.parse(this.parametersStringified);
|
|
13516
|
+
// ─── Schema Type Helpers ─────────────────────────────────────────────────────
|
|
13517
|
+
function normalizeNamespaceString(namespace) {
|
|
13518
|
+
if (!namespace)
|
|
13519
|
+
return '';
|
|
13520
|
+
if (namespace.includes('://')) {
|
|
13521
|
+
const [scheme, rest] = namespace.split('://');
|
|
13522
|
+
const path = (rest || '').replace(/\/+$/, '');
|
|
13523
|
+
return `${scheme}://${path}`;
|
|
13577
13524
|
}
|
|
13578
|
-
|
|
13579
|
-
|
|
13580
|
-
this.parametersStringified = JSON.stringify(parameters);
|
|
13525
|
+
else {
|
|
13526
|
+
return namespace.replace(/\/+$/, '');
|
|
13581
13527
|
}
|
|
13582
13528
|
}
|
|
13583
|
-
|
|
13584
|
-
|
|
13529
|
+
function normalizeSchemaType(type) {
|
|
13530
|
+
if (!type)
|
|
13531
|
+
return undefined;
|
|
13532
|
+
if (typeof type === "string")
|
|
13533
|
+
return type;
|
|
13534
|
+
if (Array.isArray(type) && type.length > 0) {
|
|
13535
|
+
const nonNull = type.find((t) => t !== "null");
|
|
13536
|
+
return nonNull || type[0];
|
|
13537
|
+
}
|
|
13538
|
+
return undefined;
|
|
13585
13539
|
}
|
|
13586
|
-
|
|
13587
|
-
|
|
13540
|
+
function isSchemaType(schema, expectedType) {
|
|
13541
|
+
return normalizeSchemaType(schema.type) === expectedType;
|
|
13588
13542
|
}
|
|
13589
|
-
|
|
13590
|
-
|
|
13543
|
+
function isArrayType(schema) {
|
|
13544
|
+
return isSchemaType(schema, "array");
|
|
13591
13545
|
}
|
|
13592
|
-
|
|
13593
|
-
|
|
13594
|
-
this.name = name;
|
|
13595
|
-
this.description = description;
|
|
13596
|
-
if (!this.description)
|
|
13597
|
-
this.description = "";
|
|
13598
|
-
}
|
|
13599
|
-
}
|
|
13600
|
-
class LanguageMetaInternal {
|
|
13601
|
-
}
|
|
13602
|
-
class LanguageExpression extends ExpressionGeneric() {
|
|
13603
|
-
}
|
|
13604
|
-
class LanguageLanguageInput {
|
|
13546
|
+
function isObjectType(schema) {
|
|
13547
|
+
return isSchemaType(schema, "object");
|
|
13605
13548
|
}
|
|
13606
|
-
|
|
13607
|
-
|
|
13608
|
-
|
|
13609
|
-
PerspectiveState["Private"] = "PRIVATE";
|
|
13610
|
-
PerspectiveState["NeighboudhoodCreationInitiated"] = "NEIGHBOURHOOD_CREATION_INITIATED";
|
|
13611
|
-
PerspectiveState["NeighbourhoodJoinInitiated"] = "NEIGHBOURHOOD_JOIN_INITIATED";
|
|
13612
|
-
PerspectiveState["LinkLanguageFailedToInstall"] = "LINK_LANGUAGE_FAILED_TO_INSTALL";
|
|
13613
|
-
PerspectiveState["LinkLanguageInstalledButNotSynced"] = "LINK_LANGUAGE_INSTALLED_BUT_NOT_SYNCED";
|
|
13614
|
-
PerspectiveState["Synced"] = "SYNCED";
|
|
13615
|
-
})(exports.PerspectiveState || (exports.PerspectiveState = {}));
|
|
13616
|
-
// This type is used in the REST interface to reference a mutable
|
|
13617
|
-
// prespective that is implemented locally by the Ad4m runtime.
|
|
13618
|
-
// The UUID is used in mutations to identify the perspective that gets mutated.
|
|
13619
|
-
class PerspectiveHandle {
|
|
13620
|
-
constructor(uuid, name, state) {
|
|
13621
|
-
this.uuid = uuid;
|
|
13622
|
-
this.name = name;
|
|
13623
|
-
if (state) {
|
|
13624
|
-
this.state = state;
|
|
13625
|
-
}
|
|
13626
|
-
else {
|
|
13627
|
-
this.state = exports.PerspectiveState.Private;
|
|
13628
|
-
}
|
|
13629
|
-
}
|
|
13549
|
+
function isNumericType(schema) {
|
|
13550
|
+
const normalized = normalizeSchemaType(schema.type);
|
|
13551
|
+
return normalized === "number" || normalized === "integer";
|
|
13630
13552
|
}
|
|
13631
|
-
|
|
13553
|
+
// ─── Predicate / Namespace Resolution ────────────────────────────────────────
|
|
13632
13554
|
/**
|
|
13633
|
-
*
|
|
13634
|
-
*
|
|
13635
|
-
*
|
|
13636
|
-
*
|
|
13637
|
-
*
|
|
13638
|
-
*
|
|
13555
|
+
* Determines the namespace for predicates using cascading precedence:
|
|
13556
|
+
* 1. Explicit namespace in options
|
|
13557
|
+
* 2. x-ad4m metadata in schema
|
|
13558
|
+
* 3. Infer from schema title
|
|
13559
|
+
* 4. Try to extract from $id
|
|
13560
|
+
* 5. Error if nothing works
|
|
13639
13561
|
*/
|
|
13640
|
-
|
|
13641
|
-
|
|
13642
|
-
|
|
13643
|
-
|
|
13644
|
-
this.debounceTimers = new Map();
|
|
13645
|
-
/** Per-subscription set of already-processed message addresses (for mention subs)
|
|
13646
|
-
* or serialized result hash (for channel-messages subs). */
|
|
13647
|
-
this.seenMessages = new Map();
|
|
13648
|
-
this.perspectiveClient = options.perspectiveClient;
|
|
13649
|
-
this.logger = options.logger;
|
|
13650
|
-
this.debounceMs = options.debounceMs ?? 2000;
|
|
13651
|
-
this.onWake = options.onWake;
|
|
13652
|
-
this.onPersist = options.onPersist;
|
|
13653
|
-
this.QuerySubscriptionProxyCtor = options.QuerySubscriptionProxy ?? null;
|
|
13654
|
-
this.previousSeenMessages = options.previousSeenMessages ?? {};
|
|
13562
|
+
function determineNamespace(schema, options) {
|
|
13563
|
+
// 1. Explicit namespace in options (highest precedence)
|
|
13564
|
+
if (options.namespace) {
|
|
13565
|
+
return options.namespace;
|
|
13655
13566
|
}
|
|
13656
|
-
|
|
13657
|
-
|
|
13658
|
-
|
|
13659
|
-
|
|
13660
|
-
|
|
13661
|
-
|
|
13662
|
-
|
|
13663
|
-
|
|
13664
|
-
|
|
13665
|
-
|
|
13666
|
-
const QuerySubscriptionProxy = this.QuerySubscriptionProxyCtor;
|
|
13667
|
-
this.logger.info(`[waker] ${sub.id}: creating subscription (perspective=${sub.perspective}, type=${sub.type})`);
|
|
13668
|
-
this.logger.info(`[waker] ${sub.id}: SPARQL query:\n${sub.query}`);
|
|
13669
|
-
const proxy = new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient);
|
|
13670
|
-
proxy.isSPARQL = true;
|
|
13671
|
-
// Suppress unhandled rejection from proxy.initialized — QuerySubscriptionProxy
|
|
13672
|
-
// rejects this promise internally when subscribe() fails, and if nobody catches
|
|
13673
|
-
// it before the next microtask it crashes the process.
|
|
13674
|
-
if (proxy.initialized && typeof proxy.initialized.catch === "function") {
|
|
13675
|
-
proxy.initialized.catch(() => { });
|
|
13676
|
-
}
|
|
13567
|
+
// 2. x-ad4m metadata in schema
|
|
13568
|
+
if (schema["x-ad4m"]?.namespace) {
|
|
13569
|
+
return schema["x-ad4m"].namespace;
|
|
13570
|
+
}
|
|
13571
|
+
// 3. Infer from schema title
|
|
13572
|
+
if (schema.title) {
|
|
13573
|
+
return `${schema.title.toLowerCase()}://`;
|
|
13574
|
+
}
|
|
13575
|
+
// 4. Try to extract from $id if it's a URL
|
|
13576
|
+
if (schema.$id) {
|
|
13677
13577
|
try {
|
|
13678
|
-
|
|
13679
|
-
|
|
13680
|
-
|
|
13681
|
-
|
|
13682
|
-
|
|
13683
|
-
|
|
13684
|
-
try {
|
|
13685
|
-
proxy.dispose();
|
|
13578
|
+
const url = new URL(schema.$id);
|
|
13579
|
+
const pathParts = url.pathname.split('/').filter(p => p);
|
|
13580
|
+
if (pathParts.length > 0) {
|
|
13581
|
+
const lastPart = pathParts[pathParts.length - 1];
|
|
13582
|
+
const baseName = lastPart.replace(/\.schema\.json$/, '').replace(/\.json$/, '');
|
|
13583
|
+
return `${baseName.toLowerCase()}://`;
|
|
13686
13584
|
}
|
|
13687
|
-
catch { }
|
|
13688
|
-
// Remove from active state so it doesn't get persisted/retried
|
|
13689
|
-
this.activeSubscriptions.delete(sub.id);
|
|
13690
|
-
this.seenMessages.delete(sub.id);
|
|
13691
|
-
this.persist();
|
|
13692
|
-
return; // Don't throw — caller should not crash
|
|
13693
13585
|
}
|
|
13694
|
-
|
|
13695
|
-
|
|
13696
|
-
const seen = new Set(this.previousSeenMessages[sub.id] ?? []);
|
|
13697
|
-
this.seenMessages.set(sub.id, seen);
|
|
13698
|
-
if (seen.size > 0) {
|
|
13699
|
-
this.logger.info(`[waker] ${sub.id}: seeded ${seen.size} seen message(s) from persisted state`);
|
|
13586
|
+
catch {
|
|
13587
|
+
// If $id is not a valid URL, continue to error
|
|
13700
13588
|
}
|
|
13701
|
-
proxy.onResult(async (result) => {
|
|
13702
|
-
this.logger.info(`[waker] ${sub.id}: onResult fired — type=${typeof result}, isArray=${Array.isArray(result)}, value=${String(JSON.stringify(result)).substring(0, 500)}`);
|
|
13703
|
-
// Query engine can deliver non-array values (e.g. false) on disconnect/reconnect — ignore them
|
|
13704
|
-
if (!Array.isArray(result)) {
|
|
13705
|
-
this.logger.warn(`[waker] ${sub.id}: ignoring non-array result: ${JSON.stringify(result)}`);
|
|
13706
|
-
return;
|
|
13707
|
-
}
|
|
13708
|
-
if (sub.type === "mention") {
|
|
13709
|
-
// For mention subscriptions: track seen message addresses.
|
|
13710
|
-
// Only wake for messages we haven't seen before.
|
|
13711
|
-
const currentSeen = this.seenMessages.get(sub.id) ?? new Set();
|
|
13712
|
-
const newMessages = [];
|
|
13713
|
-
for (const item of result) {
|
|
13714
|
-
if (item && item.source && !currentSeen.has(item.source)) {
|
|
13715
|
-
newMessages.push(item.source);
|
|
13716
|
-
}
|
|
13717
|
-
}
|
|
13718
|
-
if (newMessages.length === 0) {
|
|
13719
|
-
this.logger.info(`[waker] ${sub.id}: all ${result.length} items already seen, skipping`);
|
|
13720
|
-
return;
|
|
13721
|
-
}
|
|
13722
|
-
this.logger.info(`[waker] ${sub.id}: ${newMessages.length} new message(s) out of ${result.length} total`);
|
|
13723
|
-
// Resolve parents per new message
|
|
13724
|
-
const mentions = [];
|
|
13725
|
-
for (const msgAddr of newMessages) {
|
|
13726
|
-
const parents = [];
|
|
13727
|
-
try {
|
|
13728
|
-
const parentQuery = `SELECT ?source WHERE { ?source <ad4m://has_child> <${msgAddr}> . }`;
|
|
13729
|
-
this.logger.info(`[waker] ${sub.id}: resolving parents for ${msgAddr}`);
|
|
13730
|
-
const parentResult = await this.perspectiveClient.querySparql(sub.perspective, parentQuery);
|
|
13731
|
-
if (Array.isArray(parentResult)) {
|
|
13732
|
-
for (const link of parentResult) {
|
|
13733
|
-
if (link && link.source) {
|
|
13734
|
-
parents.push(link.source);
|
|
13735
|
-
}
|
|
13736
|
-
}
|
|
13737
|
-
}
|
|
13738
|
-
}
|
|
13739
|
-
catch (err) {
|
|
13740
|
-
this.logger.warn(`[waker] ${sub.id}: parent resolution failed for ${msgAddr} — ${err?.message ?? err}`);
|
|
13741
|
-
}
|
|
13742
|
-
this.logger.info(`[waker] ${sub.id}: message ${msgAddr} has ${parents.length} parent(s): ${parents.join(", ")}`);
|
|
13743
|
-
mentions.push({ address: msgAddr, parents });
|
|
13744
|
-
}
|
|
13745
|
-
// Mark all new messages as seen
|
|
13746
|
-
for (const addr of newMessages) {
|
|
13747
|
-
currentSeen.add(addr);
|
|
13748
|
-
}
|
|
13749
|
-
this.seenMessages.set(sub.id, currentSeen);
|
|
13750
|
-
// Debounce the wake callback
|
|
13751
|
-
const existing = this.debounceTimers.get(sub.id);
|
|
13752
|
-
if (existing)
|
|
13753
|
-
clearTimeout(existing);
|
|
13754
|
-
this.debounceTimers.set(sub.id, setTimeout(() => {
|
|
13755
|
-
this.onWake(sub, result, mentions);
|
|
13756
|
-
this.debounceTimers.delete(sub.id);
|
|
13757
|
-
this.persist();
|
|
13758
|
-
}, this.debounceMs));
|
|
13759
|
-
}
|
|
13760
|
-
else {
|
|
13761
|
-
// For channel-messages: always notify the agent on every subscription push.
|
|
13762
|
-
// No deduplication — the agent reads recent messages itself.
|
|
13763
|
-
this.logger.info(`[waker] ${sub.id}: channel update (${result.length} items)`);
|
|
13764
|
-
const existing = this.debounceTimers.get(sub.id);
|
|
13765
|
-
if (existing)
|
|
13766
|
-
clearTimeout(existing);
|
|
13767
|
-
this.debounceTimers.set(sub.id, setTimeout(() => {
|
|
13768
|
-
this.onWake(sub, result);
|
|
13769
|
-
this.debounceTimers.delete(sub.id);
|
|
13770
|
-
}, this.debounceMs));
|
|
13771
|
-
}
|
|
13772
|
-
});
|
|
13773
|
-
this.proxies.set(sub.id, proxy);
|
|
13774
|
-
this.activeSubscriptions.set(sub.id, sub);
|
|
13775
|
-
this.persist();
|
|
13776
|
-
this.logger.info(`[waker] Subscription ${sub.id} active (type=${sub.type}, perspective=${sub.perspective})`);
|
|
13777
13589
|
}
|
|
13778
|
-
|
|
13779
|
-
|
|
13780
|
-
|
|
13781
|
-
|
|
13782
|
-
|
|
13783
|
-
|
|
13784
|
-
|
|
13785
|
-
|
|
13786
|
-
|
|
13787
|
-
|
|
13788
|
-
|
|
13789
|
-
|
|
13790
|
-
|
|
13791
|
-
|
|
13792
|
-
|
|
13793
|
-
|
|
13794
|
-
|
|
13795
|
-
|
|
13796
|
-
|
|
13797
|
-
}
|
|
13798
|
-
this.activeSubscriptions.delete(id);
|
|
13799
|
-
this.seenMessages.delete(id);
|
|
13800
|
-
if (persist)
|
|
13801
|
-
this.persist();
|
|
13802
|
-
}
|
|
13803
|
-
/** Dispose all active subscriptions. */
|
|
13804
|
-
disposeAll() {
|
|
13805
|
-
for (const [id] of this.proxies) {
|
|
13806
|
-
this.dispose(id, false);
|
|
13807
|
-
}
|
|
13808
|
-
}
|
|
13809
|
-
/** Get all active subscriptions. */
|
|
13810
|
-
getActive() {
|
|
13811
|
-
return Array.from(this.activeSubscriptions.values());
|
|
13812
|
-
}
|
|
13813
|
-
/** Check if a subscription exists. */
|
|
13814
|
-
has(id) {
|
|
13815
|
-
return this.activeSubscriptions.has(id);
|
|
13816
|
-
}
|
|
13817
|
-
persist() {
|
|
13818
|
-
if (this.onPersist) {
|
|
13819
|
-
const seen = {};
|
|
13820
|
-
for (const [id, set] of this.seenMessages) {
|
|
13821
|
-
seen[id] = Array.from(set);
|
|
13822
|
-
}
|
|
13823
|
-
this.onPersist(this.getActive(), seen);
|
|
13824
|
-
}
|
|
13825
|
-
}
|
|
13826
|
-
}
|
|
13827
|
-
|
|
13828
|
-
class PerspectiveDiff {
|
|
13829
|
-
}
|
|
13830
|
-
class PerspectiveDiffExpression extends ExpressionGeneric() {
|
|
13831
|
-
}
|
|
13832
|
-
|
|
13833
|
-
var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
13834
|
-
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
13835
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
13836
|
-
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
13837
|
-
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
13838
|
-
};
|
|
13839
|
-
var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
13840
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
13841
|
-
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
13842
|
-
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
13843
|
-
};
|
|
13844
|
-
var _SmartLiteral_perspective, _SmartLiteral_base;
|
|
13845
|
-
const SMART_LITERAL_CONTENT_PREDICATE = "smart_literal://content";
|
|
13846
|
-
function makeRandomStringID(length) {
|
|
13847
|
-
let result = '';
|
|
13848
|
-
let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
|
13849
|
-
let charactersLength = characters.length;
|
|
13850
|
-
for (let i = 0; i < length; i++) {
|
|
13851
|
-
result += characters.charAt(Math.floor(Math.random() * charactersLength));
|
|
13852
|
-
}
|
|
13853
|
-
return result;
|
|
13854
|
-
}
|
|
13855
|
-
class SmartLiteral {
|
|
13856
|
-
constructor(perspective, base) {
|
|
13857
|
-
_SmartLiteral_perspective.set(this, void 0);
|
|
13858
|
-
_SmartLiteral_base.set(this, void 0);
|
|
13859
|
-
__classPrivateFieldSet(this, _SmartLiteral_perspective, perspective, "f");
|
|
13860
|
-
__classPrivateFieldSet(this, _SmartLiteral_base, base, "f");
|
|
13861
|
-
}
|
|
13862
|
-
get base() {
|
|
13863
|
-
return __classPrivateFieldGet(this, _SmartLiteral_base, "f");
|
|
13864
|
-
}
|
|
13865
|
-
static async create(perspective, literal) {
|
|
13866
|
-
const base = Literal.from(makeRandomStringID(10)).toUrl();
|
|
13867
|
-
const smartLiteral = new SmartLiteral(perspective, base);
|
|
13868
|
-
await smartLiteral.set(literal);
|
|
13869
|
-
return smartLiteral;
|
|
13870
|
-
}
|
|
13871
|
-
static async isSmartLiteralBase(perspective, base) {
|
|
13872
|
-
let links = await perspective.get(new LinkQuery({
|
|
13873
|
-
source: base,
|
|
13874
|
-
predicate: SMART_LITERAL_CONTENT_PREDICATE
|
|
13875
|
-
}));
|
|
13876
|
-
return links.length > 0;
|
|
13877
|
-
}
|
|
13878
|
-
static async getAllSmartLiterals(perspective) {
|
|
13879
|
-
let links = await perspective.get(new LinkQuery({
|
|
13880
|
-
predicate: SMART_LITERAL_CONTENT_PREDICATE
|
|
13881
|
-
}));
|
|
13882
|
-
return links.map(link => new SmartLiteral(perspective, link.data.source));
|
|
13883
|
-
}
|
|
13884
|
-
async get() {
|
|
13885
|
-
let link = await __classPrivateFieldGet(this, _SmartLiteral_perspective, "f").getSingleTarget(new LinkQuery({
|
|
13886
|
-
source: __classPrivateFieldGet(this, _SmartLiteral_base, "f"),
|
|
13887
|
-
predicate: SMART_LITERAL_CONTENT_PREDICATE
|
|
13888
|
-
}));
|
|
13889
|
-
if (!link) {
|
|
13890
|
-
throw `No content for smart literal ${__classPrivateFieldGet(this, _SmartLiteral_base, "f")}`;
|
|
13891
|
-
}
|
|
13892
|
-
return Literal.fromUrl(link).get();
|
|
13893
|
-
}
|
|
13894
|
-
async set(content) {
|
|
13895
|
-
let literal = Literal.from(content);
|
|
13896
|
-
await __classPrivateFieldGet(this, _SmartLiteral_perspective, "f").setSingleTarget(new Link({
|
|
13897
|
-
source: __classPrivateFieldGet(this, _SmartLiteral_base, "f"),
|
|
13898
|
-
predicate: SMART_LITERAL_CONTENT_PREDICATE,
|
|
13899
|
-
target: literal.toUrl()
|
|
13900
|
-
}));
|
|
13901
|
-
}
|
|
13902
|
-
}
|
|
13903
|
-
_SmartLiteral_perspective = new WeakMap(), _SmartLiteral_base = new WeakMap();
|
|
13904
|
-
|
|
13905
|
-
/**
|
|
13906
|
-
* Shared type definitions for the Ad4mModel system.
|
|
13907
|
-
*
|
|
13908
|
-
* Extracted into a standalone module so that utility files
|
|
13909
|
-
* (`query-utils.ts`, `decorators.ts`, etc.) can import types without
|
|
13910
|
-
* creating circular runtime dependencies on `Ad4mModel.ts`.
|
|
13911
|
-
*/
|
|
13912
|
-
/** Type guard for IncludeProjection objects. */
|
|
13913
|
-
function isIncludeProjection(val) {
|
|
13914
|
-
return typeof val === 'object' && val !== null && 'from' in val;
|
|
13915
|
-
}
|
|
13916
|
-
|
|
13917
|
-
/**
|
|
13918
|
-
* Shared query helpers used by both the Prolog and SPARQL query pipelines.
|
|
13919
|
-
*/
|
|
13920
|
-
/**
|
|
13921
|
-
* Resolves the predicate for a parent query.
|
|
13922
|
-
*
|
|
13923
|
-
* Uses TS discriminated union narrowing:
|
|
13924
|
-
* - Raw form (`{ id, predicate }`) → predicate used as-is
|
|
13925
|
-
* - Model form (`{ model, id, field? }`) → lookup from relation metadata
|
|
13926
|
-
* - With `field`: direct key lookup
|
|
13927
|
-
* - Without `field`: scan for a relation whose `target()` matches `childCtor`
|
|
13928
|
-
*/
|
|
13929
|
-
function resolveParentPredicate(parent, childCtor) {
|
|
13930
|
-
// Raw form — explicit predicate
|
|
13931
|
-
if ('predicate' in parent)
|
|
13932
|
-
return parent.predicate;
|
|
13933
|
-
// Model form — resolve from relation metadata
|
|
13934
|
-
const { model } = parent;
|
|
13935
|
-
const relMeta = getRelationsMetadata(model);
|
|
13936
|
-
// Direct lookup by field name when provided
|
|
13937
|
-
if (parent.field) {
|
|
13938
|
-
const entry = relMeta[parent.field];
|
|
13939
|
-
if (!entry) {
|
|
13940
|
-
throw new Error(`parent(): field "${parent.field}" is not a registered relation on ${model.name}`);
|
|
13941
|
-
}
|
|
13942
|
-
return entry.predicate;
|
|
13943
|
-
}
|
|
13944
|
-
// Fallback: scan for a relation whose target matches the child class
|
|
13945
|
-
for (const [, entry] of Object.entries(relMeta)) {
|
|
13946
|
-
if (entry.target && entry.target() === childCtor) {
|
|
13947
|
-
return entry.predicate;
|
|
13948
|
-
}
|
|
13949
|
-
}
|
|
13950
|
-
throw new Error(`parent(): could not resolve predicate — no relation on ${model.name} targets ${childCtor.name || 'the queried class'}`);
|
|
13951
|
-
}
|
|
13952
|
-
|
|
13953
|
-
/**
|
|
13954
|
-
* JSON Schema → Ad4mModel class builder and related utilities.
|
|
13955
|
-
*
|
|
13956
|
-
* Contains:
|
|
13957
|
-
* - JSON Schema type definitions (JSONSchemaProperty, JSONSchema, JSONSchemaToModelOptions)
|
|
13958
|
-
* - Schema type helpers (normalizeNamespaceString, isArrayType, etc.)
|
|
13959
|
-
* - Predicate / namespace resolution helpers
|
|
13960
|
-
* - `buildModelFromJSONSchema()` — core implementation of `Ad4mModel.fromJSONSchema()`
|
|
13961
|
-
*
|
|
13962
|
-
* @module
|
|
13963
|
-
*/
|
|
13964
|
-
// ─── Schema Type Helpers ─────────────────────────────────────────────────────
|
|
13965
|
-
function normalizeNamespaceString(namespace) {
|
|
13966
|
-
if (!namespace)
|
|
13967
|
-
return '';
|
|
13968
|
-
if (namespace.includes('://')) {
|
|
13969
|
-
const [scheme, rest] = namespace.split('://');
|
|
13970
|
-
const path = (rest || '').replace(/\/+$/, '');
|
|
13971
|
-
return `${scheme}://${path}`;
|
|
13972
|
-
}
|
|
13973
|
-
else {
|
|
13974
|
-
return namespace.replace(/\/+$/, '');
|
|
13975
|
-
}
|
|
13976
|
-
}
|
|
13977
|
-
function normalizeSchemaType(type) {
|
|
13978
|
-
if (!type)
|
|
13979
|
-
return undefined;
|
|
13980
|
-
if (typeof type === "string")
|
|
13981
|
-
return type;
|
|
13982
|
-
if (Array.isArray(type) && type.length > 0) {
|
|
13983
|
-
const nonNull = type.find((t) => t !== "null");
|
|
13984
|
-
return nonNull || type[0];
|
|
13985
|
-
}
|
|
13986
|
-
return undefined;
|
|
13987
|
-
}
|
|
13988
|
-
function isSchemaType(schema, expectedType) {
|
|
13989
|
-
return normalizeSchemaType(schema.type) === expectedType;
|
|
13990
|
-
}
|
|
13991
|
-
function isArrayType(schema) {
|
|
13992
|
-
return isSchemaType(schema, "array");
|
|
13993
|
-
}
|
|
13994
|
-
function isObjectType(schema) {
|
|
13995
|
-
return isSchemaType(schema, "object");
|
|
13996
|
-
}
|
|
13997
|
-
function isNumericType(schema) {
|
|
13998
|
-
const normalized = normalizeSchemaType(schema.type);
|
|
13999
|
-
return normalized === "number" || normalized === "integer";
|
|
14000
|
-
}
|
|
14001
|
-
// ─── Predicate / Namespace Resolution ────────────────────────────────────────
|
|
14002
|
-
/**
|
|
14003
|
-
* Determines the namespace for predicates using cascading precedence:
|
|
14004
|
-
* 1. Explicit namespace in options
|
|
14005
|
-
* 2. x-ad4m metadata in schema
|
|
14006
|
-
* 3. Infer from schema title
|
|
14007
|
-
* 4. Try to extract from $id
|
|
14008
|
-
* 5. Error if nothing works
|
|
14009
|
-
*/
|
|
14010
|
-
function determineNamespace(schema, options) {
|
|
14011
|
-
// 1. Explicit namespace in options (highest precedence)
|
|
14012
|
-
if (options.namespace) {
|
|
14013
|
-
return options.namespace;
|
|
14014
|
-
}
|
|
14015
|
-
// 2. x-ad4m metadata in schema
|
|
14016
|
-
if (schema["x-ad4m"]?.namespace) {
|
|
14017
|
-
return schema["x-ad4m"].namespace;
|
|
14018
|
-
}
|
|
14019
|
-
// 3. Infer from schema title
|
|
14020
|
-
if (schema.title) {
|
|
14021
|
-
return `${schema.title.toLowerCase()}://`;
|
|
14022
|
-
}
|
|
14023
|
-
// 4. Try to extract from $id if it's a URL
|
|
14024
|
-
if (schema.$id) {
|
|
14025
|
-
try {
|
|
14026
|
-
const url = new URL(schema.$id);
|
|
14027
|
-
const pathParts = url.pathname.split('/').filter(p => p);
|
|
14028
|
-
if (pathParts.length > 0) {
|
|
14029
|
-
const lastPart = pathParts[pathParts.length - 1];
|
|
14030
|
-
const baseName = lastPart.replace(/\.schema\.json$/, '').replace(/\.json$/, '');
|
|
14031
|
-
return `${baseName.toLowerCase()}://`;
|
|
14032
|
-
}
|
|
14033
|
-
}
|
|
14034
|
-
catch {
|
|
14035
|
-
// If $id is not a valid URL, continue to error
|
|
14036
|
-
}
|
|
14037
|
-
}
|
|
14038
|
-
// 5. Error if no namespace can be determined
|
|
14039
|
-
throw new Error(`Cannot infer namespace for JSON Schema. Please provide one of:
|
|
14040
|
-
- options.namespace
|
|
14041
|
-
- schema["x-ad4m"].namespace
|
|
14042
|
-
- schema.title
|
|
14043
|
-
- valid schema.$id`);
|
|
14044
|
-
}
|
|
14045
|
-
/**
|
|
14046
|
-
* Determines the predicate for a specific property using cascading precedence:
|
|
14047
|
-
* 1. Explicit property mapping
|
|
14048
|
-
* 2. x-ad4m metadata in property schema
|
|
14049
|
-
* 3. Predicate template
|
|
14050
|
-
* 4. Custom predicate generator
|
|
14051
|
-
* 5. Default: namespace + property name
|
|
14052
|
-
*/
|
|
14053
|
-
function determinePredicate(schema, propertyName, propertySchema, namespace, options) {
|
|
14054
|
-
// 1. Explicit property mapping (highest precedence)
|
|
14055
|
-
if (options.propertyMapping?.[propertyName]) {
|
|
14056
|
-
return options.propertyMapping[propertyName];
|
|
13590
|
+
// 5. Error if no namespace can be determined
|
|
13591
|
+
throw new Error(`Cannot infer namespace for JSON Schema. Please provide one of:
|
|
13592
|
+
- options.namespace
|
|
13593
|
+
- schema["x-ad4m"].namespace
|
|
13594
|
+
- schema.title
|
|
13595
|
+
- valid schema.$id`);
|
|
13596
|
+
}
|
|
13597
|
+
/**
|
|
13598
|
+
* Determines the predicate for a specific property using cascading precedence:
|
|
13599
|
+
* 1. Explicit property mapping
|
|
13600
|
+
* 2. x-ad4m metadata in property schema
|
|
13601
|
+
* 3. Predicate template
|
|
13602
|
+
* 4. Custom predicate generator
|
|
13603
|
+
* 5. Default: namespace + property name
|
|
13604
|
+
*/
|
|
13605
|
+
function determinePredicate(schema, propertyName, propertySchema, namespace, options) {
|
|
13606
|
+
// 1. Explicit property mapping (highest precedence)
|
|
13607
|
+
if (options.propertyMapping?.[propertyName]) {
|
|
13608
|
+
return options.propertyMapping[propertyName];
|
|
14057
13609
|
}
|
|
14058
13610
|
// 2. x-ad4m metadata in property schema
|
|
14059
13611
|
if (propertySchema["x-ad4m"]?.through) {
|
|
@@ -14923,25 +14475,25 @@ class ModelQueryBuilder {
|
|
|
14923
14475
|
return this;
|
|
14924
14476
|
}
|
|
14925
14477
|
/**
|
|
14926
|
-
*
|
|
14478
|
+
* Controls whether SPARQL property getters are evaluated during hydration.
|
|
14927
14479
|
*
|
|
14928
|
-
* By default, collection queries
|
|
14929
|
-
* Call `.deepQuery()`
|
|
14480
|
+
* By default, collection queries evaluate property getters (deepQuery=true).
|
|
14481
|
+
* Call `.deepQuery(false)` to skip getter evaluation for performance.
|
|
14930
14482
|
*
|
|
14483
|
+
* @param enabled - Whether to evaluate property getters (default: true)
|
|
14931
14484
|
* @returns The query builder for chaining
|
|
14932
14485
|
*
|
|
14933
14486
|
* @example
|
|
14934
14487
|
* ```typescript
|
|
14935
14488
|
* const messages = await Message.query(perspective)
|
|
14936
14489
|
* .parent(channel)
|
|
14937
|
-
* .deepQuery()
|
|
14490
|
+
* .deepQuery(false) // skip property getters for performance
|
|
14938
14491
|
* .limit(30)
|
|
14939
14492
|
* .get();
|
|
14940
|
-
* // messages[i].replyingTo is populated
|
|
14941
14493
|
* ```
|
|
14942
14494
|
*/
|
|
14943
|
-
deepQuery() {
|
|
14944
|
-
this.queryParams.deepQuery =
|
|
14495
|
+
deepQuery(enabled = true) {
|
|
14496
|
+
this.queryParams.deepQuery = enabled;
|
|
14945
14497
|
return this;
|
|
14946
14498
|
}
|
|
14947
14499
|
/**
|
|
@@ -15103,9 +14655,15 @@ class ModelQueryBuilder {
|
|
|
15103
14655
|
console.error('Model subscription update parse error:', e);
|
|
15104
14656
|
}
|
|
15105
14657
|
});
|
|
15106
|
-
// Set up keepalive
|
|
14658
|
+
// Set up keepalive with failure tracking
|
|
14659
|
+
let keepaliveFailures = 0;
|
|
15107
14660
|
const keepaliveTimer = setInterval(() => {
|
|
15108
|
-
this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).
|
|
14661
|
+
this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
|
|
14662
|
+
keepaliveFailures = 0;
|
|
14663
|
+
}).catch((e) => {
|
|
14664
|
+
keepaliveFailures++;
|
|
14665
|
+
console.warn(`Model subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
|
|
14666
|
+
});
|
|
15109
14667
|
}, 30000);
|
|
15110
14668
|
// Store dispose function
|
|
15111
14669
|
this.currentSubscription = {
|
|
@@ -15200,8 +14758,14 @@ class ModelQueryBuilder {
|
|
|
15200
14758
|
console.error('Count subscription update parse error:', e);
|
|
15201
14759
|
}
|
|
15202
14760
|
});
|
|
14761
|
+
let keepaliveFailures = 0;
|
|
15203
14762
|
const keepaliveTimer = setInterval(() => {
|
|
15204
|
-
this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).
|
|
14763
|
+
this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
|
|
14764
|
+
keepaliveFailures = 0;
|
|
14765
|
+
}).catch((e) => {
|
|
14766
|
+
keepaliveFailures++;
|
|
14767
|
+
console.warn(`Count subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
|
|
14768
|
+
});
|
|
15205
14769
|
}, 30000);
|
|
15206
14770
|
this.currentSubscription = {
|
|
15207
14771
|
dispose: () => {
|
|
@@ -15304,8 +14868,14 @@ class ModelQueryBuilder {
|
|
|
15304
14868
|
return;
|
|
15305
14869
|
processResults().catch(e => console.error('Paginate subscription error:', e));
|
|
15306
14870
|
});
|
|
14871
|
+
let keepaliveFailures = 0;
|
|
15307
14872
|
const keepaliveTimer = setInterval(() => {
|
|
15308
|
-
this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).
|
|
14873
|
+
this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
|
|
14874
|
+
keepaliveFailures = 0;
|
|
14875
|
+
}).catch((e) => {
|
|
14876
|
+
keepaliveFailures++;
|
|
14877
|
+
console.warn(`Paginate subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
|
|
14878
|
+
});
|
|
15309
14879
|
}, 30000);
|
|
15310
14880
|
this.currentSubscription = {
|
|
15311
14881
|
dispose: () => {
|
|
@@ -15330,12 +14900,9 @@ class ModelQueryBuilder {
|
|
|
15330
14900
|
/**
|
|
15331
14901
|
* hydration.ts — Instance hydration helpers extracted from Ad4mModel.
|
|
15332
14902
|
*
|
|
15333
|
-
* After the Rust model_query pipeline migration
|
|
15334
|
-
*
|
|
14903
|
+
* After the Rust model_query pipeline migration, most hydration logic moved
|
|
14904
|
+
* to Rust. This file retains:
|
|
15335
14905
|
* - normalizeValue() — snapshot dirty-tracking
|
|
15336
|
-
* - matchesCondition() — JS-side post-filter (used by evaluateCustomGettersForInstance)
|
|
15337
|
-
* - evaluateCustomGettersForInstance() — lazy getter evaluation (Ad4mModel.evaluateGetters)
|
|
15338
|
-
* - buildConformanceGetter() — conformance SPARQL generation for relation getters
|
|
15339
14906
|
*/
|
|
15340
14907
|
// ──────────────────────────────────────────────────────────
|
|
15341
14908
|
// Pure helpers
|
|
@@ -15351,258 +14918,6 @@ function normalizeValue(value) {
|
|
|
15351
14918
|
}
|
|
15352
14919
|
return value;
|
|
15353
14920
|
}
|
|
15354
|
-
/**
|
|
15355
|
-
* Checks if a value matches a where-condition (for post-query filtering).
|
|
15356
|
-
*/
|
|
15357
|
-
function matchesCondition(value, condition) {
|
|
15358
|
-
// Handle array values (IN clause)
|
|
15359
|
-
if (Array.isArray(condition)) {
|
|
15360
|
-
return condition.includes(value);
|
|
15361
|
-
}
|
|
15362
|
-
// Handle operator object
|
|
15363
|
-
if (typeof condition === 'object' && condition !== null) {
|
|
15364
|
-
const ops = condition;
|
|
15365
|
-
// Special case: 'not' operator (exclusive with other operators)
|
|
15366
|
-
if (ops.not !== undefined) {
|
|
15367
|
-
if (Array.isArray(ops.not)) {
|
|
15368
|
-
return !ops.not.includes(value);
|
|
15369
|
-
}
|
|
15370
|
-
else {
|
|
15371
|
-
return value !== ops.not;
|
|
15372
|
-
}
|
|
15373
|
-
}
|
|
15374
|
-
// Special case: 'between' operator (inclusive range, exclusive with gt/gte/lt/lte)
|
|
15375
|
-
if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
|
|
15376
|
-
return value >= ops.between[0] && value <= ops.between[1];
|
|
15377
|
-
}
|
|
15378
|
-
// For all other operators (gt, gte, lt, lte, contains), we need to check ALL of them
|
|
15379
|
-
// and return true only if ALL conditions are satisfied
|
|
15380
|
-
let allConditionsMet = true;
|
|
15381
|
-
if (ops.gt !== undefined) {
|
|
15382
|
-
allConditionsMet = allConditionsMet && (value > ops.gt);
|
|
15383
|
-
}
|
|
15384
|
-
if (ops.gte !== undefined) {
|
|
15385
|
-
allConditionsMet = allConditionsMet && (value >= ops.gte);
|
|
15386
|
-
}
|
|
15387
|
-
if (ops.lt !== undefined) {
|
|
15388
|
-
allConditionsMet = allConditionsMet && (value < ops.lt);
|
|
15389
|
-
}
|
|
15390
|
-
if (ops.lte !== undefined) {
|
|
15391
|
-
allConditionsMet = allConditionsMet && (value <= ops.lte);
|
|
15392
|
-
}
|
|
15393
|
-
if (ops.contains !== undefined) {
|
|
15394
|
-
if (typeof value === 'string') {
|
|
15395
|
-
allConditionsMet = allConditionsMet && value.includes(String(ops.contains));
|
|
15396
|
-
}
|
|
15397
|
-
else if (Array.isArray(value)) {
|
|
15398
|
-
allConditionsMet = allConditionsMet && value.includes(ops.contains);
|
|
15399
|
-
}
|
|
15400
|
-
else {
|
|
15401
|
-
allConditionsMet = false;
|
|
15402
|
-
}
|
|
15403
|
-
}
|
|
15404
|
-
return allConditionsMet;
|
|
15405
|
-
}
|
|
15406
|
-
// Simple equality
|
|
15407
|
-
return value === condition;
|
|
15408
|
-
}
|
|
15409
|
-
// ──────────────────────────────────────────────────────────
|
|
15410
|
-
// SPARQL custom getter evaluation
|
|
15411
|
-
// ──────────────────────────────────────────────────────────
|
|
15412
|
-
/**
|
|
15413
|
-
* Builds a SPARQL conformance getter for a relation whose `target` model
|
|
15414
|
-
* is known but no explicit `getter` string was supplied.
|
|
15415
|
-
*
|
|
15416
|
-
* The generated getter traverses outgoing links matching the relation's
|
|
15417
|
-
* predicate and then filters the target nodes to only those that conform to
|
|
15418
|
-
* the target model's shape (required properties / flags).
|
|
15419
|
-
*
|
|
15420
|
-
* Delegates to the shared `buildConformanceFilter()` utility in decorators.ts
|
|
15421
|
-
* so the same logic is used at shape-definition time and at query time.
|
|
15422
|
-
*
|
|
15423
|
-
* @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
|
|
15424
|
-
* @param targetClass - The target model class (result of calling the `target()` thunk)
|
|
15425
|
-
* @returns A SPARQL expression string, or `undefined` if no conformance
|
|
15426
|
-
* conditions could be derived from the target model.
|
|
15427
|
-
*/
|
|
15428
|
-
function buildConformanceGetter(relationPredicate, targetClass) {
|
|
15429
|
-
const filter = buildConformanceFilter(relationPredicate, targetClass);
|
|
15430
|
-
if (!filter) {
|
|
15431
|
-
const targetName = targetClass?.prototype?.className || targetClass?.name || 'unknown';
|
|
15432
|
-
console.warn(`[Ad4mModel] buildConformanceGetter: no conditions found for target "${targetName}".`);
|
|
15433
|
-
return undefined;
|
|
15434
|
-
}
|
|
15435
|
-
return filter.getter;
|
|
15436
|
-
}
|
|
15437
|
-
/**
|
|
15438
|
-
* Evaluates custom SurrealQL getters for properties and relations on a specific instance.
|
|
15439
|
-
*
|
|
15440
|
-
* For relations that declare a `target` but no explicit `getter`, a conformance
|
|
15441
|
-
* getter is auto-generated from the target model's metadata (unless `filter: false`).
|
|
15442
|
-
*/
|
|
15443
|
-
async function evaluateCustomGettersForInstance(instance, perspective, metadata, options) {
|
|
15444
|
-
`<${instance.id}>`;
|
|
15445
|
-
// Build projection filter — when requestedProperties is active, only
|
|
15446
|
-
// evaluate getters for fields that are requested (or included).
|
|
15447
|
-
const projectionActive = options?.requestedProperties && options.requestedProperties.length > 0;
|
|
15448
|
-
const projectionSet = projectionActive ? new Set(options.requestedProperties) : null;
|
|
15449
|
-
// Evaluate property getters (skip when caller only wants relation type-filtering)
|
|
15450
|
-
if (!options?.skipPropertyGetters) {
|
|
15451
|
-
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
15452
|
-
if (projectionSet && !projectionSet.has(propName))
|
|
15453
|
-
continue;
|
|
15454
|
-
if (propMeta.getter) {
|
|
15455
|
-
try {
|
|
15456
|
-
const rawGetter = propMeta.getter;
|
|
15457
|
-
const getterWithBase = rawGetter.replace(/\?source\b/g, `<${instance.id}>`).replace(/<Base>/g, `<${instance.id}>`).replace(/Base/g, `<${instance.id}>`);
|
|
15458
|
-
// If the getter is already SPARQL (starts with SELECT/ASK/CONSTRUCT), execute directly
|
|
15459
|
-
const trimmed = getterWithBase.trim().toUpperCase();
|
|
15460
|
-
if (trimmed.startsWith('SELECT') || trimmed.startsWith('ASK') || trimmed.startsWith('CONSTRUCT')) {
|
|
15461
|
-
const result = await perspective.querySparql(getterWithBase);
|
|
15462
|
-
if (trimmed.startsWith('ASK')) {
|
|
15463
|
-
instance[propName] = result === true || result === 'true';
|
|
15464
|
-
}
|
|
15465
|
-
else if (result && result.length > 0) {
|
|
15466
|
-
// Get first binding's first value
|
|
15467
|
-
const firstRow = result[0];
|
|
15468
|
-
const firstKey = Object.keys(firstRow)[0];
|
|
15469
|
-
const val = firstRow[firstKey]?.value ?? firstRow[firstKey];
|
|
15470
|
-
if (val !== undefined && val !== null && val !== 'None' && val !== '') {
|
|
15471
|
-
instance[propName] = val;
|
|
15472
|
-
}
|
|
15473
|
-
}
|
|
15474
|
-
}
|
|
15475
|
-
else {
|
|
15476
|
-
// Legacy SurrealDB-style getter — safety guard for getters that don't match
|
|
15477
|
-
// SPARQL patterns (SELECT/ASK). Logs a warning but does not crash.
|
|
15478
|
-
console.warn(`Unsupported legacy getter syntax for property ${propName} — use native SPARQL (SELECT/ASK): ${rawGetter.slice(0, 100)}`);
|
|
15479
|
-
}
|
|
15480
|
-
}
|
|
15481
|
-
catch (error) {
|
|
15482
|
-
console.warn(`Failed to evaluate getter for ${propName}:`, error);
|
|
15483
|
-
}
|
|
15484
|
-
}
|
|
15485
|
-
}
|
|
15486
|
-
} // end skipPropertyGetters guard
|
|
15487
|
-
// Evaluate relation getters (explicit or auto-generated from target)
|
|
15488
|
-
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
15489
|
-
// Skip relations excluded by property projection (unless in include map)
|
|
15490
|
-
if (projectionSet && !projectionSet.has(relName) && !(options?.include && relName in options.include))
|
|
15491
|
-
continue;
|
|
15492
|
-
const meta = relMeta;
|
|
15493
|
-
// Determine the getter to execute:
|
|
15494
|
-
// 1. Explicit `getter` always wins
|
|
15495
|
-
// 2. If `target` is set and `filter !== false`, auto-generate conformance getter
|
|
15496
|
-
// BUT skip auto-generation for reverse relations (belongsToMany / belongsToOne)
|
|
15497
|
-
// because buildConformanceGetter traverses outgoing links which is wrong for
|
|
15498
|
-
// reverse relations. Their values are already populated by the reverse link
|
|
15499
|
-
// lookup in instancesFromQueryResult / getData.
|
|
15500
|
-
let getter = meta.getter;
|
|
15501
|
-
if (!getter && meta.where && meta.direction !== 'reverse') {
|
|
15502
|
-
try {
|
|
15503
|
-
const TargetClass = meta.target?.();
|
|
15504
|
-
const targetMetadata = TargetClass
|
|
15505
|
-
? TargetClass.getModelMetadata?.() ?? null
|
|
15506
|
-
: null;
|
|
15507
|
-
// Check if all where conditions can be SPARQL-filtered.
|
|
15508
|
-
// literal-resolved properties store signed expressions (literal:json:{…}),
|
|
15509
|
-
// not raw literal:string: IRIs, so SPARQL exact-match fails for them.
|
|
15510
|
-
let allSparqlFilterable = true;
|
|
15511
|
-
if (targetMetadata) {
|
|
15512
|
-
for (const propName of Object.keys(meta.where)) {
|
|
15513
|
-
if (['id', 'author', 'timestamp'].includes(propName))
|
|
15514
|
-
continue;
|
|
15515
|
-
const propMeta = targetMetadata.properties[propName];
|
|
15516
|
-
if (propMeta && (!propMeta.resolveLanguage || propMeta.resolveLanguage === 'literal')) {
|
|
15517
|
-
allSparqlFilterable = false;
|
|
15518
|
-
break;
|
|
15519
|
-
}
|
|
15520
|
-
}
|
|
15521
|
-
}
|
|
15522
|
-
else {
|
|
15523
|
-
allSparqlFilterable = false;
|
|
15524
|
-
}
|
|
15525
|
-
if (allSparqlFilterable) {
|
|
15526
|
-
const conditions = compileWhereClause(meta.where, targetMetadata);
|
|
15527
|
-
if (conditions.length > 0) {
|
|
15528
|
-
const escapedPredicate = escapeQueryString(meta.predicate);
|
|
15529
|
-
getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;
|
|
15530
|
-
}
|
|
15531
|
-
}
|
|
15532
|
-
// If not filterable, fall through to buildConformanceGetter + JS post-filter below
|
|
15533
|
-
}
|
|
15534
|
-
catch (e) {
|
|
15535
|
-
console.warn(`[Ad4mModel] where-clause compilation failed for relation "${relName}":`, e);
|
|
15536
|
-
}
|
|
15537
|
-
}
|
|
15538
|
-
if (!getter && meta.target && meta.filter !== false && meta.direction !== 'reverse') {
|
|
15539
|
-
try {
|
|
15540
|
-
const TargetClass = meta.target();
|
|
15541
|
-
getter = buildConformanceGetter(meta.predicate, TargetClass);
|
|
15542
|
-
if (!getter) {
|
|
15543
|
-
console.warn(`[Ad4mModel] buildConformanceGetter returned undefined for relation "${relName}" (predicate: "${meta.predicate}")`);
|
|
15544
|
-
}
|
|
15545
|
-
}
|
|
15546
|
-
catch (e) {
|
|
15547
|
-
console.warn(`[Ad4mModel] auto-generation failed for relation "${relName}":`, e);
|
|
15548
|
-
}
|
|
15549
|
-
}
|
|
15550
|
-
if (getter) {
|
|
15551
|
-
try {
|
|
15552
|
-
const getterWithBase = getter.replace(/\?source\b/g, `<${instance.id}>`).replace(/<Base>/g, `<${instance.id}>`).replace(/\bBase\b/g, `<${instance.id}>`);
|
|
15553
|
-
const trimmed = getterWithBase.trim().toUpperCase();
|
|
15554
|
-
if (trimmed.startsWith('SELECT') || trimmed.startsWith('ASK') || trimmed.startsWith('CONSTRUCT')) {
|
|
15555
|
-
// Native SPARQL getter — execute directly
|
|
15556
|
-
const result = await perspective.querySparql(getterWithBase);
|
|
15557
|
-
if (result && result.length > 0) {
|
|
15558
|
-
const values = result.map((r) => {
|
|
15559
|
-
const firstKey = Object.keys(r)[0];
|
|
15560
|
-
return r[firstKey]?.value ?? r[firstKey];
|
|
15561
|
-
}).filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None');
|
|
15562
|
-
instance[relName] = values;
|
|
15563
|
-
}
|
|
15564
|
-
}
|
|
15565
|
-
else {
|
|
15566
|
-
// Legacy SurrealDB-style getter — safety guard for relation getters that don't
|
|
15567
|
-
// match SPARQL patterns (SELECT/ASK). Logs a warning but does not crash.
|
|
15568
|
-
console.warn(`Unsupported legacy getter syntax for relation ${relName} — use native SPARQL (SELECT/ASK): ${getter.slice(0, 100)}`);
|
|
15569
|
-
}
|
|
15570
|
-
}
|
|
15571
|
-
catch (error) {
|
|
15572
|
-
console.warn(`Failed to evaluate getter for ${relName}:`, error);
|
|
15573
|
-
}
|
|
15574
|
-
}
|
|
15575
|
-
// JS post-filter for where conditions that couldn't be SPARQL-filtered
|
|
15576
|
-
// (e.g. literal-resolved properties storing signed expressions)
|
|
15577
|
-
const currentValues = instance[relName];
|
|
15578
|
-
if (meta.where && Array.isArray(currentValues) && currentValues.length > 0) {
|
|
15579
|
-
const TargetClass = meta.target?.();
|
|
15580
|
-
if (TargetClass) {
|
|
15581
|
-
const filtered = [];
|
|
15582
|
-
for (const targetId of currentValues) {
|
|
15583
|
-
try {
|
|
15584
|
-
const inst = new TargetClass(perspective, targetId);
|
|
15585
|
-
await inst.get();
|
|
15586
|
-
let matches = true;
|
|
15587
|
-
for (const [prop, expected] of Object.entries(meta.where)) {
|
|
15588
|
-
if (inst[prop] !== expected) {
|
|
15589
|
-
matches = false;
|
|
15590
|
-
break;
|
|
15591
|
-
}
|
|
15592
|
-
}
|
|
15593
|
-
if (matches)
|
|
15594
|
-
filtered.push(targetId);
|
|
15595
|
-
}
|
|
15596
|
-
catch {
|
|
15597
|
-
// If we can't hydrate, keep the value (conservative)
|
|
15598
|
-
filtered.push(targetId);
|
|
15599
|
-
}
|
|
15600
|
-
}
|
|
15601
|
-
instance[relName] = filtered;
|
|
15602
|
-
}
|
|
15603
|
-
}
|
|
15604
|
-
}
|
|
15605
|
-
}
|
|
15606
14921
|
|
|
15607
14922
|
// ---------------------------------------------------------------------------
|
|
15608
14923
|
// Helpers for Rust-side include resolution
|
|
@@ -16242,6 +15557,7 @@ class Ad4mModel {
|
|
|
16242
15557
|
const query = {
|
|
16243
15558
|
where: { id: this._baseExpression },
|
|
16244
15559
|
limit: 1,
|
|
15560
|
+
deepQuery: true, // Single-instance get() always evaluates property getters
|
|
16245
15561
|
};
|
|
16246
15562
|
if (opts?.properties)
|
|
16247
15563
|
query.properties = opts.properties;
|
|
@@ -16350,6 +15666,7 @@ class Ad4mModel {
|
|
|
16350
15666
|
queryInput.limit = query.limit;
|
|
16351
15667
|
if (query.count !== undefined)
|
|
16352
15668
|
queryInput.count = query.count;
|
|
15669
|
+
queryInput.deepQuery = query.deepQuery ?? true;
|
|
16353
15670
|
if (query.include) {
|
|
16354
15671
|
const allRelMeta = getRelationsMetadata(this);
|
|
16355
15672
|
enrichShapeForIncludes(metadata, query.include, allRelMeta);
|
|
@@ -16367,10 +15684,10 @@ class Ad4mModel {
|
|
|
16367
15684
|
try {
|
|
16368
15685
|
const TargetClass = meta.target();
|
|
16369
15686
|
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
16370
|
-
//
|
|
16371
|
-
//
|
|
16372
|
-
//
|
|
16373
|
-
//
|
|
15687
|
+
// Compile where clauses to SPARQL when all target properties use
|
|
15688
|
+
// literal encoding (literal:string:X etc.) which is SPARQL-matchable.
|
|
15689
|
+
// Properties with a non-literal resolveLanguage store expression hashes
|
|
15690
|
+
// that can't be matched by value in SPARQL.
|
|
16374
15691
|
let whereConditions = [];
|
|
16375
15692
|
if (rel.where) {
|
|
16376
15693
|
try {
|
|
@@ -16381,15 +15698,12 @@ class Ad4mModel {
|
|
|
16381
15698
|
if (['id', 'author', 'timestamp'].includes(propName))
|
|
16382
15699
|
continue;
|
|
16383
15700
|
const propMeta = targetMetadata.properties[propName];
|
|
16384
|
-
if (propMeta &&
|
|
15701
|
+
if (propMeta?.resolveLanguage && propMeta.resolveLanguage !== 'literal') {
|
|
16385
15702
|
allSparqlFilterable = false;
|
|
16386
15703
|
break;
|
|
16387
15704
|
}
|
|
16388
15705
|
}
|
|
16389
15706
|
}
|
|
16390
|
-
else {
|
|
16391
|
-
allSparqlFilterable = false;
|
|
16392
|
-
}
|
|
16393
15707
|
if (allSparqlFilterable) {
|
|
16394
15708
|
whereConditions = compileWhereClause(rel.where, targetMetadata);
|
|
16395
15709
|
}
|
|
@@ -16509,6 +15823,7 @@ class Ad4mModel {
|
|
|
16509
15823
|
queryInput.limit = query.limit;
|
|
16510
15824
|
if (query.count !== undefined)
|
|
16511
15825
|
queryInput.count = query.count;
|
|
15826
|
+
queryInput.deepQuery = query.deepQuery ?? true;
|
|
16512
15827
|
// Enrich relation metadata with target class shapes for Rust-side
|
|
16513
15828
|
// include resolution. This eliminates per-relation GraphQL round-trips
|
|
16514
15829
|
// by letting the Rust endpoint resolve includes in-process.
|
|
@@ -16538,10 +15853,10 @@ class Ad4mModel {
|
|
|
16538
15853
|
try {
|
|
16539
15854
|
const TargetClass = meta.target();
|
|
16540
15855
|
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
16541
|
-
//
|
|
16542
|
-
//
|
|
16543
|
-
//
|
|
16544
|
-
//
|
|
15856
|
+
// Compile where clauses to SPARQL when all target properties use
|
|
15857
|
+
// literal encoding (literal:string:X etc.) which is SPARQL-matchable.
|
|
15858
|
+
// Properties with a non-literal resolveLanguage store expression hashes
|
|
15859
|
+
// that can't be matched by value in SPARQL.
|
|
16545
15860
|
let whereConditions = [];
|
|
16546
15861
|
if (rel.where) {
|
|
16547
15862
|
try {
|
|
@@ -16552,15 +15867,12 @@ class Ad4mModel {
|
|
|
16552
15867
|
if (['id', 'author', 'timestamp'].includes(propName))
|
|
16553
15868
|
continue;
|
|
16554
15869
|
const propMeta = targetMetadata.properties[propName];
|
|
16555
|
-
if (propMeta &&
|
|
15870
|
+
if (propMeta?.resolveLanguage && propMeta.resolveLanguage !== 'literal') {
|
|
16556
15871
|
allSparqlFilterable = false;
|
|
16557
15872
|
break;
|
|
16558
15873
|
}
|
|
16559
15874
|
}
|
|
16560
15875
|
}
|
|
16561
|
-
else {
|
|
16562
|
-
allSparqlFilterable = false;
|
|
16563
|
-
}
|
|
16564
15876
|
if (allSparqlFilterable) {
|
|
16565
15877
|
whereConditions = compileWhereClause(rel.where, targetMetadata);
|
|
16566
15878
|
}
|
|
@@ -16591,6 +15903,13 @@ class Ad4mModel {
|
|
|
16591
15903
|
// the TS decorators are the definitive source of truth.
|
|
16592
15904
|
const shapeJson = JSON.stringify(metadata);
|
|
16593
15905
|
const queryJson = JSON.stringify(queryInput);
|
|
15906
|
+
// TEMP DEBUG: Log getters with where-clause filters to diagnose CI failure
|
|
15907
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
15908
|
+
const rel = relMeta;
|
|
15909
|
+
if (rel.where) {
|
|
15910
|
+
console.log(`[MODEL_QUERY_DEBUG] relation="${relName}" getter=${rel.getter ?? 'NONE'} where=${JSON.stringify(rel.where)}`);
|
|
15911
|
+
}
|
|
15912
|
+
}
|
|
16594
15913
|
const result = await perspective.modelQuery(className, queryJson, shapeJson);
|
|
16595
15914
|
// Convert JSON instances to model class instances, recursively constructing
|
|
16596
15915
|
// class instances for any included relations resolved by Rust.
|
|
@@ -16627,40 +15946,6 @@ class Ad4mModel {
|
|
|
16627
15946
|
}
|
|
16628
15947
|
}));
|
|
16629
15948
|
}
|
|
16630
|
-
// Relation conformance getters are evaluated Rust-side via evaluate_getters()
|
|
16631
|
-
// in model_query.rs. However, for relations with non-SPARQL-filterable where
|
|
16632
|
-
// clauses (e.g. properties stored as signed expressions), we still need
|
|
16633
|
-
// TS-side evaluation as a fallback. Running evaluateCustomGettersForInstance
|
|
16634
|
-
// with skipPropertyGetters ensures conformance + JS post-filtering for
|
|
16635
|
-
// where clauses that couldn't be compiled to SPARQL.
|
|
16636
|
-
const includedRelNames = queryInput.include ? new Set(Object.keys(queryInput.include)) : new Set();
|
|
16637
|
-
for (const inst of instances) {
|
|
16638
|
-
// Save included relation values that came from Rust hydration
|
|
16639
|
-
const savedIncluded = {};
|
|
16640
|
-
for (const relName of includedRelNames) {
|
|
16641
|
-
if (inst[relName] !== undefined) {
|
|
16642
|
-
savedIncluded[relName] = inst[relName];
|
|
16643
|
-
}
|
|
16644
|
-
}
|
|
16645
|
-
await evaluateCustomGettersForInstance(inst, perspective, metadata, {
|
|
16646
|
-
skipPropertyGetters: true,
|
|
16647
|
-
});
|
|
16648
|
-
// Restore hydrated include objects that were overwritten by conformance getters
|
|
16649
|
-
for (const [relName, value] of Object.entries(savedIncluded)) {
|
|
16650
|
-
inst[relName] = value;
|
|
16651
|
-
}
|
|
16652
|
-
// Fix cardinality for non-included HasOne/BelongsToOne relations:
|
|
16653
|
-
// The conformance getter always produces arrays; unwrap to scalar.
|
|
16654
|
-
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
16655
|
-
if (includedRelNames.has(relName))
|
|
16656
|
-
continue;
|
|
16657
|
-
const kind = relMeta.kind;
|
|
16658
|
-
if ((kind === 'hasOne' || kind === 'belongsToOne') && Array.isArray(inst[relName])) {
|
|
16659
|
-
const arr = inst[relName];
|
|
16660
|
-
inst[relName] = arr.length > 0 ? arr[0] : null;
|
|
16661
|
-
}
|
|
16662
|
-
}
|
|
16663
|
-
}
|
|
16664
15949
|
// Take snapshots for dirty tracking
|
|
16665
15950
|
const snapshotRelations = queryInput.include;
|
|
16666
15951
|
for (const inst of instances) {
|
|
@@ -17088,10 +16373,10 @@ class Ad4mModel {
|
|
|
17088
16373
|
/**
|
|
17089
16374
|
* Evaluate SPARQL getters for a batch of instances on demand.
|
|
17090
16375
|
*
|
|
17091
|
-
*
|
|
17092
|
-
*
|
|
17093
|
-
*
|
|
17094
|
-
* a
|
|
16376
|
+
* Since deepQuery defaults to true, property getters are evaluated
|
|
16377
|
+
* automatically during collection queries. Use this method when
|
|
16378
|
+
* deepQuery was explicitly set to false and you want to lazily
|
|
16379
|
+
* resolve getter-backed properties for a subset of instances.
|
|
17095
16380
|
*
|
|
17096
16381
|
* @param instances - Array of model instances to evaluate getters on
|
|
17097
16382
|
* @param perspective - The perspective to query against
|
|
@@ -17100,8 +16385,8 @@ class Ad4mModel {
|
|
|
17100
16385
|
*
|
|
17101
16386
|
* @example
|
|
17102
16387
|
* ```typescript
|
|
17103
|
-
* const messages = await Message.
|
|
17104
|
-
* // messages[i].replyingTo is undefined (getter skipped
|
|
16388
|
+
* const messages = await Message.query(perspective).deepQuery(false).limit(30).get();
|
|
16389
|
+
* // messages[i].replyingTo is undefined (getter skipped)
|
|
17105
16390
|
*
|
|
17106
16391
|
* // Evaluate getters for the visible subset
|
|
17107
16392
|
* await Message.evaluateGetters(messages.slice(0, 10), perspective, ['replyingTo']);
|
|
@@ -17112,10 +16397,28 @@ class Ad4mModel {
|
|
|
17112
16397
|
if (instances.length === 0)
|
|
17113
16398
|
return;
|
|
17114
16399
|
const metadata = this.getModelMetadata();
|
|
17115
|
-
|
|
17116
|
-
|
|
17117
|
-
|
|
17118
|
-
|
|
16400
|
+
// Pre-compute conformance getters so the shape sent to Rust includes them
|
|
16401
|
+
const allRelMeta = getRelationsMetadata(this);
|
|
16402
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
16403
|
+
const rel = relMeta;
|
|
16404
|
+
if (rel.getter || rel.direction === 'reverse' || rel.filter === false)
|
|
16405
|
+
continue;
|
|
16406
|
+
const meta = allRelMeta[relName];
|
|
16407
|
+
if (!meta?.target)
|
|
16408
|
+
continue;
|
|
16409
|
+
try {
|
|
16410
|
+
const TargetClass = meta.target();
|
|
16411
|
+
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
16412
|
+
if (filter)
|
|
16413
|
+
rel.getter = filter.getter;
|
|
16414
|
+
}
|
|
16415
|
+
catch (_) { /* target class may not be available */ }
|
|
16416
|
+
}
|
|
16417
|
+
const shapeJson = JSON.stringify(metadata);
|
|
16418
|
+
const instanceIds = instances.map(inst => inst.id || inst._baseExpression);
|
|
16419
|
+
// Single RPC call evaluates all getters in-process on the executor
|
|
16420
|
+
const result = await perspective.evaluateGetters(metadata.className, instanceIds, shapeJson, propertyNames);
|
|
16421
|
+
// Determine which property names were evaluated for snapshot sync
|
|
17119
16422
|
const evaluatedPropertyNames = [];
|
|
17120
16423
|
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
17121
16424
|
if (propMeta.getter) {
|
|
@@ -17124,13 +16427,24 @@ class Ad4mModel {
|
|
|
17124
16427
|
}
|
|
17125
16428
|
}
|
|
17126
16429
|
}
|
|
16430
|
+
// Also include relation getters
|
|
16431
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
16432
|
+
if (relMeta.getter) {
|
|
16433
|
+
if (!propertyNames || propertyNames.length === 0 || propertyNames.includes(relName)) {
|
|
16434
|
+
evaluatedPropertyNames.push(relName);
|
|
16435
|
+
}
|
|
16436
|
+
}
|
|
16437
|
+
}
|
|
16438
|
+
// Apply results to instances and sync snapshots
|
|
17127
16439
|
for (const instance of instances) {
|
|
17128
|
-
|
|
17129
|
-
|
|
17130
|
-
|
|
17131
|
-
|
|
17132
|
-
|
|
17133
|
-
|
|
16440
|
+
const id = instance.id || instance._baseExpression;
|
|
16441
|
+
const props = result[id];
|
|
16442
|
+
if (props) {
|
|
16443
|
+
for (const [key, value] of Object.entries(props)) {
|
|
16444
|
+
instance[key] = value;
|
|
16445
|
+
}
|
|
16446
|
+
}
|
|
16447
|
+
// Sync snapshot so isDirty() doesn't flag getter-only changes
|
|
17134
16448
|
const modelInstance = instance;
|
|
17135
16449
|
if (modelInstance._snapshot) {
|
|
17136
16450
|
for (const propName of evaluatedPropertyNames) {
|
|
@@ -17531,7 +16845,20 @@ class Ad4mModel {
|
|
|
17531
16845
|
* @param name - Class name to assign (e.g. "Channel")
|
|
17532
16846
|
* @returns Generated Ad4mModel subclass, ready for querying
|
|
17533
16847
|
*/
|
|
17534
|
-
|
|
16848
|
+
/**
|
|
16849
|
+
* Synthesise an `Ad4mModel` subclass from a SHACL shape.
|
|
16850
|
+
*
|
|
16851
|
+
* @param shape - The SHACL shape to synthesise from.
|
|
16852
|
+
* @param name - The model name (e.g. "Channel").
|
|
16853
|
+
* @param classResolver - Optional thunk factory. When provided, any collection
|
|
16854
|
+
* property that carries a `sh:class` URI will have its `target` wired up lazily:
|
|
16855
|
+
* `target: () => classResolver(localName)`. Because `target` is only called at
|
|
16856
|
+
* query time (inside `enrichShapeForIncludes` / `jsonToModelInstance`), the
|
|
16857
|
+
* resolver just needs to return the correct class by the time a query runs —
|
|
16858
|
+
* making it safe to pass a closure over a registry object that is still being
|
|
16859
|
+
* populated (e.g. the `result` record inside `getModelClasses`).
|
|
16860
|
+
*/
|
|
16861
|
+
static fromSHACL(shape, name, classResolver) {
|
|
17535
16862
|
const DynamicModelClass = class extends this {
|
|
17536
16863
|
};
|
|
17537
16864
|
DynamicModelClass.className = name;
|
|
@@ -17570,9 +16897,19 @@ class Ad4mModel {
|
|
|
17570
16897
|
continue;
|
|
17571
16898
|
const isCollection = prop.maxCount === undefined || prop.maxCount > 1;
|
|
17572
16899
|
if (isCollection) {
|
|
16900
|
+
// Derive a lazy `target` thunk when a sh:class URI is present and a
|
|
16901
|
+
// classResolver was supplied. The thunk is evaluated at query time so
|
|
16902
|
+
// it is safe even if the target class hasn't been registered yet.
|
|
16903
|
+
let targetThunk;
|
|
16904
|
+
if (prop.class && classResolver) {
|
|
16905
|
+
const sep = Math.max(prop.class.lastIndexOf('#'), prop.class.lastIndexOf('/'));
|
|
16906
|
+
const localName = sep >= 0 ? prop.class.slice(sep + 1) : prop.class;
|
|
16907
|
+
targetThunk = () => classResolver(localName);
|
|
16908
|
+
}
|
|
17573
16909
|
setRelationRegistryEntry(DynamicModelClass, prop.name, {
|
|
17574
16910
|
predicate: prop.path,
|
|
17575
16911
|
kind: 'hasMany',
|
|
16912
|
+
...(targetThunk !== undefined && { target: targetThunk }),
|
|
17576
16913
|
...(prop.local !== undefined && { local: prop.local }),
|
|
17577
16914
|
...(prop.getter !== undefined && { getter: prop.getter }),
|
|
17578
16915
|
});
|
|
@@ -17593,6 +16930,534 @@ class Ad4mModel {
|
|
|
17593
16930
|
}
|
|
17594
16931
|
Ad4mModel.classNamesByClass = new WeakMap();
|
|
17595
16932
|
|
|
16933
|
+
var __classPrivateFieldSet$1 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
16934
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
16935
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
16936
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
16937
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
16938
|
+
};
|
|
16939
|
+
var __classPrivateFieldGet$1 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
16940
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
16941
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
16942
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
16943
|
+
};
|
|
16944
|
+
var _Ad4mClient_baseUrl, _Ad4mClient_token, _Ad4mClient_apiClient, _Ad4mClient_agentClient, _Ad4mClient_expressionClient, _Ad4mClient_languageClient, _Ad4mClient_neighbourhoodClient, _Ad4mClient_perspectiveClient, _Ad4mClient_runtimeClient, _Ad4mClient_aiClient;
|
|
16945
|
+
/**
|
|
16946
|
+
* Client for the Ad4m interface wrapping WebSocket RPC calls
|
|
16947
|
+
* for convenient use in user facing code.
|
|
16948
|
+
*
|
|
16949
|
+
* Aggregates the six sub-clients:
|
|
16950
|
+
* AgentClient, ExpressionClient, LanguageClient,
|
|
16951
|
+
* NeighbourhoodClient, PerspectiveClient and RuntimeClient
|
|
16952
|
+
* for the respective functionality.
|
|
16953
|
+
*/
|
|
16954
|
+
class Ad4mClient {
|
|
16955
|
+
constructor(baseUrl, token, subscribe = true) {
|
|
16956
|
+
_Ad4mClient_baseUrl.set(this, void 0);
|
|
16957
|
+
_Ad4mClient_token.set(this, void 0);
|
|
16958
|
+
_Ad4mClient_apiClient.set(this, void 0);
|
|
16959
|
+
_Ad4mClient_agentClient.set(this, void 0);
|
|
16960
|
+
_Ad4mClient_expressionClient.set(this, void 0);
|
|
16961
|
+
_Ad4mClient_languageClient.set(this, void 0);
|
|
16962
|
+
_Ad4mClient_neighbourhoodClient.set(this, void 0);
|
|
16963
|
+
_Ad4mClient_perspectiveClient.set(this, void 0);
|
|
16964
|
+
_Ad4mClient_runtimeClient.set(this, void 0);
|
|
16965
|
+
_Ad4mClient_aiClient.set(this, void 0);
|
|
16966
|
+
__classPrivateFieldSet$1(this, _Ad4mClient_baseUrl, baseUrl, "f");
|
|
16967
|
+
__classPrivateFieldSet$1(this, _Ad4mClient_token, token, "f");
|
|
16968
|
+
__classPrivateFieldSet$1(this, _Ad4mClient_apiClient, new ApiClient(baseUrl, token), "f");
|
|
16969
|
+
__classPrivateFieldSet$1(this, _Ad4mClient_agentClient, new AgentClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
|
|
16970
|
+
__classPrivateFieldSet$1(this, _Ad4mClient_expressionClient, new ExpressionClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
|
|
16971
|
+
__classPrivateFieldSet$1(this, _Ad4mClient_languageClient, new LanguageClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
|
|
16972
|
+
__classPrivateFieldSet$1(this, _Ad4mClient_neighbourhoodClient, new NeighbourhoodClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
|
|
16973
|
+
__classPrivateFieldSet$1(this, _Ad4mClient_aiClient, new AIClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
|
|
16974
|
+
__classPrivateFieldSet$1(this, _Ad4mClient_perspectiveClient, new PerspectiveClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
|
|
16975
|
+
__classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, "f").setExpressionClient(__classPrivateFieldGet$1(this, _Ad4mClient_expressionClient, "f"));
|
|
16976
|
+
__classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, "f").setNeighbourhoodClient(__classPrivateFieldGet$1(this, _Ad4mClient_neighbourhoodClient, "f"));
|
|
16977
|
+
__classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, "f").setAIClient(__classPrivateFieldGet$1(this, _Ad4mClient_aiClient, "f"));
|
|
16978
|
+
__classPrivateFieldSet$1(this, _Ad4mClient_runtimeClient, new RuntimeClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
|
|
16979
|
+
// Register with AD4M DevTools if the bridge is installed (e.g. browser extension)
|
|
16980
|
+
try {
|
|
16981
|
+
const dt = globalThis.__AD4M_DEVTOOLS__;
|
|
16982
|
+
if (dt) {
|
|
16983
|
+
dt._client = this;
|
|
16984
|
+
dt._Ad4mModel = Ad4mModel;
|
|
16985
|
+
}
|
|
16986
|
+
}
|
|
16987
|
+
catch { }
|
|
16988
|
+
}
|
|
16989
|
+
get agent() {
|
|
16990
|
+
return __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, "f");
|
|
16991
|
+
}
|
|
16992
|
+
get expression() {
|
|
16993
|
+
return __classPrivateFieldGet$1(this, _Ad4mClient_expressionClient, "f");
|
|
16994
|
+
}
|
|
16995
|
+
get languages() {
|
|
16996
|
+
return __classPrivateFieldGet$1(this, _Ad4mClient_languageClient, "f");
|
|
16997
|
+
}
|
|
16998
|
+
get neighbourhood() {
|
|
16999
|
+
return __classPrivateFieldGet$1(this, _Ad4mClient_neighbourhoodClient, "f");
|
|
17000
|
+
}
|
|
17001
|
+
get perspective() {
|
|
17002
|
+
return __classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, "f");
|
|
17003
|
+
}
|
|
17004
|
+
get runtime() {
|
|
17005
|
+
return __classPrivateFieldGet$1(this, _Ad4mClient_runtimeClient, "f");
|
|
17006
|
+
}
|
|
17007
|
+
get ai() {
|
|
17008
|
+
return __classPrivateFieldGet$1(this, _Ad4mClient_aiClient, "f");
|
|
17009
|
+
}
|
|
17010
|
+
/** Start event subscriptions (agent-updated, agent-status-changed, apps-changed).
|
|
17011
|
+
* Safe to call if subscriptions were deferred at construction (subscribe=false). */
|
|
17012
|
+
startSubscriptions() {
|
|
17013
|
+
__classPrivateFieldGet$1(this, _Ad4mClient_agentClient, "f").subscribeAgentUpdated();
|
|
17014
|
+
__classPrivateFieldGet$1(this, _Ad4mClient_agentClient, "f").subscribeAgentStatusChanged();
|
|
17015
|
+
__classPrivateFieldGet$1(this, _Ad4mClient_agentClient, "f").subscribeAppsChanged();
|
|
17016
|
+
}
|
|
17017
|
+
/** Close all event connections */
|
|
17018
|
+
close() {
|
|
17019
|
+
__classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f").closeAll();
|
|
17020
|
+
}
|
|
17021
|
+
}
|
|
17022
|
+
_Ad4mClient_baseUrl = new WeakMap(), _Ad4mClient_token = new WeakMap(), _Ad4mClient_apiClient = new WeakMap(), _Ad4mClient_agentClient = new WeakMap(), _Ad4mClient_expressionClient = new WeakMap(), _Ad4mClient_languageClient = new WeakMap(), _Ad4mClient_neighbourhoodClient = new WeakMap(), _Ad4mClient_perspectiveClient = new WeakMap(), _Ad4mClient_runtimeClient = new WeakMap(), _Ad4mClient_aiClient = new WeakMap();
|
|
17023
|
+
|
|
17024
|
+
exports.ExceptionType = void 0;
|
|
17025
|
+
(function (ExceptionType) {
|
|
17026
|
+
ExceptionType["LanguageIsNotLoaded"] = "LANGUAGE_IS_NOT_LOADED";
|
|
17027
|
+
ExceptionType["ExpressionIsNotVerified"] = "EXPRESSION_IS_NOT_VERIFIED";
|
|
17028
|
+
ExceptionType["AgentIsUntrusted"] = "AGENT_IS_UNTRUSTED";
|
|
17029
|
+
ExceptionType["CapabilityRequested"] = "CAPABILITY_REQUESTED";
|
|
17030
|
+
ExceptionType["InstallNotificationRequest"] = "INSTALL_NOTIFICATION_REQUEST";
|
|
17031
|
+
})(exports.ExceptionType || (exports.ExceptionType = {}));
|
|
17032
|
+
|
|
17033
|
+
// Unique Language ID with option type
|
|
17034
|
+
class LanguageRef {
|
|
17035
|
+
constructor(address, name) {
|
|
17036
|
+
this.address = address;
|
|
17037
|
+
this.name = name;
|
|
17038
|
+
}
|
|
17039
|
+
}
|
|
17040
|
+
|
|
17041
|
+
// Expression address + unique Language ID = global expression URL
|
|
17042
|
+
class ExpressionRef {
|
|
17043
|
+
constructor(lang, expr) {
|
|
17044
|
+
this.language = lang;
|
|
17045
|
+
this.expression = expr;
|
|
17046
|
+
}
|
|
17047
|
+
}
|
|
17048
|
+
// Creates unique expression URI like this:
|
|
17049
|
+
// expr:Qm3490gfwe489hf34:Qm90ghjoaw4iehioefwe4ort
|
|
17050
|
+
function exprRef2String(ref) {
|
|
17051
|
+
if (ref.language.address === 'did')
|
|
17052
|
+
return ref.expression.toString();
|
|
17053
|
+
else
|
|
17054
|
+
return `${ref.language.address}://${ref.expression}`;
|
|
17055
|
+
}
|
|
17056
|
+
function parseExprUrl(url) {
|
|
17057
|
+
if (url.startsWith("literal:")) {
|
|
17058
|
+
const languageRef = new LanguageRef();
|
|
17059
|
+
languageRef.address = 'literal';
|
|
17060
|
+
languageRef.name = 'literal';
|
|
17061
|
+
const content = url.substring(8);
|
|
17062
|
+
return new ExpressionRef(languageRef, content);
|
|
17063
|
+
}
|
|
17064
|
+
const URIregexp = /^([^:^\s]+):\/\/([\s\S]+)$/;
|
|
17065
|
+
const URImatches = URIregexp.exec(url);
|
|
17066
|
+
if (URImatches && URImatches.length == 3) {
|
|
17067
|
+
const language = URImatches[1];
|
|
17068
|
+
const expression = URImatches[2];
|
|
17069
|
+
const languageRef = new LanguageRef();
|
|
17070
|
+
languageRef.address = language;
|
|
17071
|
+
const ref = new ExpressionRef(languageRef, expression);
|
|
17072
|
+
return ref;
|
|
17073
|
+
}
|
|
17074
|
+
const DIDregexp = /^did:([^\s]+)$/;
|
|
17075
|
+
const DIDmatches = DIDregexp.exec(url);
|
|
17076
|
+
if (DIDmatches && DIDmatches.length == 2) {
|
|
17077
|
+
const languageRef = new LanguageRef();
|
|
17078
|
+
languageRef.address = 'did';
|
|
17079
|
+
const ref = new ExpressionRef(languageRef, url);
|
|
17080
|
+
return ref;
|
|
17081
|
+
}
|
|
17082
|
+
throw new Error("Couldn't parse string as expression URL or DID: " + url);
|
|
17083
|
+
}
|
|
17084
|
+
|
|
17085
|
+
class Icon {
|
|
17086
|
+
constructor(code) {
|
|
17087
|
+
this.code = code;
|
|
17088
|
+
}
|
|
17089
|
+
}
|
|
17090
|
+
|
|
17091
|
+
/**
|
|
17092
|
+
* # AD4M Language — client-side types
|
|
17093
|
+
*
|
|
17094
|
+
* This file only contains the client-visible types that the AD4M REST
|
|
17095
|
+
* API exposes on top of a running Language — interaction metadata, online
|
|
17096
|
+
* agent records, and the telepresence-signal callback shape.
|
|
17097
|
+
*
|
|
17098
|
+
* **If you're authoring an AD4M Language**, you don't consume types from
|
|
17099
|
+
* here — use [`@coasys/ad4m-ldk`](https://www.npmjs.com/package/@coasys/ad4m-ldk)
|
|
17100
|
+
* (or the [Rust ALDK](https://crates.io/crates/ad4m-ldk)), which provide
|
|
17101
|
+
* the capability traits, typed runtime-import wrappers, and authoring
|
|
17102
|
+
* macros/helpers.
|
|
17103
|
+
*
|
|
17104
|
+
* The normative interface definition lives in
|
|
17105
|
+
* [`docs-src/ad4m-lang.wit`](https://github.com/coasys/ad4m/blob/dev/docs-src/ad4m-lang.wit).
|
|
17106
|
+
* The prose spec is
|
|
17107
|
+
* [`docs-src/language-interface-spec.md`](https://github.com/coasys/ad4m/blob/dev/docs-src/language-interface-spec.md).
|
|
17108
|
+
*/
|
|
17109
|
+
// ----- Interaction metadata --------------------------------------------------
|
|
17110
|
+
//
|
|
17111
|
+
// Languages optionally publish a list of user-invocable actions per
|
|
17112
|
+
// Expression ("interactions"). The runtime surfaces these to UIs via
|
|
17113
|
+
// the API as first-class objects.
|
|
17114
|
+
class InteractionParameter {
|
|
17115
|
+
}
|
|
17116
|
+
class InteractionMeta {
|
|
17117
|
+
}
|
|
17118
|
+
class InteractionCall {
|
|
17119
|
+
get parameters() {
|
|
17120
|
+
return JSON.parse(this.parametersStringified);
|
|
17121
|
+
}
|
|
17122
|
+
constructor(name, parameters) {
|
|
17123
|
+
this.name = name;
|
|
17124
|
+
this.parametersStringified = JSON.stringify(parameters);
|
|
17125
|
+
}
|
|
17126
|
+
}
|
|
17127
|
+
// ----- Telepresence ----------------------------------------------------------
|
|
17128
|
+
class OnlineAgent {
|
|
17129
|
+
}
|
|
17130
|
+
|
|
17131
|
+
class LanguageHandle {
|
|
17132
|
+
}
|
|
17133
|
+
|
|
17134
|
+
class LanguageMeta {
|
|
17135
|
+
}
|
|
17136
|
+
class LanguageMetaInput {
|
|
17137
|
+
constructor(name, description) {
|
|
17138
|
+
this.name = name;
|
|
17139
|
+
this.description = description;
|
|
17140
|
+
if (!this.description)
|
|
17141
|
+
this.description = "";
|
|
17142
|
+
}
|
|
17143
|
+
}
|
|
17144
|
+
class LanguageMetaInternal {
|
|
17145
|
+
}
|
|
17146
|
+
class LanguageExpression extends ExpressionGeneric() {
|
|
17147
|
+
}
|
|
17148
|
+
class LanguageLanguageInput {
|
|
17149
|
+
}
|
|
17150
|
+
|
|
17151
|
+
exports.PerspectiveState = void 0;
|
|
17152
|
+
(function (PerspectiveState) {
|
|
17153
|
+
PerspectiveState["Private"] = "PRIVATE";
|
|
17154
|
+
PerspectiveState["NeighboudhoodCreationInitiated"] = "NEIGHBOURHOOD_CREATION_INITIATED";
|
|
17155
|
+
PerspectiveState["NeighbourhoodJoinInitiated"] = "NEIGHBOURHOOD_JOIN_INITIATED";
|
|
17156
|
+
PerspectiveState["LinkLanguageFailedToInstall"] = "LINK_LANGUAGE_FAILED_TO_INSTALL";
|
|
17157
|
+
PerspectiveState["LinkLanguageInstalledButNotSynced"] = "LINK_LANGUAGE_INSTALLED_BUT_NOT_SYNCED";
|
|
17158
|
+
PerspectiveState["Synced"] = "SYNCED";
|
|
17159
|
+
})(exports.PerspectiveState || (exports.PerspectiveState = {}));
|
|
17160
|
+
// This type is used in the REST interface to reference a mutable
|
|
17161
|
+
// prespective that is implemented locally by the Ad4m runtime.
|
|
17162
|
+
// The UUID is used in mutations to identify the perspective that gets mutated.
|
|
17163
|
+
class PerspectiveHandle {
|
|
17164
|
+
constructor(uuid, name, state) {
|
|
17165
|
+
this.uuid = uuid;
|
|
17166
|
+
this.name = name;
|
|
17167
|
+
if (state) {
|
|
17168
|
+
this.state = state;
|
|
17169
|
+
}
|
|
17170
|
+
else {
|
|
17171
|
+
this.state = exports.PerspectiveState.Private;
|
|
17172
|
+
}
|
|
17173
|
+
}
|
|
17174
|
+
}
|
|
17175
|
+
|
|
17176
|
+
/**
|
|
17177
|
+
* WakerSubscriptionManager — manages live query subscriptions for the waker.
|
|
17178
|
+
*
|
|
17179
|
+
* Lives in core so it can be imported by both the plugin and integration tests
|
|
17180
|
+
* without ESM/CJS import issues.
|
|
17181
|
+
*
|
|
17182
|
+
* NOTE: keep in sync with plugins/ad4m/wakerSubscriptionManager.ts
|
|
17183
|
+
*/
|
|
17184
|
+
class WakerSubscriptionManager {
|
|
17185
|
+
constructor(options) {
|
|
17186
|
+
this.proxies = new Map();
|
|
17187
|
+
this.activeSubscriptions = new Map();
|
|
17188
|
+
this.debounceTimers = new Map();
|
|
17189
|
+
/** Per-subscription set of already-processed message addresses (for mention subs)
|
|
17190
|
+
* or serialized result hash (for channel-messages subs). */
|
|
17191
|
+
this.seenMessages = new Map();
|
|
17192
|
+
this.perspectiveClient = options.perspectiveClient;
|
|
17193
|
+
this.logger = options.logger;
|
|
17194
|
+
this.debounceMs = options.debounceMs ?? 2000;
|
|
17195
|
+
this.onWake = options.onWake;
|
|
17196
|
+
this.onPersist = options.onPersist;
|
|
17197
|
+
this.QuerySubscriptionProxyCtor = options.QuerySubscriptionProxy ?? null;
|
|
17198
|
+
this.previousSeenMessages = options.previousSeenMessages ?? {};
|
|
17199
|
+
}
|
|
17200
|
+
/**
|
|
17201
|
+
* Create a live SPARQL subscription.
|
|
17202
|
+
* If a subscription with the same id already exists, it is disposed first.
|
|
17203
|
+
*/
|
|
17204
|
+
async subscribe(sub) {
|
|
17205
|
+
// Dispose existing subscription with same id if any
|
|
17206
|
+
this.dispose(sub.id, false);
|
|
17207
|
+
if (!this.QuerySubscriptionProxyCtor) {
|
|
17208
|
+
throw new Error("WakerSubscriptionManager: QuerySubscriptionProxy must be provided via constructor options");
|
|
17209
|
+
}
|
|
17210
|
+
const QuerySubscriptionProxy = this.QuerySubscriptionProxyCtor;
|
|
17211
|
+
this.logger.info(`[waker] ${sub.id}: creating subscription (perspective=${sub.perspective}, type=${sub.type})`);
|
|
17212
|
+
this.logger.info(`[waker] ${sub.id}: SPARQL query:\n${sub.query}`);
|
|
17213
|
+
const proxy = new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient);
|
|
17214
|
+
proxy.isSPARQL = true;
|
|
17215
|
+
// Suppress unhandled rejection from proxy.initialized — QuerySubscriptionProxy
|
|
17216
|
+
// rejects this promise internally when subscribe() fails, and if nobody catches
|
|
17217
|
+
// it before the next microtask it crashes the process.
|
|
17218
|
+
if (proxy.initialized && typeof proxy.initialized.catch === "function") {
|
|
17219
|
+
proxy.initialized.catch(() => { });
|
|
17220
|
+
}
|
|
17221
|
+
try {
|
|
17222
|
+
await proxy.subscribe();
|
|
17223
|
+
await proxy.initialized;
|
|
17224
|
+
}
|
|
17225
|
+
catch (err) {
|
|
17226
|
+
const msg = err?.message ?? String(err);
|
|
17227
|
+
this.logger.warn(`[waker] ${sub.id}: subscription failed — ${msg}`);
|
|
17228
|
+
try {
|
|
17229
|
+
proxy.dispose();
|
|
17230
|
+
}
|
|
17231
|
+
catch { }
|
|
17232
|
+
// Remove from active state so it doesn't get persisted/retried
|
|
17233
|
+
this.activeSubscriptions.delete(sub.id);
|
|
17234
|
+
this.seenMessages.delete(sub.id);
|
|
17235
|
+
this.persist();
|
|
17236
|
+
return; // Don't throw — caller should not crash
|
|
17237
|
+
}
|
|
17238
|
+
this.logger.info(`[waker] ${sub.id}: subscription initialized successfully`);
|
|
17239
|
+
// Seed from persisted seen messages so we don't re-wake after restart
|
|
17240
|
+
const seen = new Set(this.previousSeenMessages[sub.id] ?? []);
|
|
17241
|
+
this.seenMessages.set(sub.id, seen);
|
|
17242
|
+
if (seen.size > 0) {
|
|
17243
|
+
this.logger.info(`[waker] ${sub.id}: seeded ${seen.size} seen message(s) from persisted state`);
|
|
17244
|
+
}
|
|
17245
|
+
proxy.onResult(async (result) => {
|
|
17246
|
+
this.logger.info(`[waker] ${sub.id}: onResult fired — type=${typeof result}, isArray=${Array.isArray(result)}, value=${String(JSON.stringify(result)).substring(0, 500)}`);
|
|
17247
|
+
// Query engine can deliver non-array values (e.g. false) on disconnect/reconnect — ignore them
|
|
17248
|
+
if (!Array.isArray(result)) {
|
|
17249
|
+
this.logger.warn(`[waker] ${sub.id}: ignoring non-array result: ${JSON.stringify(result)}`);
|
|
17250
|
+
return;
|
|
17251
|
+
}
|
|
17252
|
+
if (sub.type === "mention") {
|
|
17253
|
+
// For mention subscriptions: track seen message addresses.
|
|
17254
|
+
// Only wake for messages we haven't seen before.
|
|
17255
|
+
const currentSeen = this.seenMessages.get(sub.id) ?? new Set();
|
|
17256
|
+
const newMessages = [];
|
|
17257
|
+
for (const item of result) {
|
|
17258
|
+
if (item && item.source && !currentSeen.has(item.source)) {
|
|
17259
|
+
newMessages.push(item.source);
|
|
17260
|
+
}
|
|
17261
|
+
}
|
|
17262
|
+
if (newMessages.length === 0) {
|
|
17263
|
+
this.logger.info(`[waker] ${sub.id}: all ${result.length} items already seen, skipping`);
|
|
17264
|
+
return;
|
|
17265
|
+
}
|
|
17266
|
+
this.logger.info(`[waker] ${sub.id}: ${newMessages.length} new message(s) out of ${result.length} total`);
|
|
17267
|
+
// Resolve parents per new message
|
|
17268
|
+
const mentions = [];
|
|
17269
|
+
for (const msgAddr of newMessages) {
|
|
17270
|
+
const parents = [];
|
|
17271
|
+
try {
|
|
17272
|
+
const parentQuery = `SELECT ?source WHERE { ?source <ad4m://has_child> <${msgAddr}> . }`;
|
|
17273
|
+
this.logger.info(`[waker] ${sub.id}: resolving parents for ${msgAddr}`);
|
|
17274
|
+
const parentResult = await this.perspectiveClient.querySparql(sub.perspective, parentQuery);
|
|
17275
|
+
if (Array.isArray(parentResult)) {
|
|
17276
|
+
for (const link of parentResult) {
|
|
17277
|
+
if (link && link.source) {
|
|
17278
|
+
parents.push(link.source);
|
|
17279
|
+
}
|
|
17280
|
+
}
|
|
17281
|
+
}
|
|
17282
|
+
}
|
|
17283
|
+
catch (err) {
|
|
17284
|
+
this.logger.warn(`[waker] ${sub.id}: parent resolution failed for ${msgAddr} — ${err?.message ?? err}`);
|
|
17285
|
+
}
|
|
17286
|
+
this.logger.info(`[waker] ${sub.id}: message ${msgAddr} has ${parents.length} parent(s): ${parents.join(", ")}`);
|
|
17287
|
+
mentions.push({ address: msgAddr, parents });
|
|
17288
|
+
}
|
|
17289
|
+
// Mark all new messages as seen
|
|
17290
|
+
for (const addr of newMessages) {
|
|
17291
|
+
currentSeen.add(addr);
|
|
17292
|
+
}
|
|
17293
|
+
this.seenMessages.set(sub.id, currentSeen);
|
|
17294
|
+
// Debounce the wake callback
|
|
17295
|
+
const existing = this.debounceTimers.get(sub.id);
|
|
17296
|
+
if (existing)
|
|
17297
|
+
clearTimeout(existing);
|
|
17298
|
+
this.debounceTimers.set(sub.id, setTimeout(() => {
|
|
17299
|
+
this.onWake(sub, result, mentions);
|
|
17300
|
+
this.debounceTimers.delete(sub.id);
|
|
17301
|
+
this.persist();
|
|
17302
|
+
}, this.debounceMs));
|
|
17303
|
+
}
|
|
17304
|
+
else {
|
|
17305
|
+
// For channel-messages: always notify the agent on every subscription push.
|
|
17306
|
+
// No deduplication — the agent reads recent messages itself.
|
|
17307
|
+
this.logger.info(`[waker] ${sub.id}: channel update (${result.length} items)`);
|
|
17308
|
+
const existing = this.debounceTimers.get(sub.id);
|
|
17309
|
+
if (existing)
|
|
17310
|
+
clearTimeout(existing);
|
|
17311
|
+
this.debounceTimers.set(sub.id, setTimeout(() => {
|
|
17312
|
+
this.onWake(sub, result);
|
|
17313
|
+
this.debounceTimers.delete(sub.id);
|
|
17314
|
+
}, this.debounceMs));
|
|
17315
|
+
}
|
|
17316
|
+
});
|
|
17317
|
+
this.proxies.set(sub.id, proxy);
|
|
17318
|
+
this.activeSubscriptions.set(sub.id, sub);
|
|
17319
|
+
this.persist();
|
|
17320
|
+
this.logger.info(`[waker] Subscription ${sub.id} active (type=${sub.type}, perspective=${sub.perspective})`);
|
|
17321
|
+
}
|
|
17322
|
+
/**
|
|
17323
|
+
* Dispose a single subscription.
|
|
17324
|
+
* @param persist — if false, skip calling onPersist (used during batch cleanup).
|
|
17325
|
+
*/
|
|
17326
|
+
dispose(id, persist = true) {
|
|
17327
|
+
const proxy = this.proxies.get(id);
|
|
17328
|
+
if (proxy) {
|
|
17329
|
+
try {
|
|
17330
|
+
proxy.dispose();
|
|
17331
|
+
}
|
|
17332
|
+
catch {
|
|
17333
|
+
/* ignore */
|
|
17334
|
+
}
|
|
17335
|
+
this.proxies.delete(id);
|
|
17336
|
+
}
|
|
17337
|
+
const timer = this.debounceTimers.get(id);
|
|
17338
|
+
if (timer) {
|
|
17339
|
+
clearTimeout(timer);
|
|
17340
|
+
this.debounceTimers.delete(id);
|
|
17341
|
+
}
|
|
17342
|
+
this.activeSubscriptions.delete(id);
|
|
17343
|
+
this.seenMessages.delete(id);
|
|
17344
|
+
if (persist)
|
|
17345
|
+
this.persist();
|
|
17346
|
+
}
|
|
17347
|
+
/** Dispose all active subscriptions. */
|
|
17348
|
+
disposeAll() {
|
|
17349
|
+
for (const [id] of this.proxies) {
|
|
17350
|
+
this.dispose(id, false);
|
|
17351
|
+
}
|
|
17352
|
+
}
|
|
17353
|
+
/** Get all active subscriptions. */
|
|
17354
|
+
getActive() {
|
|
17355
|
+
return Array.from(this.activeSubscriptions.values());
|
|
17356
|
+
}
|
|
17357
|
+
/** Check if a subscription exists. */
|
|
17358
|
+
has(id) {
|
|
17359
|
+
return this.activeSubscriptions.has(id);
|
|
17360
|
+
}
|
|
17361
|
+
persist() {
|
|
17362
|
+
if (this.onPersist) {
|
|
17363
|
+
const seen = {};
|
|
17364
|
+
for (const [id, set] of this.seenMessages) {
|
|
17365
|
+
seen[id] = Array.from(set);
|
|
17366
|
+
}
|
|
17367
|
+
this.onPersist(this.getActive(), seen);
|
|
17368
|
+
}
|
|
17369
|
+
}
|
|
17370
|
+
}
|
|
17371
|
+
|
|
17372
|
+
class PerspectiveDiff {
|
|
17373
|
+
}
|
|
17374
|
+
class PerspectiveDiffExpression extends ExpressionGeneric() {
|
|
17375
|
+
}
|
|
17376
|
+
|
|
17377
|
+
var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
17378
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
17379
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
17380
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
17381
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
17382
|
+
};
|
|
17383
|
+
var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
17384
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
17385
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
17386
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
17387
|
+
};
|
|
17388
|
+
var _SmartLiteral_perspective, _SmartLiteral_base;
|
|
17389
|
+
const SMART_LITERAL_CONTENT_PREDICATE = "smart_literal://content";
|
|
17390
|
+
function makeRandomStringID(length) {
|
|
17391
|
+
let result = '';
|
|
17392
|
+
let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
|
17393
|
+
let charactersLength = characters.length;
|
|
17394
|
+
for (let i = 0; i < length; i++) {
|
|
17395
|
+
result += characters.charAt(Math.floor(Math.random() * charactersLength));
|
|
17396
|
+
}
|
|
17397
|
+
return result;
|
|
17398
|
+
}
|
|
17399
|
+
class SmartLiteral {
|
|
17400
|
+
constructor(perspective, base) {
|
|
17401
|
+
_SmartLiteral_perspective.set(this, void 0);
|
|
17402
|
+
_SmartLiteral_base.set(this, void 0);
|
|
17403
|
+
__classPrivateFieldSet(this, _SmartLiteral_perspective, perspective, "f");
|
|
17404
|
+
__classPrivateFieldSet(this, _SmartLiteral_base, base, "f");
|
|
17405
|
+
}
|
|
17406
|
+
get base() {
|
|
17407
|
+
return __classPrivateFieldGet(this, _SmartLiteral_base, "f");
|
|
17408
|
+
}
|
|
17409
|
+
static async create(perspective, literal) {
|
|
17410
|
+
const base = Literal.from(makeRandomStringID(10)).toUrl();
|
|
17411
|
+
const smartLiteral = new SmartLiteral(perspective, base);
|
|
17412
|
+
await smartLiteral.set(literal);
|
|
17413
|
+
return smartLiteral;
|
|
17414
|
+
}
|
|
17415
|
+
static async isSmartLiteralBase(perspective, base) {
|
|
17416
|
+
let links = await perspective.get(new LinkQuery({
|
|
17417
|
+
source: base,
|
|
17418
|
+
predicate: SMART_LITERAL_CONTENT_PREDICATE
|
|
17419
|
+
}));
|
|
17420
|
+
return links.length > 0;
|
|
17421
|
+
}
|
|
17422
|
+
static async getAllSmartLiterals(perspective) {
|
|
17423
|
+
let links = await perspective.get(new LinkQuery({
|
|
17424
|
+
predicate: SMART_LITERAL_CONTENT_PREDICATE
|
|
17425
|
+
}));
|
|
17426
|
+
return links.map(link => new SmartLiteral(perspective, link.data.source));
|
|
17427
|
+
}
|
|
17428
|
+
async get() {
|
|
17429
|
+
let link = await __classPrivateFieldGet(this, _SmartLiteral_perspective, "f").getSingleTarget(new LinkQuery({
|
|
17430
|
+
source: __classPrivateFieldGet(this, _SmartLiteral_base, "f"),
|
|
17431
|
+
predicate: SMART_LITERAL_CONTENT_PREDICATE
|
|
17432
|
+
}));
|
|
17433
|
+
if (!link) {
|
|
17434
|
+
throw `No content for smart literal ${__classPrivateFieldGet(this, _SmartLiteral_base, "f")}`;
|
|
17435
|
+
}
|
|
17436
|
+
return Literal.fromUrl(link).get();
|
|
17437
|
+
}
|
|
17438
|
+
async set(content) {
|
|
17439
|
+
let literal = Literal.from(content);
|
|
17440
|
+
await __classPrivateFieldGet(this, _SmartLiteral_perspective, "f").setSingleTarget(new Link({
|
|
17441
|
+
source: __classPrivateFieldGet(this, _SmartLiteral_base, "f"),
|
|
17442
|
+
predicate: SMART_LITERAL_CONTENT_PREDICATE,
|
|
17443
|
+
target: literal.toUrl()
|
|
17444
|
+
}));
|
|
17445
|
+
}
|
|
17446
|
+
}
|
|
17447
|
+
_SmartLiteral_perspective = new WeakMap(), _SmartLiteral_base = new WeakMap();
|
|
17448
|
+
|
|
17449
|
+
/**
|
|
17450
|
+
* Shared type definitions for the Ad4mModel system.
|
|
17451
|
+
*
|
|
17452
|
+
* Extracted into a standalone module so that utility files
|
|
17453
|
+
* (`query-utils.ts`, `decorators.ts`, etc.) can import types without
|
|
17454
|
+
* creating circular runtime dependencies on `Ad4mModel.ts`.
|
|
17455
|
+
*/
|
|
17456
|
+
/** Type guard for IncludeProjection objects. */
|
|
17457
|
+
function isIncludeProjection(val) {
|
|
17458
|
+
return typeof val === 'object' && val !== null && 'from' in val;
|
|
17459
|
+
}
|
|
17460
|
+
|
|
17596
17461
|
class Neighbourhood {
|
|
17597
17462
|
constructor(linkLanguage, meta) {
|
|
17598
17463
|
this.linkLanguage = linkLanguage;
|
|
@@ -17728,7 +17593,6 @@ exports.VerificationRequestResult = VerificationRequestResult;
|
|
|
17728
17593
|
exports.VoiceActivityParamsInput = VoiceActivityParamsInput;
|
|
17729
17594
|
exports.WakerSubscriptionManager = WakerSubscriptionManager;
|
|
17730
17595
|
exports.buildConformanceFilter = buildConformanceFilter;
|
|
17731
|
-
exports.buildConformanceGetter = buildConformanceGetter;
|
|
17732
17596
|
exports.buildModelFromJSONSchema = buildModelFromJSONSchema;
|
|
17733
17597
|
exports.buildPaginationSubquery = buildPaginationSubquery;
|
|
17734
17598
|
exports.buildSDNA = buildSDNA;
|
|
@@ -17742,7 +17606,6 @@ exports.compileWhereClause = compileWhereClause;
|
|
|
17742
17606
|
exports.determineNamespace = determineNamespace;
|
|
17743
17607
|
exports.determinePredicate = determinePredicate;
|
|
17744
17608
|
exports.escapeQueryString = escapeQueryString;
|
|
17745
|
-
exports.evaluateCustomGettersForInstance = evaluateCustomGettersForInstance;
|
|
17746
17609
|
exports.exprRef2String = exprRef2String;
|
|
17747
17610
|
exports.formatList = formatList;
|
|
17748
17611
|
exports.formatQueryValue = formatQueryValue;
|
|
@@ -17763,7 +17626,6 @@ exports.isNumericType = isNumericType;
|
|
|
17763
17626
|
exports.isObjectType = isObjectType;
|
|
17764
17627
|
exports.isSchemaType = isSchemaType;
|
|
17765
17628
|
exports.linkEqual = linkEqual;
|
|
17766
|
-
exports.matchesCondition = matchesCondition;
|
|
17767
17629
|
exports.normalizeNamespaceString = normalizeNamespaceString;
|
|
17768
17630
|
exports.normalizeSchemaType = normalizeSchemaType;
|
|
17769
17631
|
exports.normalizeValue = normalizeValue;
|