@coasys/ad4m 0.13.0-test-interpretation-2 → 0.13.0-test-model-layer

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 (254) hide show
  1. package/lib/index.cjs +1982 -498
  2. package/lib/index.js +1982 -499
  3. package/lib/src/ai/AIClient.js +6 -3
  4. package/lib/src/apiClient.d.ts +40 -4
  5. package/lib/src/apiClient.js +149 -9
  6. package/lib/src/index.d.ts +3 -1
  7. package/lib/src/index.js +2 -0
  8. package/lib/src/model/Ad4mModel.d.ts +6 -5
  9. package/lib/src/model/Ad4mModel.js +246 -29
  10. package/lib/src/model/Ad4mModel.test.js +480 -735
  11. package/lib/src/model/decorators.d.ts +147 -4
  12. package/lib/src/model/decorators.js +70 -24
  13. package/lib/src/model/model-manifest.d.ts +41 -0
  14. package/lib/src/model/model-manifest.js +11 -0
  15. package/lib/src/model/query-sparql.test.js +92 -10
  16. package/lib/src/model/shacl-gen.js +33 -0
  17. package/lib/src/model/types.d.ts +9 -0
  18. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +33 -33
  19. package/lib/src/perspectives/AutoProcessor.d.ts +90 -24
  20. package/lib/src/perspectives/FlowInstance.d.ts +187 -0
  21. package/lib/src/perspectives/FlowInstance.js +336 -0
  22. package/lib/src/perspectives/FlowModels.d.ts +94 -0
  23. package/lib/src/perspectives/FlowModels.js +182 -0
  24. package/lib/src/perspectives/InterpretationModels.d.ts +12 -22
  25. package/lib/src/perspectives/InterpretationModels.js +2 -6
  26. package/lib/src/perspectives/PerspectiveClient.d.ts +68 -7
  27. package/lib/src/perspectives/PerspectiveClient.js +105 -10
  28. package/lib/src/perspectives/PerspectiveProxy.d.ts +142 -57
  29. package/lib/src/perspectives/PerspectiveProxy.js +388 -274
  30. package/lib/src/shacl/SHACLFlow.d.ts +273 -47
  31. package/lib/src/shacl/SHACLFlow.js +397 -88
  32. package/lib/src/shacl/SHACLShape.d.ts +8 -0
  33. package/lib/src/shacl/SHACLShape.js +17 -0
  34. package/lib/src/shacl/SHACLShape.test.js +82 -0
  35. package/package.json +2 -2
  36. package/src/ai/AIClient.ts +6 -3
  37. package/src/apiClient.test.ts +227 -0
  38. package/src/apiClient.ts +185 -9
  39. package/src/index.ts +3 -1
  40. package/src/model/Ad4mModel.test.ts +645 -0
  41. package/src/model/Ad4mModel.ts +245 -26
  42. package/src/model/decorators.ts +216 -35
  43. package/src/model/relation-filtering.test.ts +70 -20
  44. package/src/model/shacl-gen.ts +36 -0
  45. package/src/model/shacl-roundtrip.test.ts +130 -0
  46. package/src/model/types.ts +7 -0
  47. package/src/perspectives/AutoProcessor.ts +94 -24
  48. package/src/perspectives/FlowInstance.ts +369 -0
  49. package/src/perspectives/FlowModels.ts +157 -0
  50. package/src/perspectives/InterpretationModels.ts +13 -25
  51. package/src/perspectives/PerspectiveClient.test.ts +67 -6
  52. package/src/perspectives/PerspectiveClient.ts +142 -12
  53. package/src/perspectives/PerspectiveProxy.test.ts +406 -0
  54. package/src/perspectives/PerspectiveProxy.ts +459 -289
  55. package/src/perspectives/shacl-rpc.test.ts +258 -0
  56. package/src/shacl/SHACLFlow.test.ts +762 -35
  57. package/src/shacl/SHACLFlow.ts +680 -112
  58. package/src/shacl/SHACLShape.ts +31 -0
  59. package/lib/src/generated/rest/AIModelLoadingStatus.d.ts +0 -7
  60. package/lib/src/generated/rest/AIModelLoadingStatus.js +0 -2
  61. package/lib/src/generated/rest/AddAgentInfosRequest.d.ts +0 -3
  62. package/lib/src/generated/rest/AddAgentInfosRequest.js +0 -2
  63. package/lib/src/generated/rest/AddLinkExpressionRequest.d.ts +0 -6
  64. package/lib/src/generated/rest/AddLinkExpressionRequest.js +0 -1
  65. package/lib/src/generated/rest/AddLinkRequest.d.ts +0 -6
  66. package/lib/src/generated/rest/AddLinkRequest.js +0 -1
  67. package/lib/src/generated/rest/AddLinksBulkRequest.d.ts +0 -6
  68. package/lib/src/generated/rest/AddLinksBulkRequest.js +0 -1
  69. package/lib/src/generated/rest/AddSdnaRequest.d.ts +0 -6
  70. package/lib/src/generated/rest/AddSdnaRequest.js +0 -2
  71. package/lib/src/generated/rest/ApplyTemplateRequest.d.ts +0 -4
  72. package/lib/src/generated/rest/ApplyTemplateRequest.js +0 -2
  73. package/lib/src/generated/rest/AuthInfoInput.d.ts +0 -10
  74. package/lib/src/generated/rest/AuthInfoInput.js +0 -1
  75. package/lib/src/generated/rest/BroadcastRequest.d.ts +0 -6
  76. package/lib/src/generated/rest/BroadcastRequest.js +0 -1
  77. package/lib/src/generated/rest/CapabilityInput.d.ts +0 -5
  78. package/lib/src/generated/rest/CapabilityInput.js +0 -1
  79. package/lib/src/generated/rest/CommitBatchRequest.d.ts +0 -3
  80. package/lib/src/generated/rest/CommitBatchRequest.js +0 -2
  81. package/lib/src/generated/rest/ComputeLogEntry.d.ts +0 -9
  82. package/lib/src/generated/rest/ComputeLogEntry.js +0 -2
  83. package/lib/src/generated/rest/CreateExpressionRequest.d.ts +0 -4
  84. package/lib/src/generated/rest/CreateExpressionRequest.js +0 -2
  85. package/lib/src/generated/rest/CreatePerspectiveRequest.d.ts +0 -3
  86. package/lib/src/generated/rest/CreatePerspectiveRequest.js +0 -2
  87. package/lib/src/generated/rest/CreateSubjectRequest.d.ts +0 -6
  88. package/lib/src/generated/rest/CreateSubjectRequest.js +0 -2
  89. package/lib/src/generated/rest/CreateUserRequest.d.ts +0 -4
  90. package/lib/src/generated/rest/CreateUserRequest.js +0 -2
  91. package/lib/src/generated/rest/CreateUserResponse.d.ts +0 -5
  92. package/lib/src/generated/rest/CreateUserResponse.js +0 -2
  93. package/lib/src/generated/rest/DecoratedExpressionProof.d.ts +0 -6
  94. package/lib/src/generated/rest/DecoratedExpressionProof.js +0 -2
  95. package/lib/src/generated/rest/DecoratedLinkExpression.d.ts +0 -10
  96. package/lib/src/generated/rest/DecoratedLinkExpression.js +0 -1
  97. package/lib/src/generated/rest/DisposeQueryRequest.d.ts +0 -3
  98. package/lib/src/generated/rest/DisposeQueryRequest.js +0 -2
  99. package/lib/src/generated/rest/EmailTestRequest.d.ts +0 -6
  100. package/lib/src/generated/rest/EmailTestRequest.js +0 -2
  101. package/lib/src/generated/rest/EmbedRequest.d.ts +0 -4
  102. package/lib/src/generated/rest/EmbedRequest.js +0 -2
  103. package/lib/src/generated/rest/EntanglementProofInput.d.ts +0 -6
  104. package/lib/src/generated/rest/EntanglementProofInput.js +0 -2
  105. package/lib/src/generated/rest/EntanglementProofPreflightRequest.d.ts +0 -4
  106. package/lib/src/generated/rest/EntanglementProofPreflightRequest.js +0 -2
  107. package/lib/src/generated/rest/ExecuteCommandsRequest.d.ts +0 -4
  108. package/lib/src/generated/rest/ExecuteCommandsRequest.js +0 -2
  109. package/lib/src/generated/rest/ExportRequest.d.ts +0 -5
  110. package/lib/src/generated/rest/ExportRequest.js +0 -2
  111. package/lib/src/generated/rest/ExpressionManyRequest.d.ts +0 -3
  112. package/lib/src/generated/rest/ExpressionManyRequest.js +0 -2
  113. package/lib/src/generated/rest/ExpressionProof.d.ts +0 -4
  114. package/lib/src/generated/rest/ExpressionProof.js +0 -2
  115. package/lib/src/generated/rest/ExpressionProofInput.d.ts +0 -6
  116. package/lib/src/generated/rest/ExpressionProofInput.js +0 -2
  117. package/lib/src/generated/rest/FriendSendMessageRequest.d.ts +0 -3
  118. package/lib/src/generated/rest/FriendSendMessageRequest.js +0 -2
  119. package/lib/src/generated/rest/FriendsListRequest.d.ts +0 -3
  120. package/lib/src/generated/rest/FriendsListRequest.js +0 -2
  121. package/lib/src/generated/rest/GenerateAgentRequest.d.ts +0 -3
  122. package/lib/src/generated/rest/GenerateAgentRequest.js +0 -2
  123. package/lib/src/generated/rest/GenerateJwtRequest.d.ts +0 -4
  124. package/lib/src/generated/rest/GenerateJwtRequest.js +0 -2
  125. package/lib/src/generated/rest/GetSubjectDataRequest.d.ts +0 -4
  126. package/lib/src/generated/rest/GetSubjectDataRequest.js +0 -2
  127. package/lib/src/generated/rest/HostingInfoResponse.d.ts +0 -5
  128. package/lib/src/generated/rest/HostingInfoResponse.js +0 -2
  129. package/lib/src/generated/rest/HostingWalletResponse.d.ts +0 -4
  130. package/lib/src/generated/rest/HostingWalletResponse.js +0 -2
  131. package/lib/src/generated/rest/ImportAgentRequest.d.ts +0 -6
  132. package/lib/src/generated/rest/ImportAgentRequest.js +0 -2
  133. package/lib/src/generated/rest/ImportRequest.d.ts +0 -4
  134. package/lib/src/generated/rest/ImportRequest.js +0 -2
  135. package/lib/src/generated/rest/JoinNeighbourhoodRequest.d.ts +0 -3
  136. package/lib/src/generated/rest/JoinNeighbourhoodRequest.js +0 -2
  137. package/lib/src/generated/rest/KeepAliveQueryRequest.d.ts +0 -3
  138. package/lib/src/generated/rest/KeepAliveQueryRequest.js +0 -2
  139. package/lib/src/generated/rest/LanguageMetaInput.d.ts +0 -6
  140. package/lib/src/generated/rest/LanguageMetaInput.js +0 -2
  141. package/lib/src/generated/rest/Link.d.ts +0 -5
  142. package/lib/src/generated/rest/Link.js +0 -2
  143. package/lib/src/generated/rest/LinkExpression.d.ts +0 -10
  144. package/lib/src/generated/rest/LinkExpression.js +0 -1
  145. package/lib/src/generated/rest/LinkExpressionInput.d.ts +0 -10
  146. package/lib/src/generated/rest/LinkExpressionInput.js +0 -1
  147. package/lib/src/generated/rest/LinkInput.d.ts +0 -5
  148. package/lib/src/generated/rest/LinkInput.js +0 -2
  149. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.d.ts +0 -3
  150. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.js +0 -2
  151. package/lib/src/generated/rest/LinkMutationRequest.d.ts +0 -12
  152. package/lib/src/generated/rest/LinkMutationRequest.js +0 -1
  153. package/lib/src/generated/rest/LinkMutationResponse.d.ts +0 -9
  154. package/lib/src/generated/rest/LinkMutationResponse.js +0 -1
  155. package/lib/src/generated/rest/LinkMutations.d.ts +0 -6
  156. package/lib/src/generated/rest/LinkMutations.js +0 -1
  157. package/lib/src/generated/rest/LinkMutationsRequest.d.ts +0 -5
  158. package/lib/src/generated/rest/LinkMutationsRequest.js +0 -1
  159. package/lib/src/generated/rest/LinkStatus.d.ts +0 -1
  160. package/lib/src/generated/rest/LinkStatus.js +0 -2
  161. package/lib/src/generated/rest/LinkUpdateInput.d.ts +0 -5
  162. package/lib/src/generated/rest/LinkUpdateInput.js +0 -1
  163. package/lib/src/generated/rest/LockAgentRequest.d.ts +0 -3
  164. package/lib/src/generated/rest/LockAgentRequest.js +0 -2
  165. package/lib/src/generated/rest/LoginUserRequest.d.ts +0 -5
  166. package/lib/src/generated/rest/LoginUserRequest.js +0 -2
  167. package/lib/src/generated/rest/ModelType.d.ts +0 -1
  168. package/lib/src/generated/rest/ModelType.js +0 -2
  169. package/lib/src/generated/rest/NotificationGrantRequest.d.ts +0 -3
  170. package/lib/src/generated/rest/NotificationGrantRequest.js +0 -2
  171. package/lib/src/generated/rest/NotificationInput.d.ts +0 -10
  172. package/lib/src/generated/rest/NotificationInput.js +0 -2
  173. package/lib/src/generated/rest/OpenLinkRequest.d.ts +0 -3
  174. package/lib/src/generated/rest/OpenLinkRequest.js +0 -2
  175. package/lib/src/generated/rest/PermitCapabilityRequest.d.ts +0 -3
  176. package/lib/src/generated/rest/PermitCapabilityRequest.js +0 -2
  177. package/lib/src/generated/rest/PerspectiveInput.d.ts +0 -4
  178. package/lib/src/generated/rest/PerspectiveInput.js +0 -1
  179. package/lib/src/generated/rest/PromptRequest.d.ts +0 -4
  180. package/lib/src/generated/rest/PromptRequest.js +0 -2
  181. package/lib/src/generated/rest/PublicPerspectiveInput.d.ts +0 -4
  182. package/lib/src/generated/rest/PublicPerspectiveInput.js +0 -1
  183. package/lib/src/generated/rest/PublishLanguageRequest.d.ts +0 -5
  184. package/lib/src/generated/rest/PublishLanguageRequest.js +0 -1
  185. package/lib/src/generated/rest/PublishNeighbourhoodRequest.d.ts +0 -6
  186. package/lib/src/generated/rest/PublishNeighbourhoodRequest.js +0 -1
  187. package/lib/src/generated/rest/QueryRequest.d.ts +0 -7
  188. package/lib/src/generated/rest/QueryRequest.js +0 -2
  189. package/lib/src/generated/rest/RemoveLinkRequest.d.ts +0 -5
  190. package/lib/src/generated/rest/RemoveLinkRequest.js +0 -1
  191. package/lib/src/generated/rest/RemoveLinksBulkRequest.d.ts +0 -5
  192. package/lib/src/generated/rest/RemoveLinksBulkRequest.js +0 -1
  193. package/lib/src/generated/rest/RequestCapabilityRequest.d.ts +0 -4
  194. package/lib/src/generated/rest/RequestCapabilityRequest.js +0 -1
  195. package/lib/src/generated/rest/RequestPaymentRequest.d.ts +0 -3
  196. package/lib/src/generated/rest/RequestPaymentRequest.js +0 -2
  197. package/lib/src/generated/rest/RequestVerificationRequest.d.ts +0 -4
  198. package/lib/src/generated/rest/RequestVerificationRequest.js +0 -2
  199. package/lib/src/generated/rest/ResourceInput.d.ts +0 -4
  200. package/lib/src/generated/rest/ResourceInput.js +0 -2
  201. package/lib/src/generated/rest/SetDefaultModelRequest.d.ts +0 -4
  202. package/lib/src/generated/rest/SetDefaultModelRequest.js +0 -1
  203. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.d.ts +0 -3
  204. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.js +0 -2
  205. package/lib/src/generated/rest/SetHotWalletAddressRequest.d.ts +0 -3
  206. package/lib/src/generated/rest/SetHotWalletAddressRequest.js +0 -2
  207. package/lib/src/generated/rest/SetMultiUserRequest.d.ts +0 -3
  208. package/lib/src/generated/rest/SetMultiUserRequest.js +0 -2
  209. package/lib/src/generated/rest/SetOnlineStatusRequest.d.ts +0 -5
  210. package/lib/src/generated/rest/SetOnlineStatusRequest.js +0 -1
  211. package/lib/src/generated/rest/SetStatusRequest.d.ts +0 -3
  212. package/lib/src/generated/rest/SetStatusRequest.js +0 -2
  213. package/lib/src/generated/rest/SetUserFreeAccessRequest.d.ts +0 -4
  214. package/lib/src/generated/rest/SetUserFreeAccessRequest.js +0 -2
  215. package/lib/src/generated/rest/SignMessageRequest.d.ts +0 -3
  216. package/lib/src/generated/rest/SignMessageRequest.js +0 -2
  217. package/lib/src/generated/rest/SignalRequest.d.ts +0 -6
  218. package/lib/src/generated/rest/SignalRequest.js +0 -1
  219. package/lib/src/generated/rest/SubscribeQueryRequest.d.ts +0 -3
  220. package/lib/src/generated/rest/SubscribeQueryRequest.js +0 -2
  221. package/lib/src/generated/rest/SubscribeQueryResponse.d.ts +0 -4
  222. package/lib/src/generated/rest/SubscribeQueryResponse.js +0 -2
  223. package/lib/src/generated/rest/TrustedAgentsRequest.d.ts +0 -3
  224. package/lib/src/generated/rest/TrustedAgentsRequest.js +0 -2
  225. package/lib/src/generated/rest/UnlockAgentRequest.d.ts +0 -4
  226. package/lib/src/generated/rest/UnlockAgentRequest.js +0 -2
  227. package/lib/src/generated/rest/UpdateLinkRequest.d.ts +0 -7
  228. package/lib/src/generated/rest/UpdateLinkRequest.js +0 -1
  229. package/lib/src/generated/rest/UpdatePerspectiveRequest.d.ts +0 -3
  230. package/lib/src/generated/rest/UpdatePerspectiveRequest.js +0 -2
  231. package/lib/src/generated/rest/UpdateProfileRequest.d.ts +0 -5
  232. package/lib/src/generated/rest/UpdateProfileRequest.js +0 -1
  233. package/lib/src/generated/rest/UserStatistics.d.ts +0 -9
  234. package/lib/src/generated/rest/UserStatistics.js +0 -2
  235. package/lib/src/generated/rest/VerificationRequestResult.d.ts +0 -6
  236. package/lib/src/generated/rest/VerificationRequestResult.js +0 -2
  237. package/lib/src/generated/rest/VerifyEmailRequest.d.ts +0 -6
  238. package/lib/src/generated/rest/VerifyEmailRequest.js +0 -2
  239. package/lib/src/generated/rest/VerifySignatureRequest.d.ts +0 -5
  240. package/lib/src/generated/rest/VerifySignatureRequest.js +0 -2
  241. package/lib/src/generated/rest/WriteSettingsRequest.d.ts +0 -3
  242. package/lib/src/generated/rest/WriteSettingsRequest.js +0 -2
  243. package/lib/src/generated/rest/index.d.ts +0 -73
  244. package/lib/src/generated/rest/index.js +0 -8
  245. package/lib/src/generated/rest/routes.d.ts +0 -587
  246. package/lib/src/generated/rest/routes.js +0 -3
  247. package/lib/src/model/query-surreal.d.ts +0 -44
  248. package/lib/src/model/query-surreal.js +0 -249
  249. package/lib/src/model/surreal-utils.d.ts +0 -42
  250. package/lib/src/model/surreal-utils.js +0 -128
  251. package/lib/src/perspectives/PerspectiveProxy.test.d.ts +0 -1
  252. package/lib/src/perspectives/PerspectiveProxy.test.js +0 -34
  253. package/lib/src/restClient.d.ts +0 -52
  254. package/lib/src/restClient.js +0 -227
