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