@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,169 @@
1
+ import { PerspectiveClient } from "./PerspectiveClient";
2
+ import { PerspectiveHandle, PerspectiveState } from "./PerspectiveHandle";
3
+ /**
4
+ * Focused unit tests for PerspectiveClient proxy cache behaviour.
5
+ * Uses a mock Apollo client to isolate cache logic from network.
6
+ */
7
+ // Minimal mock Apollo client that returns controllable results
8
+ function createMockApolloClient(overrides = {}) {
9
+ return {
10
+ query: overrides.query || jest.fn().mockResolvedValue({ data: {} }),
11
+ mutate: overrides.mutate || jest.fn().mockResolvedValue({ data: {} }),
12
+ subscribe: overrides.subscribe || jest.fn().mockReturnValue({
13
+ subscribe: jest.fn()
14
+ }),
15
+ };
16
+ }
17
+ function makeHandle(uuid, name, state = PerspectiveState.Private) {
18
+ const h = new PerspectiveHandle(uuid, name, state);
19
+ return h;
20
+ }
21
+ describe('PerspectiveClient proxy cache', () => {
22
+ it('byUUID returns the same proxy reference on cache hit', async () => {
23
+ const handle = makeHandle('uuid-1', 'Test');
24
+ const mockClient = createMockApolloClient({
25
+ query: jest.fn().mockResolvedValue({
26
+ data: { perspective: handle }
27
+ }),
28
+ });
29
+ const client = new PerspectiveClient(mockClient, false);
30
+ const p1 = await client.byUUID('uuid-1');
31
+ const p2 = await client.byUUID('uuid-1');
32
+ expect(p1).toBe(p2);
33
+ // Only one query should have been made (second is cache hit)
34
+ expect(mockClient.query).toHaveBeenCalledTimes(1);
35
+ });
36
+ it('byUUID returns null for non-existent perspectives', async () => {
37
+ const mockClient = createMockApolloClient({
38
+ query: jest.fn().mockResolvedValue({
39
+ data: { perspective: null }
40
+ }),
41
+ });
42
+ const client = new PerspectiveClient(mockClient, false);
43
+ const p = await client.byUUID('non-existent');
44
+ expect(p).toBeNull();
45
+ });
46
+ it('all() populates cache so subsequent byUUID is a hit', async () => {
47
+ const handles = [
48
+ makeHandle('uuid-a', 'A'),
49
+ makeHandle('uuid-b', 'B'),
50
+ ];
51
+ const queryFn = jest.fn()
52
+ .mockResolvedValueOnce({ data: { perspectives: handles } });
53
+ const mockClient = createMockApolloClient({ query: queryFn });
54
+ const client = new PerspectiveClient(mockClient, false);
55
+ const all = await client.all();
56
+ expect(all.length).toBe(2);
57
+ // byUUID should be a cache hit — no additional query
58
+ const pa = await client.byUUID('uuid-a');
59
+ expect(pa).toBe(all[0]);
60
+ expect(queryFn).toHaveBeenCalledTimes(1); // only the all() query
61
+ });
62
+ it('add() populates cache', async () => {
63
+ const handle = makeHandle('uuid-new', 'New');
64
+ const mockClient = createMockApolloClient({
65
+ mutate: jest.fn().mockResolvedValue({
66
+ data: { perspectiveAdd: handle }
67
+ }),
68
+ });
69
+ const client = new PerspectiveClient(mockClient, false);
70
+ const added = await client.add('New');
71
+ expect(added.uuid).toBe('uuid-new');
72
+ // byUUID should hit cache
73
+ const fetched = await client.byUUID('uuid-new');
74
+ expect(fetched).toBe(added);
75
+ });
76
+ it('update() evicts and recreates cached proxy', async () => {
77
+ const originalHandle = makeHandle('uuid-u', 'Original');
78
+ const updatedHandle = makeHandle('uuid-u', 'Updated');
79
+ const queryFn = jest.fn().mockResolvedValue({
80
+ data: { perspective: originalHandle }
81
+ });
82
+ const mutateFn = jest.fn().mockResolvedValue({
83
+ data: { perspectiveUpdate: updatedHandle }
84
+ });
85
+ const mockClient = createMockApolloClient({
86
+ query: queryFn,
87
+ mutate: mutateFn,
88
+ });
89
+ const client = new PerspectiveClient(mockClient, false);
90
+ const original = await client.byUUID('uuid-u');
91
+ expect(original.name).toBe('Original');
92
+ const updated = await client.update('uuid-u', 'Updated');
93
+ expect(updated).not.toBe(original); // new reference after eviction
94
+ expect(updated.name).toBe('Updated');
95
+ expect(original.name).toBe('Original'); // old reference retains stale data
96
+ });
97
+ it('remove() evicts from cache', async () => {
98
+ const handle = makeHandle('uuid-r', 'ToRemove');
99
+ const queryFn = jest.fn().mockResolvedValue({
100
+ data: { perspective: handle }
101
+ });
102
+ const mutateFn = jest.fn().mockResolvedValue({
103
+ data: { perspectiveRemove: true }
104
+ });
105
+ const mockClient = createMockApolloClient({
106
+ query: queryFn,
107
+ mutate: mutateFn,
108
+ });
109
+ const client = new PerspectiveClient(mockClient, false);
110
+ const p = await client.byUUID('uuid-r');
111
+ expect(p).toBeTruthy();
112
+ expect(queryFn).toHaveBeenCalledTimes(1);
113
+ await client.remove('uuid-r');
114
+ // byUUID should miss cache and query again
115
+ const handle2 = makeHandle('uuid-r', 'Recreated');
116
+ queryFn.mockResolvedValueOnce({ data: { perspective: handle2 } });
117
+ const p2 = await client.byUUID('uuid-r');
118
+ expect(p2).not.toBe(p);
119
+ expect(p2.name).toBe('Recreated');
120
+ expect(queryFn).toHaveBeenCalledTimes(2);
121
+ });
122
+ it('getOrCreateProxy does not re-register listeners on cache hit', async () => {
123
+ // Verify that getting the same proxy twice does not create duplicate subscriptions
124
+ const handle = makeHandle('uuid-dup', 'NoDuplicates');
125
+ const subscribeCalls = [];
126
+ const subscribeFn = jest.fn().mockImplementation((opts) => {
127
+ // Track subscription query names
128
+ const queryStr = opts.query?.loc?.source?.body || '';
129
+ subscribeCalls.push(queryStr);
130
+ return {
131
+ subscribe: jest.fn()
132
+ };
133
+ });
134
+ const queryFn = jest.fn()
135
+ .mockResolvedValueOnce({ data: { perspectives: [handle] } });
136
+ const mockClient = createMockApolloClient({
137
+ query: queryFn,
138
+ subscribe: subscribeFn,
139
+ });
140
+ const client = new PerspectiveClient(mockClient, false);
141
+ const all = await client.all();
142
+ const firstProxy = all[0];
143
+ // Record how many subscribe calls happened from PerspectiveProxy constructor
144
+ const callsAfterFirst = subscribeFn.mock.calls.length;
145
+ // Get same proxy again via all() — should be cache hit, no new constructor call
146
+ queryFn.mockResolvedValueOnce({ data: { perspectives: [handle] } });
147
+ const all2 = await client.all();
148
+ const secondProxy = all2[0];
149
+ expect(secondProxy).toBe(firstProxy);
150
+ // No additional subscribe calls should have been made
151
+ expect(subscribeFn.mock.calls.length).toBe(callsAfterFirst);
152
+ });
153
+ it('all() updates existing cached proxies with fresh data', async () => {
154
+ const handle1 = makeHandle('uuid-f', 'OldName');
155
+ const handle2 = makeHandle('uuid-f', 'FreshName');
156
+ const queryFn = jest.fn()
157
+ .mockResolvedValueOnce({ data: { perspective: handle1 } })
158
+ .mockResolvedValueOnce({ data: { perspectives: [handle2] } });
159
+ const mockClient = createMockApolloClient({ query: queryFn });
160
+ const client = new PerspectiveClient(mockClient, false);
161
+ const original = await client.byUUID('uuid-f');
162
+ expect(original.name).toBe('OldName');
163
+ const all = await client.all();
164
+ const refreshed = all.find(p => p.uuid === 'uuid-f');
165
+ expect(refreshed).toBe(original); // same reference
166
+ expect(refreshed.name).toBe('FreshName'); // updated in-place
167
+ expect(original.name).toBe('FreshName'); // original ref also updated
168
+ });
169
+ });
@@ -46,7 +46,6 @@ type QueryCallback = (result: AllInstancesResult) => void;
46
46
  */