@@ -333,4 +333,86 @@ describe('SHACLShape', () => {
333
333
  expect(prop.remover).toEqual(original.properties[0].remover);
334
334
  });
335
335
  });
336
+ describe('sh:in round-trip', () => {
337
+ it('preserves sh:in enum values through toLinks() → fromLinks()', () => {
338
+ const original = new SHACLShape('test://Model');
339
+ original.addProperty({
340
+ name: 'status',
341
+ path: 'test://status',
342
+ datatype: 'xsd:string',
343
+ in: [
344
+ { value: 'active', label: 'Active' },
345
+ { value: 'inactive', label: 'Inactive' },
346
+ { value: 'archived' },
347
+ ],
348
+ });
349
+ const links = original.toLinks();
350
+ // Verify sh:in link was created
351
+ const inLink = links.find(l => l.predicate === 'sh://in');
352
+ expect(inLink).toBeDefined();
353
+ expect(inLink.target).toContain('literal:string:');
354
+ // Reconstruct and verify
355
+ const reconstructed = SHACLShape.fromLinks(links, 'test://ModelShape');
356
+ expect(reconstructed.properties[0].in).toBeDefined();
357
+ expect(reconstructed.properties[0].in).toEqual([
358
+ { value: 'active', label: 'Active' },
359
+ { value: 'inactive', label: 'Inactive' },
360
+ { value: 'archived' },
361
+ ]);
362
+ });
363
+ it('handles sh:in with special characters in values', () => {
364
+ const original = new SHACLShape('test://Model');
365
+ original.addProperty({
366
+ name: 'category',
367
+ path: 'test://category',
368
+ in: [
369
+ { value: 'food & drink', label: 'Food & Drink' },
370
+ { value: 'arts/crafts' },
371
+ ],
372
+ });
373
+ const links = original.toLinks();
374
+ const reconstructed = SHACLShape.fromLinks(links, 'test://ModelShape');
375
+ expect(reconstructed.properties[0].in).toEqual(original.properties[0].in);
376
+ });
377
+ it('handles sh:in with empty array (no link created)', () => {
378
+ const original = new SHACLShape('test://Model');
379
+ original.addProperty({
380
+ name: 'field',
381
+ path: 'test://field',
382
+ in: [],
383
+ });
384
+ const links = original.toLinks();
385
+ const inLink = links.find(l => l.predicate === 'sh://in');
386
+ expect(inLink).toBeUndefined();
387
+ });
388
+ it('handles sh:in with literal://string: prefix variant', () => {
389
+ // fromLinks should handle both `literal:string:` and `literal://string:` prefixes
390
+ const links = [
391
+ { source: 'test://ModelShape', predicate: 'sh://targetClass', target: 'test://Model' },
392
+ { source: 'test://ModelShape', predicate: 'sh://property', target: 'test://Model.status' },
393
+ { source: 'test://Model.status', predicate: 'sh://path', target: 'test://status' },
394
+ { source: 'test://Model.status', predicate: 'sh://in', target: 'literal://string:[{"value":"a"},{"value":"b"}]' },
395
+ ];
396
+ const reconstructed = SHACLShape.fromLinks(links, 'test://ModelShape');
397
+ expect(reconstructed.properties[0].in).toEqual([
398
+ { value: 'a' },
399
+ { value: 'b' },
400
+ ]);
401
+ });
402
+ it('preserves sh:in through toJSON() → fromJSON()', () => {
403
+ const original = new SHACLShape('test://Model');
404
+ original.addProperty({
405
+ name: 'priority',
406
+ path: 'test://priority',
407
+ in: [
408
+ { value: 'high', label: 'High' },
409
+ { value: 'medium', label: 'Medium' },
410
+ { value: 'low', label: 'Low' },
411
+ ],
412
+ });
413
+ const json = original.toJSON();
414
+ const reconstructed = SHACLShape.fromJSON(json);
415
+ expect(reconstructed.properties[0].in).toEqual(original.properties[0].in);
416
+ });
417
+ });
336
418
  });
