@coasys/ad4m 0.13.0-test-1 → 0.13.0-test-3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/lib/index.cjs +2377 -849
  2. package/lib/index.js +2354 -846
  3. package/lib/src/Literal.js +6 -5
  4. package/lib/src/agent/AgentClient.d.ts +5 -1
  5. package/lib/src/agent/AgentClient.js +48 -2
  6. package/lib/src/expression/ExpressionRef.js +2 -2
  7. package/lib/src/index.d.ts +0 -1
  8. package/lib/src/index.js +0 -1
  9. package/lib/src/language/Language.d.ts +26 -176
  10. package/lib/src/language/Language.js +28 -2
  11. package/lib/src/model/Ad4mModel.d.ts +52 -28
  12. package/lib/src/model/Ad4mModel.js +255 -118
  13. package/lib/src/model/Ad4mModel.test.js +1727 -537
  14. package/lib/src/model/ModelQueryBuilder.d.ts +67 -34
  15. package/lib/src/model/ModelQueryBuilder.js +208 -79
  16. package/lib/src/model/Subject.js +6 -6
  17. package/lib/src/model/decorators.d.ts +14 -8
  18. package/lib/src/model/decorators.js +41 -14
  19. package/lib/src/model/hydration-batch.d.ts +34 -0
  20. package/lib/src/model/hydration-batch.js +147 -0
  21. package/lib/src/model/hydration-batching.test.d.ts +7 -0
  22. package/lib/src/model/hydration-batching.test.js +456 -0
  23. package/lib/src/model/hydration.d.ts +4 -3
  24. package/lib/src/model/hydration.js +365 -86
  25. package/lib/src/model/index.d.ts +4 -1
  26. package/lib/src/model/index.js +4 -1
  27. package/lib/src/model/json-schema.js +2 -2
  28. package/lib/src/model/query-cache.d.ts +30 -0
  29. package/lib/src/model/query-cache.js +66 -0
  30. package/lib/src/model/query-cache.test.d.ts +1 -0
  31. package/lib/src/model/query-cache.test.js +43 -0
  32. package/lib/src/model/query-common.d.ts +1 -1
  33. package/lib/src/model/query-common.js +1 -1
  34. package/lib/src/model/query-sparql-batch.d.ts +17 -0
  35. package/lib/src/model/query-sparql-batch.js +260 -0
  36. package/lib/src/model/query-sparql.d.ts +124 -0
  37. package/lib/src/model/query-sparql.js +767 -0
  38. package/lib/src/model/query-sparql.test.d.ts +1 -0
  39. package/lib/src/model/query-sparql.test.js +495 -0
  40. package/lib/src/model/{surreal-utils.d.ts → query-utils.d.ts} +12 -9
  41. package/lib/src/model/{surreal-utils.js → query-utils.js} +43 -27
  42. package/lib/src/model/relation-filtering.test.js +15 -15
  43. package/lib/src/model/sdna.js +1 -1
  44. package/lib/src/model/shacl-gen.js +42 -18
  45. package/lib/src/model/subscription-delta.test.d.ts +24 -0
  46. package/lib/src/model/subscription-delta.test.js +180 -0
  47. package/lib/src/model/subscription-pool.d.ts +39 -0
  48. package/lib/src/model/subscription-pool.js +165 -0
  49. package/lib/src/model/types.d.ts +52 -4
  50. package/lib/src/model/types.js +1 -1
  51. package/lib/src/perspectives/PerspectiveClient.d.ts +3 -17
  52. package/lib/src/perspectives/PerspectiveClient.js +42 -66
  53. package/lib/src/perspectives/PerspectiveClient.test.d.ts +1 -0
  54. package/lib/src/perspectives/PerspectiveClient.test.js +169 -0
  55. package/lib/src/perspectives/PerspectiveProxy.d.ts +54 -30
  56. package/lib/src/perspectives/PerspectiveProxy.js +239 -177
  57. package/lib/src/perspectives/PerspectiveResolver.d.ts +0 -1
  58. package/lib/src/perspectives/PerspectiveResolver.js +0 -11
  59. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +3 -3
  60. package/lib/src/perspectives/WakerSubscriptionManager.js +7 -8
  61. package/lib/src/runtime/RuntimeResolver.d.ts +11 -0
  62. package/lib/src/runtime/RuntimeResolver.js +56 -0
  63. package/lib/src/schema.gql +11 -1
  64. package/lib/src/shacl/SHACLFlow.d.ts +1 -1
  65. package/lib/src/shacl/SHACLFlow.js +9 -9
  66. package/lib/src/shacl/SHACLShape.d.ts +1 -1
  67. package/lib/src/shacl/SHACLShape.js +38 -38
  68. package/lib/src/typeDefs.js +11 -1
  69. package/lib/src/utils.d.ts +6 -6
  70. package/lib/src/utils.js +6 -6
  71. package/package.json +1 -1
  72. package/src/Ad4mClient.test.ts +56 -1
  73. package/src/Literal.test.ts +10 -5
  74. package/src/Literal.ts +6 -5
  75. package/src/agent/AgentClient.ts +53 -1
  76. package/src/expression/ExpressionRef.ts +2 -2
  77. package/src/index.ts +0 -1
  78. package/src/language/Language.ts +55 -231
  79. package/src/model/Ad4mModel.test.ts +1709 -572
  80. package/src/model/Ad4mModel.ts +274 -120
  81. package/src/model/ModelQueryBuilder.ts +234 -87
  82. package/src/model/Subject.ts +6 -6
  83. package/src/model/decorators.ts +51 -22
  84. package/src/model/hydration-batch.ts +205 -0
  85. package/src/model/hydration-batching.test.ts +563 -0
  86. package/src/model/hydration.ts +349 -84
  87. package/src/model/index.ts +4 -1
  88. package/src/model/json-schema.ts +2 -2
  89. package/src/model/query-cache.test.ts +54 -0
  90. package/src/model/query-cache.ts +79 -0
  91. package/src/model/query-common.ts +1 -1
  92. package/src/model/query-sparql-batch.ts +301 -0
  93. package/src/model/query-sparql.test.ts +568 -0
  94. package/src/model/query-sparql.ts +820 -0
  95. package/src/model/{surreal-utils.ts → query-utils.ts} +44 -27
  96. package/src/model/relation-filtering.test.ts +15 -15
  97. package/src/model/sdna.ts +1 -1
  98. package/src/model/shacl-gen.ts +42 -17
  99. package/src/model/subscription-delta.test.ts +207 -0
  100. package/src/model/subscription-pool.ts +211 -0
  101. package/src/model/types.ts +53 -4
  102. package/src/perspectives/PerspectiveClient.test.ts +204 -0
  103. package/src/perspectives/PerspectiveClient.ts +41 -68
  104. package/src/perspectives/PerspectiveProxy.ts +244 -181
  105. package/src/perspectives/PerspectiveResolver.ts +0 -8
  106. package/src/perspectives/WakerSubscriptionManager.ts +8 -9
  107. package/src/runtime/RuntimeResolver.ts +43 -0
  108. package/src/shacl/SHACLFlow.ts +9 -9
  109. package/src/shacl/SHACLShape.ts +39 -39
  110. package/src/utils.ts +6 -6
  111. package/lib/src/model/query-surreal.d.ts +0 -44
  112. package/lib/src/model/query-surreal.js +0 -249
  113. package/src/language/LanguageContext.ts +0 -37
  114. package/src/model/query-surreal.ts +0 -280
  115. package/tsconfig-browser.json +0 -82
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Subscription Pool — deduplicates identical SPARQL subscriptions.
3
+ *
4
+ * When multiple UI components subscribe to the same SPARQL query on the same
5
+ * perspective, the pool shares a single `subscribeQuery()` call and distributes
6
+ * results to all registered callbacks. Hydration happens once per result set,
7
+ * then is shared across all subscribers.
8
+ *
9
+ * Key: `perspectiveUUID + sparqlQuery`
10
+ */
11
+ const pool = new Map();
12
+ function makeKey(perspectiveUUID, sparqlQuery) {
13
+ return `${perspectiveUUID}::${sparqlQuery}`;
14
+ }
15
+ /**
16
+ * Subscribe to a SPARQL query, sharing the underlying subscription
17
+ * with any other subscribers using the same perspective + query.
18
+ *
19
+ * @param perspective - The perspective proxy
20
+ * @param sparqlQuery - The SPARQL query text
21
+ * @param hydrate - Async function that takes raw SPARQL results and returns hydrated results
22
+ * @param onResult - Callback for subsequent result updates (hydrated)
23
+ * @returns PooledSubscription with initial result and dispose function
24
+ */
25
+ export async function pooledSubscribe(perspective, sparqlQuery, hydrate, onResult) {
26
+ const uuid = perspective.uuid || perspective.handle?.uuid || '';
27
+ const key = makeKey(uuid, sparqlQuery);
28
+ const entry = pool.get(key);
29
+ const subscriber = { onResult, hydrate };
30
+ if (entry) {
31
+ // Join existing subscription
32
+ entry.callbacks.add(subscriber);
33
+ entry.refCount++;
34
+ // Hydrate latest result for this new subscriber
35
+ let initialResult;
36
+ if (entry.latestHydrated !== undefined) {
37
+ initialResult = entry.latestHydrated;
38
+ }
39
+ else if (entry.latestRaw !== undefined) {
40
+ initialResult = await hydrate(entry.latestRaw);
41
+ }
42
+ return {
43
+ initialResult,
44
+ dispose: () => disposeSubscriber(key, subscriber),
45
+ };
46
+ }
47
+ // Create new subscription
48
+ const subscription = await perspective.subscribeQuery(sparqlQuery);
49
+ const newEntry = {
50
+ subscription,
51
+ callbacks: new Set([subscriber]),
52
+ latestRaw: subscription.result,
53
+ latestHydrated: undefined,
54
+ hydrating: false,
55
+ refCount: 1,
56
+ };
57
+ pool.set(key, newEntry);
58
+ // Set up shared result handler with delta optimization
59
+ subscription.onResult(async (rawResult) => {
60
+ const prevRaw = newEntry.latestRaw;
61
+ newEntry.latestRaw = rawResult;
62
+ newEntry.hydrating = true;
63
+ try {
64
+ const firstSub = newEntry.callbacks.values().next().value;
65
+ if (firstSub) {
66
+ // Delta optimization: if the new result is strictly an addition
67
+ // (all previous rows still present + new rows), only hydrate the
68
+ // new rows and append them to the cached hydrated result.
69
+ const prevArr = Array.isArray(prevRaw) ? prevRaw : [];
70
+ const newArr = Array.isArray(rawResult) ? rawResult : [];
71
+ const prevHydrated = newEntry.latestHydrated;
72
+ if (prevHydrated &&
73
+ Array.isArray(prevHydrated) &&
74
+ newArr.length > prevArr.length &&
75
+ newArr.length - prevArr.length <= 5 // small delta — worth optimizing
76
+ ) {
77
+ // Build a set of source URIs from previous results for quick lookup
78
+ const prevSources = new Set(prevArr.map((r) => `${r.source}|${r.predicate}|${r.target}`));
79
+ const addedRows = newArr.filter((r) => !prevSources.has(`${r.source}|${r.predicate}|${r.target}`));
80
+ // Check that no rows were removed (pure addition)
81
+ const newSources = new Set(newArr.map((r) => `${r.source}|${r.predicate}|${r.target}`));
82
+ const removedRows = prevArr.filter((r) => !newSources.has(`${r.source}|${r.predicate}|${r.target}`));
83
+ if (removedRows.length === 0 && addedRows.length > 0) {
84
+ // Verify ALL added rows have sources not in previous results.
85
+ // If any added row's source matches an existing source, it means
86
+ // an existing instance got new links — we need full rehydration.
87
+ const prevSourceIds = new Set(prevArr.map((r) => r.source));
88
+ const allNewSources = addedRows.every((r) => !prevSourceIds.has(r.source));
89
+ if (allNewSources) {
90
+ // Pure addition of new instances — hydrate only the new rows
91
+ try {
92
+ const deltaHydrated = await firstSub.hydrate(addedRows);
93
+ if (Array.isArray(deltaHydrated)) {
94
+ const merged = [...prevHydrated, ...deltaHydrated];
95
+ newEntry.latestHydrated = merged;
96
+ for (const cb of newEntry.callbacks) {
97
+ try {
98
+ cb.onResult(merged);
99
+ }
100
+ catch (e) { /* subscriber error */ }
101
+ }
102
+ return; // Delta path succeeded
103
+ }
104
+ }
105
+ catch {
106
+ // Delta hydration failed — fall through to full hydration
107
+ }
108
+ }
109
+ }
110
+ }
111
+ // Full hydration fallback
112
+ const hydrated = await firstSub.hydrate(rawResult);
113
+ newEntry.latestHydrated = hydrated;
114
+ // Distribute to all callbacks
115
+ for (const cb of newEntry.callbacks) {
116
+ try {
117
+ cb.onResult(hydrated);
118
+ }
119
+ catch (e) { /* subscriber error */ }
120
+ }
121
+ }
122
+ }
123
+ finally {
124
+ newEntry.hydrating = false;
125
+ }
126
+ });
127
+ // Hydrate initial result
128
+ const initialResult = await hydrate(subscription.result);
129
+ newEntry.latestHydrated = initialResult;
130
+ return {
131
+ initialResult,
132
+ dispose: () => disposeSubscriber(key, subscriber),
133
+ };
134
+ }
135
+ function disposeSubscriber(key, subscriber) {
136
+ const entry = pool.get(key);
137
+ if (!entry)
138
+ return;
139
+ entry.callbacks.delete(subscriber);
140
+ entry.refCount--;
141
+ if (entry.refCount <= 0) {
142
+ // Last subscriber — tear down the underlying subscription
143
+ if (entry.subscription?.dispose) {
144
+ entry.subscription.dispose();
145
+ }
146
+ pool.delete(key);
147
+ }
148
+ }
149
+ /**
150
+ * Clear the entire pool (for testing).
151
+ */
152
+ export function clearSubscriptionPool() {
153
+ for (const entry of pool.values()) {
154
+ if (entry.subscription?.dispose) {
155
+ entry.subscription.dispose();
156
+ }
157
+ }
158
+ pool.clear();
159
+ }
160
+ /**
161
+ * Get the current pool size (for testing).
162
+ */
163
+ export function subscriptionPoolSize() {
164
+ return pool.size;
165
+ }
@@ -2,7 +2,7 @@
2
2
  * Shared type definitions for the Ad4mModel system.
