@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,211 @@
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
+
12
+ import type { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
13
+
14
+ type HydrateCallback = (rawResult: any) => Promise<any>;
15
+ type ResultCallback = (hydratedResult: any) => void;
16
+
17
+ interface PoolEntry {
18
+ /** The underlying subscription from perspective.subscribeQuery() */
19
+ subscription: any;
20
+ /** All registered callbacks */
21
+ callbacks: Set<{ onResult: ResultCallback; hydrate: HydrateCallback }>;
22
+ /** Latest raw result (for new subscribers joining late) */
23
+ latestRaw: any;
24
+ /** Latest hydrated result */
25
+ latestHydrated: any;
26
+ /** Whether hydration is in flight */
27
+ hydrating: boolean;
28
+ /** Reference count for disposal */
29
+ refCount: number;
30
+ }
31
+
32
+ const pool = new Map<string, PoolEntry>();
33
+
34
+ function makeKey(perspectiveUUID: string, sparqlQuery: string): string {
35
+ return `${perspectiveUUID}::${sparqlQuery}`;
36
+ }
37
+
38
+ export interface PooledSubscription {
39
+ /** The initial (hydrated) result */
40
+ initialResult: any;
41
+ /** Unsubscribe this particular callback from the pool */
42
+ dispose: () => void;
43
+ }
44
+
45
+ /**
46
+ * Subscribe to a SPARQL query, sharing the underlying subscription
47
+ * with any other subscribers using the same perspective + query.
48
+ *
49
+ * @param perspective - The perspective proxy
50
+ * @param sparqlQuery - The SPARQL query text
51
+ * @param hydrate - Async function that takes raw SPARQL results and returns hydrated results
52
+ * @param onResult - Callback for subsequent result updates (hydrated)
53
+ * @returns PooledSubscription with initial result and dispose function
54
+ */
55
+ export async function pooledSubscribe(
56
+ perspective: PerspectiveProxy,
57
+ sparqlQuery: string,
58
+ hydrate: HydrateCallback,
59
+ onResult: ResultCallback,
60
+ ): Promise<PooledSubscription> {
61
+ const uuid = (perspective as any).uuid || (perspective as any).handle?.uuid || '';
62
+ const key = makeKey(uuid, sparqlQuery);
63
+
64
+ const entry = pool.get(key);
65
+ const subscriber = { onResult, hydrate };
66
+
67
+ if (entry) {
68
+ // Join existing subscription
69
+ entry.callbacks.add(subscriber);
70
+ entry.refCount++;
71
+
72
+ // Hydrate latest result for this new subscriber
73
+ let initialResult: any;
74
+ if (entry.latestHydrated !== undefined) {
75
+ initialResult = entry.latestHydrated;
76
+ } else if (entry.latestRaw !== undefined) {
77
+ initialResult = await hydrate(entry.latestRaw);
78
+ }
79
+
80
+ return {
81
+ initialResult,
82
+ dispose: () => disposeSubscriber(key, subscriber),
83
+ };
84
+ }
85
+
86
+ // Create new subscription
87
+ const subscription = await perspective.subscribeQuery(sparqlQuery);
88
+
89
+ const newEntry: PoolEntry = {
90
+ subscription,
91
+ callbacks: new Set([subscriber]),
92
+ latestRaw: subscription.result,
93
+ latestHydrated: undefined,
94
+ hydrating: false,
95
+ refCount: 1,
96
+ };
97
+
98
+ pool.set(key, newEntry);
99
+
100
+ // Set up shared result handler with delta optimization
101
+ subscription.onResult(async (rawResult: any) => {
102
+ const prevRaw = newEntry.latestRaw;
103
+ newEntry.latestRaw = rawResult;
104
+ newEntry.hydrating = true;
105
+ try {
106
+ const firstSub = newEntry.callbacks.values().next().value;
107
+ if (firstSub) {
108
+ // Delta optimization: if the new result is strictly an addition
109
+ // (all previous rows still present + new rows), only hydrate the
110
+ // new rows and append them to the cached hydrated result.
111
+ const prevArr = Array.isArray(prevRaw) ? prevRaw : [];
112
+ const newArr = Array.isArray(rawResult) ? rawResult : [];
113
+ const prevHydrated = newEntry.latestHydrated;
114
+
115
+ if (
116
+ prevHydrated &&
117
+ Array.isArray(prevHydrated) &&
118
+ newArr.length > prevArr.length &&
119
+ newArr.length - prevArr.length <= 5 // small delta — worth optimizing
120
+ ) {
121
+ // Build a set of source URIs from previous results for quick lookup
122
+ const prevSources = new Set(prevArr.map((r: any) => `${r.source}|${r.predicate}|${r.target}`));
123
+ const addedRows = newArr.filter((r: any) => !prevSources.has(`${r.source}|${r.predicate}|${r.target}`));
124
+
125
+ // Check that no rows were removed (pure addition)
126
+ const newSources = new Set(newArr.map((r: any) => `${r.source}|${r.predicate}|${r.target}`));
127
+ const removedRows = prevArr.filter((r: any) => !newSources.has(`${r.source}|${r.predicate}|${r.target}`));
128
+
129
+ if (removedRows.length === 0 && addedRows.length > 0) {
130
+ // Verify ALL added rows have sources not in previous results.
131
+ // If any added row's source matches an existing source, it means
132
+ // an existing instance got new links — we need full rehydration.
133
+ const prevSourceIds = new Set(prevArr.map((r: any) => r.source));
134
+ const allNewSources = addedRows.every((r: any) => !prevSourceIds.has(r.source));
135
+
136
+ if (allNewSources) {
137
+ // Pure addition of new instances — hydrate only the new rows
138
+ try {
139
+ const deltaHydrated = await firstSub.hydrate(addedRows);
140
+ if (Array.isArray(deltaHydrated)) {
141
+ const merged = [...prevHydrated, ...deltaHydrated];
142
+ newEntry.latestHydrated = merged;
143
+ for (const cb of newEntry.callbacks) {
144
+ try { cb.onResult(merged); } catch (e) { /* subscriber error */ }
145
+ }
146
+ return; // Delta path succeeded
147
+ }
148
+ } catch {
149
+ // Delta hydration failed — fall through to full hydration
150
+ }
151
+ }
152
+ }
153
+ }
154
+
155
+ // Full hydration fallback
156
+ const hydrated = await firstSub.hydrate(rawResult);
157
+ newEntry.latestHydrated = hydrated;
158
+ // Distribute to all callbacks
159
+ for (const cb of newEntry.callbacks) {
160
+ try { cb.onResult(hydrated); } catch (e) { /* subscriber error */ }
161
+ }
162
+ }
163
+ } finally {
164
+ newEntry.hydrating = false;
165
+ }
166
+ });
167
+
168
+ // Hydrate initial result
169
+ const initialResult = await hydrate(subscription.result);
170
+ newEntry.latestHydrated = initialResult;
171
+
172
+ return {
173
+ initialResult,
174
+ dispose: () => disposeSubscriber(key, subscriber),
175
+ };
176
+ }
177
+
178
+ function disposeSubscriber(key: string, subscriber: { onResult: ResultCallback; hydrate: HydrateCallback }): void {
179
+ const entry = pool.get(key);
180
+ if (!entry) return;
181
+
182
+ entry.callbacks.delete(subscriber);
183
+ entry.refCount--;
184
+
185
+ if (entry.refCount <= 0) {
186
+ // Last subscriber — tear down the underlying subscription
187
+ if (entry.subscription?.dispose) {
188
+ entry.subscription.dispose();
189
+ }
190
+ pool.delete(key);
191
+ }
192
+ }
193
+
194
+ /**
195
+ * Clear the entire pool (for testing).
196
+ */
197
+ export function clearSubscriptionPool(): void {
198
+ for (const entry of pool.values()) {
199
+ if (entry.subscription?.dispose) {
200
+ entry.subscription.dispose();
201
+ }
202
+ }
203
+ pool.clear();
204
+ }
205
+
206
+ /**
207
+ * Get the current pool size (for testing).
208
+ */
209
+ export function subscriptionPoolSize(): number {
210
+ return pool.size;
211
+ }
@@ -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
 
@@ -41,12 +41,48 @@ export type ParentScope =
41
41
  | { model: typeof Ad4mModel; id: string; field?: string }
42
42
  | { id: string; 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
+ }
78
+
44
79
  /**
45
80
  * Describes which relations to eager-load when querying.
46
81
  *
47
82
  * Each value is either:
48
83
  * - `true` — hydrate the relation one level deep
49
84
  * - A `RelationSubQuery` — scoped sub-query (filter / sort / paginate / nested include)
85
+ * - An `IncludeProjection` — user-named derived field (count, filtered subset, single item)
50
86
  *
51
87
  * @example
52
88
  * ```typescript
@@ -58,10 +94,13 @@ export type ParentScope =
58
94
  *
59
95
  * // Nested eager-load
60
96
  * { comments: { include: { author: true } } }
97
+ *
98
+ * // Projection: count + filtered single item
99
+ * { $signalCount: { from: 'signals', count: true }, $mySignal: { from: 'signals', where: { author: myDid }, limit: 1 } }
61
100
  * ```
62
101
  */
63
102
  export interface IncludeMap {
64
- [relation: string]: boolean | RelationSubQuery;
103
+ [relation: string]: boolean | RelationSubQuery | IncludeProjection;
65
104
  }
66
105
 
67
106
  export type Query = {
@@ -74,6 +113,16 @@ export type Query = {
74
113
  offset?: number;
75
114
  limit?: number;
76
115
  count?: boolean;
116
+ /**
117
+ * When true, SPARQL property getters (@Property with `getter`) ARE evaluated
118
+ * during collection hydration. By default, collection queries skip getter
119
+ * evaluation for performance — getters run only on single-instance get().
120
+ *
121
+ * Use this when you need getter-backed properties (e.g. `replyingTo`,
122
+ * `isPopular`) in a list query. For most list/feed UIs, leave this off
123
+ * and use `Ad4mModel.evaluateGetters()` on visible items only.
124
+ */
125
+ deepQuery?: boolean;
77
126
  };
78
127
 
79
128
  /**
@@ -134,7 +183,7 @@ export interface PropertyMetadata {
134
183
  prologGetter?: string;
135
184
  /** Custom Prolog setter code */
136
185
  prologSetter?: string;
137
- /** Custom SurrealQL getter code */
186
+ /** Custom getter code */
138
187
  getter?: string;
139
188
  /** Whether stored locally only */
140
189
  local?: boolean;
@@ -152,7 +201,7 @@ export interface RelationMetadata {
152
201
  name: string;
153
202
  /** The predicate URI (through value) */
154
203
  predicate: string;
155
- /** Custom SurrealQL getter code */
204
+ /** Custom getter code */
156
205
  getter?: string;
157
206
  /** Whether stored locally only */
158
207
  local?: boolean;
@@ -0,0 +1,204 @@
1
+ import { ApolloClient, InMemoryCache, gql } from "@apollo/client/core"
2
+ import { PerspectiveClient } from "./PerspectiveClient"
3
+ import { PerspectiveHandle, PerspectiveState } from "./PerspectiveHandle"
4
+
5
+ /**
6
+ * Focused unit tests for PerspectiveClient proxy cache behaviour.
7
+ * Uses a mock Apollo client to isolate cache logic from network.
8
+ */
9
+
10
+ // Minimal mock Apollo client that returns controllable results
11
+ function createMockApolloClient(overrides: {
12
+ query?: (opts: any) => any,
13
+ mutate?: (opts: any) => any,
14
+ subscribe?: (opts: any) => any,
15
+ } = {}) {
16
+ return {
17
+ query: overrides.query || jest.fn().mockResolvedValue({ data: {} }),
18
+ mutate: overrides.mutate || jest.fn().mockResolvedValue({ data: {} }),
19
+ subscribe: overrides.subscribe || jest.fn().mockReturnValue({
20
+ subscribe: jest.fn()
21
+ }),
22
+ } as unknown as ApolloClient<any>
23
+ }
24
+
25
+ function makeHandle(uuid: string, name: string, state = PerspectiveState.Private): PerspectiveHandle {
26
+ const h = new PerspectiveHandle(uuid, name, state)
27
+ return h
28
+ }
29
+
30
+ describe('PerspectiveClient proxy cache', () => {
31
+ it('byUUID returns the same proxy reference on cache hit', async () => {
32
+ const handle = makeHandle('uuid-1', 'Test')
33
+ const mockClient = createMockApolloClient({
34
+ query: jest.fn().mockResolvedValue({
35
+ data: { perspective: handle }
36
+ }),
37
+ })
38
+ const client = new PerspectiveClient(mockClient, false)
39
+
40
+ const p1 = await client.byUUID('uuid-1')
41
+ const p2 = await client.byUUID('uuid-1')
42
+ expect(p1).toBe(p2)
43
+ // Only one query should have been made (second is cache hit)
44
+ expect(mockClient.query).toHaveBeenCalledTimes(1)
45
+ })
46
+
47
+ it('byUUID returns null for non-existent perspectives', async () => {
48
+ const mockClient = createMockApolloClient({
49
+ query: jest.fn().mockResolvedValue({
50
+ data: { perspective: null }
51
+ }),
52
+ })
53
+ const client = new PerspectiveClient(mockClient, false)
54
+ const p = await client.byUUID('non-existent')
55
+ expect(p).toBeNull()
56
+ })
57
+
58
+ it('all() populates cache so subsequent byUUID is a hit', async () => {
59
+ const handles = [
60
+ makeHandle('uuid-a', 'A'),
61
+ makeHandle('uuid-b', 'B'),
62
+ ]
63
+ const queryFn = jest.fn()
64
+ .mockResolvedValueOnce({ data: { perspectives: handles } })
65
+ const mockClient = createMockApolloClient({ query: queryFn })
66
+ const client = new PerspectiveClient(mockClient, false)
67
+
68
+ const all = await client.all()
69
+ expect(all.length).toBe(2)
70
+
71
+ // byUUID should be a cache hit — no additional query
72
+ const pa = await client.byUUID('uuid-a')
73
+ expect(pa).toBe(all[0])
74
+ expect(queryFn).toHaveBeenCalledTimes(1) // only the all() query
75
+ })
76
+
77
+ it('add() populates cache', async () => {
78
+ const handle = makeHandle('uuid-new', 'New')
79
+ const mockClient = createMockApolloClient({
80
+ mutate: jest.fn().mockResolvedValue({
81
+ data: { perspectiveAdd: handle }
82
+ }),
83
+ })
84
+ const client = new PerspectiveClient(mockClient, false)
85
+
86
+ const added = await client.add('New')
87
+ expect(added.uuid).toBe('uuid-new')
88
+
89
+ // byUUID should hit cache
90
+ const fetched = await client.byUUID('uuid-new')
91
+ expect(fetched).toBe(added)
92
+ })
93
+
94
+ it('update() evicts and recreates cached proxy', async () => {
95
+ const originalHandle = makeHandle('uuid-u', 'Original')
96
+ const updatedHandle = makeHandle('uuid-u', 'Updated')
97
+ const queryFn = jest.fn().mockResolvedValue({
98
+ data: { perspective: originalHandle }
99
+ })
100
+ const mutateFn = jest.fn().mockResolvedValue({
101
+ data: { perspectiveUpdate: updatedHandle }
102
+ })
103
+ const mockClient = createMockApolloClient({
104
+ query: queryFn,
105
+ mutate: mutateFn,
106
+ })
107
+ const client = new PerspectiveClient(mockClient, false)
108
+
109
+ const original = await client.byUUID('uuid-u')
110
+ expect(original.name).toBe('Original')
111
+
112
+ const updated = await client.update('uuid-u', 'Updated')
113
+ expect(updated).not.toBe(original) // new reference after eviction
114
+ expect(updated.name).toBe('Updated')
115
+ expect(original.name).toBe('Original') // old reference retains stale data
116
+ })
117
+
118
+ it('remove() evicts from cache', async () => {
119
+ const handle = makeHandle('uuid-r', 'ToRemove')
120
+ const queryFn = jest.fn().mockResolvedValue({
121
+ data: { perspective: handle }
122
+ })
123
+ const mutateFn = jest.fn().mockResolvedValue({
124
+ data: { perspectiveRemove: true }
125
+ })
126
+ const mockClient = createMockApolloClient({
127
+ query: queryFn,
128
+ mutate: mutateFn,
129
+ })
130
+ const client = new PerspectiveClient(mockClient, false)
131
+
132
+ const p = await client.byUUID('uuid-r')
133
+ expect(p).toBeTruthy()
134
+ expect(queryFn).toHaveBeenCalledTimes(1)
135
+
136
+ await client.remove('uuid-r')
137
+
138
+ // byUUID should miss cache and query again
139
+ const handle2 = makeHandle('uuid-r', 'Recreated')
140
+ queryFn.mockResolvedValueOnce({ data: { perspective: handle2 } })
141
+
142
+ const p2 = await client.byUUID('uuid-r')
143
+ expect(p2).not.toBe(p)
144
+ expect(p2.name).toBe('Recreated')
145
+ expect(queryFn).toHaveBeenCalledTimes(2)
146
+ })
147
+
148
+ it('getOrCreateProxy does not re-register listeners on cache hit', async () => {
149
+ // Verify that getting the same proxy twice does not create duplicate subscriptions
150
+ const handle = makeHandle('uuid-dup', 'NoDuplicates')
151
+ const subscribeCalls: string[] = []
152
+ const subscribeFn = jest.fn().mockImplementation((opts) => {
153
+ // Track subscription query names
154
+ const queryStr = opts.query?.loc?.source?.body || ''
155
+ subscribeCalls.push(queryStr)
156
+ return {
157
+ subscribe: jest.fn()
158
+ }
159
+ })
160
+ const queryFn = jest.fn()
161
+ .mockResolvedValueOnce({ data: { perspectives: [handle] } })
162
+ const mockClient = createMockApolloClient({
163
+ query: queryFn,
164
+ subscribe: subscribeFn,
165
+ })
166
+
167
+ const client = new PerspectiveClient(mockClient, false)
168
+ const all = await client.all()
169
+ const firstProxy = all[0]
170
+
171
+ // Record how many subscribe calls happened from PerspectiveProxy constructor
172
+ const callsAfterFirst = subscribeFn.mock.calls.length
173
+
174
+ // Get same proxy again via all() — should be cache hit, no new constructor call
175
+ queryFn.mockResolvedValueOnce({ data: { perspectives: [handle] } })
176
+ const all2 = await client.all()
177
+ const secondProxy = all2[0]
178
+
179
+ expect(secondProxy).toBe(firstProxy)
180
+ // No additional subscribe calls should have been made
181
+ expect(subscribeFn.mock.calls.length).toBe(callsAfterFirst)
182
+ })
183
+
184
+ it('all() updates existing cached proxies with fresh data', async () => {
185
+ const handle1 = makeHandle('uuid-f', 'OldName')
186
+ const handle2 = makeHandle('uuid-f', 'FreshName')
187
+
188
+ const queryFn = jest.fn()
189
+ .mockResolvedValueOnce({ data: { perspective: handle1 } })
190
+ .mockResolvedValueOnce({ data: { perspectives: [handle2] } })
191
+ const mockClient = createMockApolloClient({ query: queryFn })
192
+ const client = new PerspectiveClient(mockClient, false)
193
+
194
+ const original = await client.byUUID('uuid-f')
195
+ expect(original.name).toBe('OldName')
196
+
197
+ const all = await client.all()
198
+ const refreshed = all.find(p => p.uuid === 'uuid-f')
199
+
200
+ expect(refreshed).toBe(original) // same reference
201
+ expect(refreshed.name).toBe('FreshName') // updated in-place
202
+ expect(original.name).toBe('FreshName') // original ref also updated
203
+ })
204
+ })