package/package.json CHANGED
@@ -33,7 +33,7 @@
33
33
  "dependencies": {
34
34
  "@holochain/client": "0.16.0",
35
35
  "base64-js": "*",
36
- "pako": "*"
36
+ "pako": "^2.1.0"
37
37
  },
38
38
  "devDependencies": {
39
39
  "@rollup/plugin-commonjs": "^20.0.0",
@@ -61,5 +61,5 @@
61
61
  "pako": "2.1.0"
62
62
  }
63
63
  },
64
- "version": "0.13.0-test-interpretation-2"
64
+ "version": "0.13.0-test-model-layer"
65
65
  }
@@ -83,9 +83,12 @@ export class AIClient {
83
83
  const aiEmbed = await this.#apiClient.call<string>('ai.embed', { modelId, text });
84
84
 
85
85
  const compressed = base64js.toByteArray(aiEmbed);
86
- // Decode to a string via TextDecoder rather than pako's `{ to: 'string' }`
87
- // option: newer @types/pako dropped that overload, which broke the build.
88
- const decompressed = JSON.parse(new TextDecoder().decode(pako.inflate(compressed)));
86
+ // NB: pako v1 accepts `{ to: 'string' }`, pako v2 wants `{ toText: true }`,
87
+ // pako v3 also drops that overload from its bundled types. Call the
88
+ // version-agnostic form (returns Uint8Array) and decode explicitly so
89
+ // this works regardless of which pako major the lockfile pins.
90
+ const inflated = pako.inflate(compressed);
91
+ const decompressed = JSON.parse(new TextDecoder('utf-8').decode(inflated));
89
92
 
90
93
  return decompressed;
91
94
  }