3
3
  *
4
4
  * Extracted into a standalone module so that utility files
5
- * (`surreal-utils.ts`, `decorators.ts`, etc.) can import types without
5
+ * (`query-utils.ts`, `decorators.ts`, etc.) can import types without
6
6
  * creating circular runtime dependencies on `Ad4mModel.ts`.
7
7
  */
8
8
  import type { Ad4mModel } from "./Ad4mModel";
@@ -41,12 +41,47 @@ export type ParentScope = {
41
41
  id: string;
42
42
  predicate: string;
43
43
  };
44
+ /**
45
+ * Descriptor for a user-named projection — a derived field computed from a
46
+ * relation that is attached to the parent instance under a custom `$`-prefixed
47
+ * key in the `IncludeMap`.
48
+ *
49
+ * The `from` field must name a declared relation on the model.
50
+ *
51
+ * @example
52
+ * ```typescript
53
+ * include: {
54
+ * $signalCount: { from: 'signals', count: true },
55
+ * $mySignal: { from: 'signals', where: { author: myDid }, limit: 1 },
56
+ * $likeSignals: { from: 'signals', where: { signalTypeId: 'like' } },
57
+ * }
58
+ * ```
59
+ */
60
+ export interface IncludeProjection {
61
+ /** Declared relation name on the model to derive the projection from. */
62
+ from: string;
63
+ /**
64
+ * When true, the projection result is the count of matching instances
65
+ * as a `number`. All other options (`where`, `limit`) are still applied
66
+ * before counting. `count: true` → result type is `number`.
67
+ */
68
+ count?: true;
69
+ /** Filter applied to the related instances before the projection result is produced. */
70
+ where?: Where;
71
+ /**
72
+ * Maximum number of results to include.
73
+ * When `limit` is `1`, the result type is `T | null` (unwrapped single instance)
74
+ * rather than `T[]`.
75
+ */
76
+ limit?: number;
77
+ }
44
78
  /**
45
79
  * Describes which relations to eager-load when querying.
46
80
  *
47
81
  * Each value is either:
48
82
  * - `true` — hydrate the relation one level deep
49
83
  * - A `RelationSubQuery` — scoped sub-query (filter / sort / paginate / nested include)
84
+ * - An `IncludeProjection` — user-named derived field (count, filtered subset, single item)
50
85
  *
51
86
  * @example
52
87
  * ```typescript
@@ -58,10 +93,13 @@ export type ParentScope = {
58
93
  *
59
94
  * // Nested eager-load
60
95
  * { comments: { include: { author: true } } }
96
+ *
97
+ * // Projection: count + filtered single item
98
+ * { $signalCount: { from: 'signals', count: true }, $mySignal: { from: 'signals', where: { author: myDid }, limit: 1 } }
61
99
  * ```
62
100
  */