47
47
  export declare class QuerySubscriptionProxy {
48
48
  #private;
49
- isSurrealDB: boolean;
50
49
  /** Creates a new query subscription
51
50
  * @param uuid - The UUID of the perspective
52
51
  * @param query - The Prolog query to subscribe to
@@ -181,6 +180,9 @@ export declare class PerspectiveProxy {
181
180
  * Note: Don't create this directly, use ad4m.perspective.add() instead.
182
181
  */
183
182
  constructor(handle: PerspectiveHandle, ad4m: PerspectiveClient);
183
+ /** Update the proxy's internal handle and public fields in-place.
184
+ * Keeps the same object reference so all holders see the update. */
185
+ updateHandle(handle: PerspectiveHandle): void;
184
186
  /**
185
187
  * Escapes special regex characters in a string to prevent ReDoS attacks
186
188
  * and regex injection when building dynamic regular expressions.
@@ -299,33 +301,22 @@ export declare class PerspectiveProxy {
299
301
  */
300
302
  infer(query: string): Promise<any>;
301
303
  /**
302
- * Executes a SurrealQL query against the perspective's link cache.
303
- * This allows powerful SQL-like queries on the link data stored in SurrealDB.
304
+ * Executes a SPARQL query against the perspective's link cache.
305
+ * This allows powerful SQL-like queries on the link data stored in SPARQL.
304
306
  *
305
307
  * **Security Note:** Only read-only queries (SELECT, RETURN, etc.) are permitted.
306
308
  * Mutating operations (DELETE, UPDATE, INSERT, CREATE, DROP, DEFINE, etc.) are
307
309
  * blocked for security reasons. Use the perspective's add/remove methods to modify links.
308
310
  *
309
- * @param query - SurrealQL query string (read-only operations only)
311
+ * @param query - SPARQL query string (read-only operations only)
310
312
  * @returns Query results as parsed JSON
311
313
  *
312
- * @example
313
- * ```typescript
314
- * // Get all links
315
- * const links = await perspective.querySurrealDB('SELECT * FROM link');
316
- *
317
- * // Filter links by predicate
318
- * const follows = await perspective.querySurrealDB(
319
- * "SELECT * FROM link WHERE predicate = 'follows'"
320
- * );
321
- *
322
- * // Complex aggregation query
323
- * const stats = await perspective.querySurrealDB(
324
- * "SELECT predicate, count() as total FROM link GROUP BY predicate"
325
- * );
326
- * ```
314
+ * Executes a SPARQL query against the perspective's RDF (Oxigraph) store.
315
+ *
316
+ * @param query - SPARQL query string
317
+ * @returns Query results as parsed JSON
327
318
  */
328
- querySurrealDB(query: string): Promise<any>;
319
+ querySparql(query: string): Promise<any>;
329
320
  /**
330
321
  * Adds a new link to the perspective.
331
322
  *
@@ -552,6 +543,11 @@ export declare class PerspectiveProxy {
552
543
  * await perspective.addSdna('Recipe', prologCode, 'subject_class');
553
544
  */
554
545
  addSdna(name: string, sdnaCode: string, sdnaType: "subject_class" | "flow" | "custom", shaclJson?: string): Promise<boolean>;
546
+ /**
547
+ * Adds a subject class to the perspective.
548
+ * Alias for addSdna() with sdnaType='subject_class'.
549
+ */
550
+ addSubjectClass(name: string, shaclJson: string): Promise<boolean>;
555
551
  /**
556
552
  * **Recommended way to add SDNA schemas.**
557
553
  *
@@ -693,6 +689,23 @@ export declare class PerspectiveProxy {
693
689
  * Gets subject class metadata from SHACL links using SHACLShape.fromLinks().
694
690
  * Retrieves the SHACL shape and extracts metadata for instance queries.
695
691
  */
692
+ getSubjectClassMetadata(className: string): Promise<{
693
+ requiredPredicates: string[];
694
+ requiredTriples: Array<{
695
+ predicate: string;
696
+ target?: string;
697
+ }>;
698
+ properties: Map<string, {
699
+ predicate: string;
700
+ resolveLanguage?: string;
701
+ }>;
702
+ relations: Map<string, {
703
+ predicate: string;
704
+ instanceFilter?: string;
705
+ condition?: string;
706
+ }>;
707
+ } | null>;
708
+ /** @deprecated Use getSubjectClassMetadata() */
696
709
  getSubjectClassMetadataFromSDNA(className: string): Promise<{
697
710
  requiredPredicates: string[];
698
711
  requiredTriples: Array<{
@@ -710,22 +723,26 @@ export declare class PerspectiveProxy {
710
723
  }>;
711
724
  } | null>;
712
725
  /**
713
- * Generates a SurrealDB query to find instances based on class metadata.
726
+ * Generates a SPARQL query to find instances based on class metadata.
727
+ */
728
+ /**
729
+ * Finds all instances matching subject class metadata by querying links.
730
+ * Returns base URIs of matching instances.
714
731
  */
715
- private generateSurrealInstanceQuery;
732
+ private findInstancesByMetadata;
716
733
  /**
717
- * Gets a property value using SurrealDB when Prolog fails.
734
+ * Gets a property value using SPARQL when Prolog fails.
718
735
  * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
719
736
  */
720
- getPropertyValueViaSurreal(baseExpression: string, className: string, propertyName: string): Promise<any>;
737
+ getPropertyValueViaSparql(baseExpression: string, className: string, propertyName: string): Promise<any>;
721
738
  /**
722
- * Gets relation values using SurrealDB when Prolog fails.
739
+ * Gets relation values using SPARQL when Prolog fails.
723
740
  * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
724
741
  * Note: This is used by Subject.ts (legacy pattern). Ad4mModel.ts uses getModelMetadata() instead.
725
742
  */
726
- getRelationValuesViaSurreal(baseExpression: string, className: string, relationName: string): Promise<any[]>;
743
+ getRelationValuesViaSparql(baseExpression: string, className: string, relationName: string): Promise<any[]>;
727
744
  /**
728
- * Batch-checks multiple expressions against subject class metadata using a single or limited SurrealDB queries.
745
+ * Batch-checks multiple expressions against subject class metadata using a single or limited SPARQL queries.
729
746
  * This avoids N+1 query problems by checking all values at once.
730
747
  */
731
748
  batchCheckSubjectInstances(expressions: string[], metadata: {
@@ -785,6 +802,12 @@ export declare class PerspectiveProxy {
785
802
  * static generateSDNA() function and adds it to the perspective's SDNA.
786
803
  */
787
804
  ensureSDNASubjectClass(jsClass: any): Promise<void>;
805
+ /** Takes a JS class (its constructor) and ensures the SHACL subject class exists. */
806
+ ensureSubjectClass(jsClass: any): Promise<void>;
807
+ /** Clear the per-instance ensured subject class cache.
808
+ * Call this after wiping a perspective's links so that
809
+ * subsequent register() calls re-add SHACL definitions. */
810
+ clearEnsuredSubjectClasses(): void;
788
811
  getNeighbourhoodProxy(): NeighbourhoodProxy;
789
812
  /**
790
813
  * Returns a proxy object for working with AI capabilities.
@@ -842,7 +865,7 @@ export declare class PerspectiveProxy {
842
865
  */
843
866
  subscribeInfer(query: string): Promise<QuerySubscriptionProxy>;
844
867
  /**
845
- * Creates a subscription for a SurrealQL query that updates in real-time.
868
+ * Creates a subscription for a SPARQL query that updates in real-time.
846
869
  *
847
870
  * This method:
848
871
  * 1. Creates the subscription on the Rust side
@@ -857,9 +880,10 @@ export declare class PerspectiveProxy {
857
880
  * when dispose() is called. Make sure to call dispose() when you're done to
858
881
  * prevent memory leaks and ensure proper cleanup of resources.
859
882
  *
860
- * @param query - SurrealQL query string
883
+ /** Subscribe to a query with live updates via the SPARQL subscription endpoint.
884
+ * @param query - Query string
861
885
  * @returns Initialized QuerySubscriptionProxy instance
862
886
  */
863
- subscribeSurrealDB(query: string): Promise<QuerySubscriptionProxy>;
887
+ subscribeQuery(query: string): Promise<QuerySubscriptionProxy>;
864
888
  }
865
889
  export {};