@@ -0,0 +1,227 @@
1
+ import { ApiClient } from "./apiClient"
2
+
3
+ /**
4
+ * Unit tests for ApiClient AbortSignal support.
5
+ *
6
+ * Uses a fake WebSocket implementation injected via the constructor so
7
+ * we can drive open / send / message / close transitions deterministically
8
+ * without spinning up a real server.
9
+ */
10
+
11
+ type AnyMsg = Record<string, unknown>
12
+
13
+ class FakeWebSocket {
14
+ static OPEN = 1
15
+ static CONNECTING = 0
16
+ static CLOSING = 2
17
+ static CLOSED = 3
18
+
19
+ readyState = FakeWebSocket.CONNECTING
20
+ sent: string[] = []
21
+ onopen: ((ev?: unknown) => void) | null = null
22
+ onmessage: ((ev: { data: string }) => void) | null = null
23
+ onerror: ((ev: unknown) => void) | null = null
24
+ onclose: ((ev?: unknown) => void) | null = null
25
+
26
+ static last: FakeWebSocket | null = null
27
+
28
+ constructor(public url: string) {
29
+ FakeWebSocket.last = this
30
+ // Defer "open" so callers can attach handlers first.
31
+ setTimeout(() => {
32
+ this.readyState = FakeWebSocket.OPEN
33
+ this.onopen?.()
34
+ }, 0)
35
+ }
36
+
37
+ send(data: string) {
38
+ this.sent.push(data)
39
+ }
40
+
41
+ close() {
42
+ this.readyState = FakeWebSocket.CLOSED
43
+ this.onclose?.()
44
+ }
45
+
46
+ // Test helper — simulate a server-sent message.
47
+ serverPush(msg: AnyMsg) {
48
+ this.onmessage?.({ data: JSON.stringify(msg) })
49
+ }
50
+ }
51
+
52
+ function lastSent(ws: FakeWebSocket): AnyMsg | undefined {
53
+ if (ws.sent.length === 0) return undefined
54
+ return JSON.parse(ws.sent[ws.sent.length - 1]) as AnyMsg
55
+ }
56
+
57
+ function flushMicrotasks() {
58
+ return new Promise((r) => setTimeout(r, 0))
59
+ }
60
+
61
+ describe('ApiClient AbortSignal support', () => {
62
+ it('rejects immediately with AbortError if signal is already aborted', async () => {
63
+ const client = new ApiClient(
64
+ 'http://localhost:1234',
65
+ undefined,
66
+ FakeWebSocket as unknown as new (url: string) => WebSocket,
67
+ )
68
+ const controller = new AbortController()
69
+ controller.abort()
70
+
71
+ let caught: unknown
72
+ try {
73
+ await client.call('agent.get', {}, { signal: controller.signal })
74
+ } catch (e) {
75
+ caught = e
76
+ }
77
+ expect(caught).toBeInstanceOf(DOMException)
78
+ expect((caught as DOMException).name).toBe('AbortError')
79
+ // No socket should have been opened — the fast-path bailed before _ready.
80
+ expect(FakeWebSocket.last).toBeNull()
81
+
82
+ client.closeAll()
83
+ })
84
+
85
+ it('sends request.cancel and rejects with AbortError when signal fires mid-flight', async () => {
86
+ const client = new ApiClient(
87
+ 'http://localhost:1234',
88
+ undefined,
89
+ FakeWebSocket as unknown as new (url: string) => WebSocket,
90
+ )
91
+ const controller = new AbortController()
92
+ const promise = client.call('perspective.querySparql', { uuid: 'u', engine: 'sparql', query: 'SELECT * WHERE { ?s ?p ?o }' }, { signal: controller.signal })
93
+
94
+ // Wait for socket open + send.
95
+ await flushMicrotasks()
96
+ const ws = FakeWebSocket.last
97
+ expect(ws).not.toBeNull()
98
+ // First send should be the actual RPC request.
99
+ const sentReq = JSON.parse(ws!.sent[0]) as AnyMsg
100
+ expect(sentReq.type).toBe('perspective.querySparql')
101
+ const origId = sentReq.id as string
102
+
103
+ // Now abort.
104
+ controller.abort()
105
+
106
+ // Last sent message should be request.cancel pointing at orig id.
107
+ const cancelMsg = lastSent(ws!)
108
+ expect(cancelMsg).toBeDefined()
109
+ expect(cancelMsg!.type).toBe('request.cancel')
110
+ const params = cancelMsg!.params as { targetId: string }
111
+ expect(params.targetId).toBe(origId)
112
+
113
+ // The promise should now reject with AbortError.
114
+ let caught: unknown
115
+ try { await promise } catch (e) { caught = e }
116
+ expect(caught).toBeInstanceOf(DOMException)
117
+ expect((caught as DOMException).name).toBe('AbortError')
118
+
119
+ client.closeAll()
120
+ })
121
+
122
+ it('late server reply after abort does not resolve or reject the original promise twice', async () => {
123
+ const client = new ApiClient(
124
+ 'http://localhost:1234',
125
+ undefined,
126
+ FakeWebSocket as unknown as new (url: string) => WebSocket,
127
+ )
128
+ const events: AnyMsg[] = []
129
+ client.subscribe((m) => events.push(m as AnyMsg))
130
+
131
+ const controller = new AbortController()
132
+ const promise = client.call('perspective.querySparql', { uuid: 'u', engine: 'sparql', query: 'q' }, { signal: controller.signal })
133
+
134
+ await flushMicrotasks()
135
+ const ws = FakeWebSocket.last!
136
+ const sentReq = JSON.parse(ws.sent[0]) as AnyMsg
137
+ const origId = sentReq.id as string
138
+
139
+ controller.abort()
140
+ let caught: unknown
141
+ try { await promise } catch (e) { caught = e }
142
+ expect((caught as DOMException).name).toBe('AbortError')
143
+
144
+ // Now the server (oblivious to cancellation) ships a late reply.
145
+ // It must NOT trigger a double-settle (no unhandled rejection from
146
+ // the test, no resolve thrown — the promise is already settled).
147
+ // Because we delete the entry from _pendingCalls on abort, the
148
+ // late reply with the same id will be routed to subscribers
149
+ // instead.
150
+ ws.serverPush({ id: origId, result: '[]' })
151
+
152
+ // Subscribers should have received the late reply (it's routed
153
+ // because the id is no longer in _pendingCalls).
154
+ const lateReply = events.find((e) => e.id === origId)
155
+ expect(lateReply).toBeDefined()
156
+ expect(lateReply!.result).toBe('[]')
157
+
158
+ client.closeAll()
159
+ })
160
+
161
+ it('successful resolution removes the abort listener (no leak)', async () => {
162
+ const client = new ApiClient(
163
+ 'http://localhost:1234',
164
+ undefined,
165
+ FakeWebSocket as unknown as new (url: string) => WebSocket,
166
+ )
167
+ const controller = new AbortController()
168
+ let listenerCount = 0
169
+ const orig = controller.signal.addEventListener.bind(controller.signal)
170
+ controller.signal.addEventListener = ((type: string, listener: any, opts?: any) => {
171
+ listenerCount++
172
+ return orig(type as any, listener, opts)
173
+ }) as typeof controller.signal.addEventListener
174
+
175
+ const promise = client.call('agent.get', {}, { signal: controller.signal })
176
+ await flushMicrotasks()
177
+ const ws = FakeWebSocket.last!
178
+ const sentReq = JSON.parse(ws.sent[0]) as AnyMsg
179
+ const origId = sentReq.id as string
180
+
181
+ // Resolve the call.
182
+ ws.serverPush({ id: origId, result: { did: 'did:test' } })
183
+ const result = await promise
184
+ expect((result as { did: string }).did).toBe('did:test')
185
+
186
+ // After resolution, firing the controller should not trigger any
187
+ // abort handler (the listener was removed in cleanup()). The
188
+ // simplest detection: confirm the abort doesn't cause a stray
189
+ // request.cancel message on the wire — i.e. no new send beyond
190
+ // the original.
191
+ const sendCountBefore = ws.sent.length
192
+ controller.abort()
193
+ // Give microtasks a chance.
194
+ await flushMicrotasks()
195
+ expect(ws.sent.length).toBe(sendCountBefore)
196
+ // Two listeners were registered in total: one in _readyOrAbort
197
+ // (connection phase) and one in call() (in-flight phase). Both
198
+ // were removed via cleanup — the "no extra send" check above
199
+ // confirms no stale handler remains.
200
+ expect(listenerCount).toBe(2)
201
+
202
+ client.closeAll()
203
+ })
204
+
205
+ it('passes through normal call signatures (no options) without regression', async () => {
206
+ const client = new ApiClient(
207
+ 'http://localhost:1234',
208
+ undefined,
209
+ FakeWebSocket as unknown as new (url: string) => WebSocket,
210
+ )
211
+ const promise = client.call('agent.get', { foo: 'bar' })
212
+ await flushMicrotasks()
213
+ const ws = FakeWebSocket.last!
214
+ const sentReq = JSON.parse(ws.sent[0]) as AnyMsg
215
+ expect(sentReq.type).toBe('agent.get')
216
+ expect(sentReq.params).toEqual({ foo: 'bar' })
217
+ ws.serverPush({ id: sentReq.id, result: { did: 'd' } })
218
+ const result = await promise
219
+ expect((result as { did: string }).did).toBe('d')
220
+
221
+ client.closeAll()
222
+ })
223
+
224
+ beforeEach(() => {
225
+ FakeWebSocket.last = null
226
+ })
227
+ })
package/src/apiClient.ts CHANGED
@@ -19,6 +19,31 @@ export class RpcError extends Error {
19
19
  }