63
101
  export interface IncludeMap {
64
- [relation: string]: boolean | RelationSubQuery;
102
+ [relation: string]: boolean | RelationSubQuery | IncludeProjection;
65
103
  }
66
104
  export type Query = {
67
105
  /** Filter to instances that are the target of a link from a given parent. */
@@ -73,6 +111,16 @@ export type Query = {
73
111
  offset?: number;
74
112
  limit?: number;
75
113
  count?: boolean;
114
+ /**
115
+ * When true, SPARQL property getters (@Property with `getter`) ARE evaluated
116
+ * during collection hydration. By default, collection queries skip getter
117
+ * evaluation for performance — getters run only on single-instance get().
118
+ *
119
+ * Use this when you need getter-backed properties (e.g. `replyingTo`,
120
+ * `isPopular`) in a list query. For most list/feed UIs, leave this off
121
+ * and use `Ad4mModel.evaluateGetters()` on visible items only.
122
+ */
123
+ deepQuery?: boolean;
76
124
  };
77
125
  /**
78
126
  * Sub-query options for a specific relation inside an `IncludeMap`.
@@ -128,7 +176,7 @@ export interface PropertyMetadata {
128
176
  prologGetter?: string;
129
177
  /** Custom Prolog setter code */
130
178
  prologSetter?: string;
131
- /** Custom SurrealQL getter code */
179
+ /** Custom getter code */
132
180
  getter?: string;
133
181
  /** Whether stored locally only */
134
182
  local?: boolean;
@@ -145,7 +193,7 @@ export interface RelationMetadata {
145
193
  name: string;
146
194
  /** The predicate URI (through value) */
147
195
  predicate: string;
148
- /** Custom SurrealQL getter code */
196
+ /** Custom getter code */
149
197
  getter?: string;
150
198
  /** Whether stored locally only */
151
199
  local?: boolean;
@@ -2,7 +2,7 @@
2
2
  * Shared type definitions for the Ad4mModel system.
3
3
  *
4
4
  * Extracted into a standalone module so that utility files
5
- * (`surreal-utils.ts`, `decorators.ts`, etc.) can import types without
5
+ * (`query-utils.ts`, `decorators.ts`, etc.) can import types without
6
6
  * creating circular runtime dependencies on `Ad4mModel.ts`.
7
7
  */
8
8
  export {};
@@ -17,6 +17,8 @@ export type SyncStateChangeCallback = (state: PerspectiveState) => null;
17
17
  export declare class PerspectiveClient {
18
18
  #private;
19
19
  constructor(client: ApolloClient<any>, subscribe?: boolean);
20
+ /** Get or create a proxy for a UUID. If the proxy exists in cache, update its handle and return it. */
21
+ private getOrCreateProxy;
20
22
  setExpressionClient(client: ExpressionClient): void;
21
23
  setNeighbourhoodClient(client: NeighbourhoodClient): void;
22
24
  setAIClient(client: AIClient): void;
@@ -27,28 +29,12 @@ export declare class PerspectiveClient {
27
29
  publishSnapshotByUUID(uuid: string): Promise<string | null>;
28
30
  queryLinks(uuid: string, query: LinkQuery): Promise<LinkExpression[]>;
29
31
  queryProlog(uuid: string, query: string): Promise<any>;
30
- /**
31
- * Executes a read-only SurrealQL query against a perspective's link cache.
32
- *
33
- * Security: Only SELECT, RETURN, and other read-only queries are permitted.
34
- * Mutating operations (DELETE, UPDATE, INSERT, etc.) are blocked.
35
- *
36
- * Note: GraphQL field name is "perspectiveQuerySurrealDb" (lowercase "b" in "Db")
37
- * as generated from Rust method "perspective_query_surreal_db"
38
- */
39
- querySurrealDB(uuid: string, query: string): Promise<any>;
32
+ querySparql(uuid: string, query: string): Promise<any>;
40
33
  subscribeQuery(uuid: string, query: string): Promise<{
41
34
  subscriptionId: string;
42
35
  result: AllInstancesResult;
43
36
  isInit?: boolean;
44
37
  }>;
45
- perspectiveSubscribeSurrealQuery(uuid: string, query: string): Promise<{
46
- subscriptionId: string;
47
- result: AllInstancesResult;
48
- isInit?: boolean;
49
- }>;
50
- perspectiveKeepAliveSurrealQuery(uuid: string, subscriptionId: string): Promise<boolean>;
51
- perspectiveDisposeSurrealQuerySubscription(uuid: string, subscriptionId: string): Promise<boolean>;
52
38
  subscribeToQueryUpdates(subscriptionId: string, onData: (result: AllInstancesResult) => void): () => void;
53
39
  keepAliveQuery(uuid: string, subscriptionId: string): Promise<boolean>;
54
40
  disposeQuerySubscription(uuid: string, subscriptionId: string): Promise<boolean>;
@@ -9,7 +9,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  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");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _PerspectiveClient_apolloClient, _PerspectiveClient_perspectiveAddedCallbacks, _PerspectiveClient_perspectiveUpdatedCallbacks, _PerspectiveClient_perspectiveRemovedCallbacks, _PerspectiveClient_perspectiveSyncStateChangeCallbacks, _PerspectiveClient_expressionClient, _PerspectiveClient_neighbourhoodClient, _PerspectiveClient_aiClient;
12
+ var _PerspectiveClient_apolloClient, _PerspectiveClient_perspectiveAddedCallbacks, _PerspectiveClient_perspectiveUpdatedCallbacks, _PerspectiveClient_perspectiveRemovedCallbacks, _PerspectiveClient_perspectiveSyncStateChangeCallbacks, _PerspectiveClient_expressionClient, _PerspectiveClient_neighbourhoodClient, _PerspectiveClient_aiClient, _PerspectiveClient_proxyCache;
13
13
  import { gql } from "@apollo/client/core";
14
14
  import { NeighbourhoodProxy } from "../neighbourhood/NeighbourhoodProxy";
15
15
  import unwrapApolloResult from "../unwrapApolloResult";
@@ -53,6 +53,7 @@ export class PerspectiveClient {
53
53
  _PerspectiveClient_expressionClient.set(this, void 0);
54
54
  _PerspectiveClient_neighbourhoodClient.set(this, void 0);
55
55
  _PerspectiveClient_aiClient.set(this, void 0);
56
+ _PerspectiveClient_proxyCache.set(this, new Map());
56
57
  __classPrivateFieldSet(this, _PerspectiveClient_apolloClient, client, "f");
57
58
  __classPrivateFieldSet(this, _PerspectiveClient_perspectiveAddedCallbacks, [], "f");
58
59
  __classPrivateFieldSet(this, _PerspectiveClient_perspectiveUpdatedCallbacks, [], "f");
@@ -64,6 +65,17 @@ export class PerspectiveClient {
64
65
  this.subscribePerspectiveRemoved();
65
66
  }
66
67
  }
68
+ /** Get or create a proxy for a UUID. If the proxy exists in cache, update its handle and return it. */
69
+ getOrCreateProxy(handle) {
70
+ const existing = __classPrivateFieldGet(this, _PerspectiveClient_proxyCache, "f").get(handle.uuid);
71
+ if (existing) {
72
+ existing.updateHandle(handle);
73
+ return existing;
74
+ }
75
+ const proxy = new PerspectiveProxy(handle, this);
76
+ __classPrivateFieldGet(this, _PerspectiveClient_proxyCache, "f").set(handle.uuid, proxy);
77
+ return proxy;
78
+ }
67
79
  setExpressionClient(client) {
68
80
  __classPrivateFieldSet(this, _PerspectiveClient_expressionClient, client, "f");
69
81
  }
@@ -84,9 +96,12 @@ export class PerspectiveClient {
84
96
  }
85
97
  }`
86
98
  }));
87
- return perspectives.map(handle => new PerspectiveProxy(handle, this));
99
+ return perspectives.map(handle => this.getOrCreateProxy(handle));
88
100
  }
89
101
  async byUUID(uuid) {
102
+ const cached = __classPrivateFieldGet(this, _PerspectiveClient_proxyCache, "f").get(uuid);
103
+ if (cached)
104
+ return cached;
90
105
  const { perspective } = unwrapApolloResult(await __classPrivateFieldGet(this, _PerspectiveClient_apolloClient, "f").query({
91
106
  query: gql `query perspective($uuid: String!) {
92
107
  perspective(uuid: $uuid) {
@@ -97,7 +112,7 @@ export class PerspectiveClient {
97
112
  }));
98
113
  if (!perspective)
99
114
  return null;
100
- return new PerspectiveProxy(perspective, this);
115
+ return this.getOrCreateProxy(perspective);
101
116
  }
102
117
  async snapshotByUUID(uuid) {
103
118
  const { perspectiveSnapshot } = unwrapApolloResult(await __classPrivateFieldGet(this, _PerspectiveClient_apolloClient, "f").query({
@@ -139,23 +154,14 @@ export class PerspectiveClient {
139
154
  }));
140
155
  return JSON.parse(perspectiveQueryProlog);
141
156
  }
142
- /**
143
- * Executes a read-only SurrealQL query against a perspective's link cache.
144
- *
145
- * Security: Only SELECT, RETURN, and other read-only queries are permitted.
146
- * Mutating operations (DELETE, UPDATE, INSERT, etc.) are blocked.
147
- *
148
- * Note: GraphQL field name is "perspectiveQuerySurrealDb" (lowercase "b" in "Db")
149
- * as generated from Rust method "perspective_query_surreal_db"
150
- */
151
- async querySurrealDB(uuid, query) {
152
- const { perspectiveQuerySurrealDb } = unwrapApolloResult(await __classPrivateFieldGet(this, _PerspectiveClient_apolloClient, "f").query({
153
- query: gql `query perspectiveQuerySurrealDb($uuid: String!, $query: String!) {
154
- perspectiveQuerySurrealDb(uuid: $uuid, query: $query)
157
+ async querySparql(uuid, query) {
158
+ const { perspectiveQuerySparql } = unwrapApolloResult(await __classPrivateFieldGet(this, _PerspectiveClient_apolloClient, "f").query({
159
+ query: gql `query perspectiveQuerySparql($uuid: String!, $query: String!) {
160
+ perspectiveQuerySparql(uuid: $uuid, query: $query)
155
161
  }`,
156
162
  variables: { uuid, query }
157
163
  }));
158
- return JSON.parse(perspectiveQuerySurrealDb);
164
+ return JSON.parse(perspectiveQuerySparql);
159
165
  }
160
166
  async subscribeQuery(uuid, query) {
161
167
  const { perspectiveSubscribeQuery } = unwrapApolloResult(await __classPrivateFieldGet(this, _PerspectiveClient_apolloClient, "f").mutate({
@@ -182,49 +188,6 @@ export class PerspectiveClient {
182
188
  }
183
189
  return { subscriptionId, result: finalResult, isInit };
184
190
  }
185
- async perspectiveSubscribeSurrealQuery(uuid, query) {
186
- const { perspectiveSubscribeSurrealQuery } = unwrapApolloResult(await __classPrivateFieldGet(this, _PerspectiveClient_apolloClient, "f").mutate({
187
- mutation: gql `mutation perspectiveSubscribeSurrealQuery($uuid: String!, $query: String!) {
188
- perspectiveSubscribeSurrealQuery(uuid: $uuid, query: $query) {
189
- subscriptionId
190
- result
191
- }
192
- }`,
193
- variables: { uuid, query }
194
- }));
195
- const { subscriptionId, result } = perspectiveSubscribeSurrealQuery;
196
- let finalResult = result;
197
- let isInit = false;
198
- if (finalResult.startsWith("#init#")) {
199
- finalResult = finalResult.substring(6);
200
- isInit = true;
201
- }
202
- try {
203
- finalResult = JSON.parse(finalResult);
204
- }
205
- catch (e) {
206
- console.error('Error parsing perspectiveSubscribeSurrealQuery result:', e);
207
- }
208
- return { subscriptionId, result: finalResult, isInit };
209
- }
210
- async perspectiveKeepAliveSurrealQuery(uuid, subscriptionId) {
211
- const { perspectiveKeepAliveSurrealQuery } = unwrapApolloResult(await __classPrivateFieldGet(this, _PerspectiveClient_apolloClient, "f").mutate({
212
- mutation: gql `mutation perspectiveKeepAliveSurrealQuery($uuid: String!, $subscriptionId: String!) {
213
- perspectiveKeepAliveSurrealQuery(uuid: $uuid, subscriptionId: $subscriptionId)
214
- }`,
215
- variables: { uuid, subscriptionId }
216
- }));
217
- return perspectiveKeepAliveSurrealQuery;
218
- }
219
- async perspectiveDisposeSurrealQuerySubscription(uuid, subscriptionId) {
220
- const { perspectiveDisposeSurrealQuerySubscription } = unwrapApolloResult(await __classPrivateFieldGet(this, _PerspectiveClient_apolloClient, "f").mutate({
221
- mutation: gql `mutation perspectiveDisposeSurrealQuerySubscription($uuid: String!, $subscriptionId: String!) {
222
- perspectiveDisposeSurrealQuerySubscription(uuid: $uuid, subscriptionId: $subscriptionId)
223
- }`,
224
- variables: { uuid, subscriptionId }
225
- }));
226
- return perspectiveDisposeSurrealQuerySubscription;
227
- }
228
191
  subscribeToQueryUpdates(subscriptionId, onData) {
229
192
  const subscription = __classPrivateFieldGet(this, _PerspectiveClient_apolloClient, "f").subscribe({
230
193
  query: gql `
@@ -287,7 +250,7 @@ export class PerspectiveClient {
287
250
  }`,
288
251
  variables: { name }
289
252
  }));
290
- return new PerspectiveProxy(perspectiveAdd, this);
253
+ return this.getOrCreateProxy(perspectiveAdd);
291
254
  }
292
255
  async update(uuid, name) {
293
256
  const { perspectiveUpdate } = unwrapApolloResult(await __classPrivateFieldGet(this, _PerspectiveClient_apolloClient, "f").mutate({
@@ -298,9 +261,12 @@ export class PerspectiveClient {
298
261
  }`,
299
262
  variables: { uuid, name }
300
263
  }));
301
- return new PerspectiveProxy(perspectiveUpdate, this);
264
+ // Evict stale proxy — getOrCreateProxy will create a fresh one with updated handle
265
+ __classPrivateFieldGet(this, _PerspectiveClient_proxyCache, "f").delete(uuid);
266
+ return this.getOrCreateProxy(perspectiveUpdate);
302
267
  }
303
268
  async remove(uuid) {
269
+ __classPrivateFieldGet(this, _PerspectiveClient_proxyCache, "f").delete(uuid);
304
270
  return unwrapApolloResult(await __classPrivateFieldGet(this, _PerspectiveClient_apolloClient, "f").mutate({
305
271
  mutation: gql `mutation perspectiveRemove($uuid: String!) {
306
272
  perspectiveRemove(uuid: $uuid)
@@ -453,9 +419,12 @@ export class PerspectiveClient {
453
419
  `
454
420
  }).subscribe({
455
421
  next: result => {
422
+ const handle = result.data.perspectiveAdded;
456
423
  __classPrivateFieldGet(this, _PerspectiveClient_perspectiveAddedCallbacks, "f").forEach(cb => {
457
- cb(result.data.perspectiveAdded);
424
+ cb(handle);
458
425
  });
426
+ // Populate cache so subsequent byUUID() calls get a hit
427
+ this.getOrCreateProxy(handle);
459
428
  },
460
429
  error: (e) => console.error(e)
461
430
  });
@@ -471,9 +440,13 @@ export class PerspectiveClient {
471
440
  `
472
441
  }).subscribe({
473
442
  next: result => {
443
+ const handle = result.data.perspectiveUpdated;
474
444
  __classPrivateFieldGet(this, _PerspectiveClient_perspectiveUpdatedCallbacks, "f").forEach(cb => {
475
- cb(result.data.perspectiveUpdated);
445
+ cb(handle);
476
446
  });
447
+ // Evict stale proxy and create fresh one with updated handle
448
+ __classPrivateFieldGet(this, _PerspectiveClient_proxyCache, "f").delete(handle.uuid);
449
+ this.getOrCreateProxy(handle);
477
450
  },
478
451
  error: (e) => console.error(e)
479
452
  });
@@ -508,9 +481,12 @@ export class PerspectiveClient {
508
481
  `
509
482
  }).subscribe({
510
483
  next: result => {
484
+ const uuid = result.data.perspectiveRemoved;
511
485
  __classPrivateFieldGet(this, _PerspectiveClient_perspectiveRemovedCallbacks, "f").forEach(cb => {
512
- cb(result.data.perspectiveRemoved);
486
+ cb(uuid);
513
487
  });
488
+ // Evict from cache
489
+ __classPrivateFieldGet(this, _PerspectiveClient_proxyCache, "f").delete(uuid);
514
490
  },
515
491
  error: (e) => console.error(e)
516
492
  });
@@ -608,4 +584,4 @@ export class PerspectiveClient {
608
584
  return perspectiveCommitBatch;
609
585
  }
610
586
  }
611
- _PerspectiveClient_apolloClient = new WeakMap(), _PerspectiveClient_perspectiveAddedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveUpdatedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveRemovedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveSyncStateChangeCallbacks = new WeakMap(), _PerspectiveClient_expressionClient = new WeakMap(), _PerspectiveClient_neighbourhoodClient = new WeakMap(), _PerspectiveClient_aiClient = new WeakMap();
587
+ _PerspectiveClient_apolloClient = new WeakMap(), _PerspectiveClient_perspectiveAddedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveUpdatedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveRemovedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveSyncStateChangeCallbacks = new WeakMap(), _PerspectiveClient_expressionClient = new WeakMap(), _PerspectiveClient_neighbourhoodClient = new WeakMap(), _PerspectiveClient_aiClient = new WeakMap(), _PerspectiveClient_proxyCache = new WeakMap();
@@ -0,0 +1 @@
1
+ export {};