20
20
  }
21
21
 
22
+ /** Options accepted by [`ApiClient.call`]. */
23
+ export interface CallOptions {
24
+ /**
25
+ * AbortSignal that, when fired, sends a `request.cancel` to the
26
+ * executor and rejects the call with a DOMException (`name === 'AbortError'`).
27
+ *
28
+ * Use this for long-running operations like `querySparql` so a UI
29
+ * teardown or a newer query supersession can stop the in-flight one
30
+ * without paying the network + deserialise tax on its result.
31
+ *
32
+ * Cancellation is best-effort on the executor: the SPARQL evaluation
33
+ * itself isn't preempted (Oxigraph can't be interrupted), but the
34
+ * reply is discarded and the network traffic + JSON parsing on the
35
+ * client are skipped.
36
+ */
37
+ signal?: AbortSignal
38
+
39
+ /**
40
+ * Per-call timeout override in ms. Defaults to [[DEFAULT_TIMEOUT_MS]].
41
+ * Use for long-running calls (LLM prompts, holochain ops) that
42
+ * legitimately exceed the default.
43
+ */
44
+ timeoutMs?: number
45
+ }
46
+
22
47
  /** Default RPC call timeout in milliseconds (30 seconds). */
23
48
  const DEFAULT_TIMEOUT_MS = 30_000
24
49
 
@@ -69,6 +94,8 @@ export class ApiClient {
69
94
 
70
95
  private _ws: WebSocket | null = null
71
96
  private _wsCallbacks = new Set<(data: unknown) => void>()
97
+ private _reconnectCallbacks = new Set<() => void>()
98
+ private _hasConnectedOnce = false
72
99
  private _pendingCalls = new Map<string, PendingCall>()
73
100
  private _wsReady: Promise<void> | null = null
74
101
  private _wsReadyResolve: (() => void) | null = null
@@ -76,6 +103,7 @@ export class ApiClient {
76
103
  private _wsReconnectDelay = INITIAL_RECONNECT_DELAY_MS
77
104
  private _wsClosed = false
78
105
  private _wsPingTimer: ReturnType<typeof setInterval> | null = null
106
+ private _ignoredResponseIds = new Set<string>()
79
107
 
80
108
  private _getWsUrl(): string {
81
109
  const wsBase = this.baseUrl
@@ -100,7 +128,20 @@ export class ApiClient {
100
128
  })
101
129
 
102
130
  const url = this._getWsUrl()
103
- const WsImpl = this._webSocketImpl ?? WebSocket
131
+ // Fallback order: injected impl → globalThis.WebSocket (browsers, Node ≥ 22) → require('ws') (Node ≤ 20).
132
+ // globalThis lookup avoids a ReferenceError on Node 18 where `WebSocket` is not a global.
133
+ const globalWs = (globalThis as any).WebSocket as (new (url: string) => WebSocket) | undefined
134
+ let WsImpl: new (url: string) => WebSocket
135
+ if (this._webSocketImpl) {
136
+ WsImpl = this._webSocketImpl
137
+ } else if (globalWs) {
138
+ WsImpl = globalWs
139
+ } else {
140
+ // Lazy CommonJS require so bundlers targeting browsers don't try to bundle `ws`.
141
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
142
+ const req = eval('require') as NodeRequire
143
+ WsImpl = req('ws') as new (url: string) => WebSocket
144
+ }
104
145
  const ws = new WsImpl(url)
105
146
  this._ws = ws
106
147
 
@@ -111,6 +152,16 @@ export class ApiClient {
111
152
  this._wsReadyResolve = null
112
153
  }
113
154
  this._startPing()
155
+
156
+ // Fire reconnect callbacks only on reconnect (not first connect)
157
+ if (this._hasConnectedOnce) {
158
+ for (const cb of this._reconnectCallbacks) {
159
+ try { cb() } catch (e) {
160
+ console.error('Error in reconnect callback:', e)
161
+ }
162
+ }
163
+ }
164
+ this._hasConnectedOnce = true
114
165
  }
115
166
 
116
167
  ws.onmessage = (event) => {
@@ -139,6 +190,14 @@ export class ApiClient {
139
190
  return
140
191
  }
141
192
 
193
+ // Discard ack responses to cancel requests we sent — they have
194
+ // an id that was never in _pendingCalls, so without this guard
195
+ // they'd leak into subscriber callbacks as spurious events.
196
+ if (id && this._ignoredResponseIds.has(id)) {
197
+ this._ignoredResponseIds.delete(id)
198
+ return
199
+ }
200
+
142
201
  // Server-push event (no id, or id not in pending) → route to subscribers
143
202
  for (const cb of this._wsCallbacks) cb(parsed)
144
203
  }
@@ -201,44 +260,147 @@ export class ApiClient {
201
260
  if (this._wsReady) await this._wsReady
202
261
  }
203
262
 
263
+ /**
264
+ * Like `_ready()`, but races the connection against an AbortSignal so
265
+ * that callers don't hang if the signal fires while connecting.
266
+ */
267
+ private async _readyOrAbort(signal?: AbortSignal): Promise<void> {
268
+ if (signal?.aborted) {
269
+ throw new DOMException('Aborted', 'AbortError')
270
+ }
271
+
272
+ await new Promise<void>((resolve, reject) => {
273
+ let settled = false
274
+
275
+ const finish = (fn: () => void) => {
276
+ if (settled) return
277
+ settled = true
278
+ if (signal && onAbort) {
279
+ signal.removeEventListener('abort', onAbort)
280
+ }
281
+ fn()
282
+ }
283
+
284
+ const onAbort = signal
285
+ ? () => finish(() => reject(new DOMException('Aborted', 'AbortError')))
286
+ : null
287
+
288
+ if (onAbort) {
289
+ signal!.addEventListener('abort', onAbort, { once: true })
290
+ }
291
+
292
+ this._ready().then(
293
+ () => finish(resolve),
294
+ (error) => finish(() => reject(error)),
295
+ )
296
+ })
297
+ }
298
+
204
299
  // ── RPC call method ─────────────────────────────────────────────────────
205
300
 
206
301
  /**
207
302
  * Send an RPC call over the WebSocket connection.
208
303
  * @param type - The operation type (e.g. 'agent.get', 'perspective.all')
209
304
  * @param params - Optional parameters to include in the message
210
- * @param timeoutMs - Optional per-call timeout override in ms. Defaults to
211
- * [[DEFAULT_TIMEOUT_MS]]. Use for long-running calls (LLM prompts,
212
- * holochain ops) that legitimately exceed the default.
305
+ * @param options - Optional call options: `signal` (AbortSignal for
306
+ * cancellation) and/or `timeoutMs` (per-call timeout override,
307
+ * defaults to [[DEFAULT_TIMEOUT_MS]] — use for long-running calls
308
+ * like LLM prompts or holochain ops that legitimately exceed it).
213
309
  * @returns Promise that resolves with the result from the server
214
310
  */
215
- async call<T>(type: string, params?: Record<string, unknown>, timeoutMs?: number): Promise<T> {
216
- await this._ready()
311
+ async call<T>(type: string, params?: Record<string, unknown>, options?: CallOptions): Promise<T> {
312
+ // Fast-path: if the caller already aborted, bail out before
313
+ // opening the socket. Matches fetch()'s behaviour.
314
+ const signal = options?.signal
315
+ if (signal?.aborted) {
316
+ throw new DOMException('Aborted', 'AbortError')
317
+ }
318
+
319
+ await this._readyOrAbort(signal)
217
320
 
218
321
  const id = nextId()
219
322
  // Put params under a "params" key to avoid collision with
220
323
  // protocol fields "id" and "type" (e.g. params might contain
221
324
  // { id: modelId } or { type: "db" }).
222
325
  const message: Record<string, unknown> = { id, type, params: params || {} }
223
- const effectiveTimeout = timeoutMs ?? DEFAULT_TIMEOUT_MS
326
+ const effectiveTimeout = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS
224
327
 
225
328
  return new Promise<T>((resolve, reject) => {
329
+ let abortHandler: (() => void) | null = null
330
+
331
+ const cleanup = () => {
332
+ if (signal && abortHandler) {
333
+ signal.removeEventListener('abort', abortHandler)
334
+ abortHandler = null
335
+ }
336
+ }
337
+
226
338
  const timer = setTimeout(() => {
227
339
  this._pendingCalls.delete(id)
340
+ cleanup()
228
341
  reject(new RpcError(408, `RPC call '${type}' timed out after ${effectiveTimeout}ms`))
229
342
  }, effectiveTimeout)
230
343
 
344
+ // Wrap resolve/reject so we always clean up the abort listener.
231
345
  this._pendingCalls.set(id, {
232
- resolve: resolve as (value: unknown) => void,
233
- reject,
346
+ resolve: (value: unknown) => { cleanup(); resolve(value as T) },
347
+ reject: (reason: unknown) => { cleanup(); reject(reason) },
234
348
  timer,
235
349
  })
236
350
 
351
+ if (signal) {
352
+ abortHandler = () => {
353
+ // Drop the pending entry first so the late server
354
+ // reply (if any) routes to the event subscribers,
355
+ // not to a stale resolver.
356
+ this._pendingCalls.delete(id)
357
+ clearTimeout(timer)
358
+ cleanup()
359
+
360
+ // Best-effort `request.cancel` — the executor will
361
+ // race the cancellation token against the in-flight
362
+ // handler. If the socket is already gone there's
363
+ // nothing useful we can send; the client side is
364
+ // still aborted either way.
365
+ if (this._ws && this._ws.readyState === 1 /* OPEN */) {
366
+ try {
367
+ const cancelId = nextId()
368
+ this._ignoredResponseIds.add(cancelId)
369
+ // Safety-net eviction: if the executor's ack never
370
+ // arrives (e.g. the socket drops right after we
371
+ // send request.cancel), the normal cleanup path
372
+ // (deleting the id when its response lands) never
373
+ // fires and the entry would live in this set for
374
+ // the lifetime of the client. Bound it instead —
375
+ // DEFAULT_TIMEOUT_MS is already the ceiling every
376
+ // other in-flight call uses, so an ack that hasn't
377
+ // shown up by then isn't coming.
378
+ setTimeout(() => {
379
+ this._ignoredResponseIds.delete(cancelId)
380
+ }, DEFAULT_TIMEOUT_MS)
381
+ this._ws.send(JSON.stringify({
382
+ id: cancelId,
383
+ type: 'request.cancel',
384
+ params: { targetId: id },
385
+ }))
386
+ } catch (e) {
387
+ // Swallow — the user-visible failure mode is the
388
+ // AbortError below; a socket send failure here
389
+ // doesn't change client semantics.
390
+ }
391
+ }
392
+
393
+ reject(new DOMException('Aborted', 'AbortError'))
394
+ }
395
+ signal.addEventListener('abort', abortHandler, { once: true })
396
+ }
397
+
237
398
  if (this._ws && this._ws.readyState === 1 /* OPEN */) {
238
399
  this._ws.send(JSON.stringify(message))
239
400
  } else {
240
401
  this._pendingCalls.delete(id)
241
402
  clearTimeout(timer)
403
+ cleanup()
242
404
  reject(new RpcError(503, 'WebSocket not connected'))
243
405
  }
244
406
  })
@@ -284,6 +446,14 @@ export class ApiClient {
284
446
  }
285
447
  }
286
448
 
449
+ /** Register a callback that fires after a successful WebSocket reconnect.
450
+ * Does NOT fire on the initial connection — only on reconnects.
451
+ * Returns an unsubscribe function. */
452
+ onReconnect(callback: () => void): () => void {
453
+ this._reconnectCallbacks.add(callback)
454
+ return () => { this._reconnectCallbacks.delete(callback) }
455
+ }
456
+
287
457
  /** Close all open WebSocket connections and reject pending calls. */
288
458
  closeAll(): void {
289
459
  // Reject pending calls
@@ -294,5 +464,11 @@ export class ApiClient {
294
464
  this._pendingCalls.clear()
295
465
  this._closeWs()
296
466
  this._wsCallbacks.clear()
467
+ this._reconnectCallbacks.clear()
468
+ // Reset the first-connect gate so a reused client (closeAll() →
469
+ // later call()/subscribe() reopening via _ensureWs) does not fire
470
+ // freshly registered onReconnect callbacks on the initial open of
471
+ // the new connection — see the contract on onReconnect().
472
+ this._hasConnectedOnce = false
297
473
  }
298
474
  }
package/src/index.ts CHANGED
@@ -18,6 +18,8 @@ export * from "./perspectives/PerspectiveHandle";
18
18
  export * from "./perspectives/PerspectiveProxy";
19
19
  export * from "./perspectives/AutoProcessor";
20
20
  export * from "./perspectives/InterpretationModels";
21
+ export * from "./perspectives/FlowModels";
22
+ export * from "./perspectives/FlowInstance";
21
23
  export * from "./perspectives/SparqlBindings";
22
24
  export * from "./perspectives/WakerSubscriptionManager";
23
25
  export * from "./perspectives/PerspectiveDiff";
@@ -35,7 +37,7 @@ export * from "./ai/Tasks"
35
37
  export * from "./runtime/RuntimeTypes"
36
38
  export { Model as AIModel, ModelApi, TokenizerSource, LocalModel, ModelType, ModelApiInput, TokenizerSourceInput, LocalModelInput, ModelInput, VoiceActivityParamsInput } from "./ai/AITypes"
37
39
  export * from './shacl/SHACLShape'
38
- export { SHACLFlow, FlowState, FlowTransition, LinkPattern, FlowableCondition } from './shacl/SHACLFlow'
40
+ export { SHACLFlow, FlowState, FlowTransition, LinkPattern, ModelQuery, PropertyCondition, ConsensusRule } from './shacl/SHACLFlow'
39
41
  export * from './shacl/NodeExpression'
40
42
  export * from './shacl/builders'
41
43
  export { fileToDataUri } from './shacl/index'