@coasys/ad4m 0.13.1-staging.6 → 0.13.1-staging.8

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 (174) hide show
  1. package/lib/index.cjs +1130 -650
  2. package/lib/index.js +1130 -651
  3. package/lib/src/Ad4mClient.d.ts +3 -0
  4. package/lib/src/Ad4mClient.js +9 -2
  5. package/lib/src/agent/Agent.d.ts +5 -1
  6. package/lib/src/agent/Agent.js +3 -0
  7. package/lib/src/agent/AgentClient.d.ts +3 -0
  8. package/lib/src/agent/AgentClient.js +3 -0
  9. package/lib/src/agent/AgentStatus.d.ts +2 -0
  10. package/lib/src/agent/AgentStatus.js +2 -0
  11. package/lib/src/apiClient.d.ts +41 -0
  12. package/lib/src/apiClient.js +138 -1
  13. package/lib/src/generated/api/AgentStatus.d.ts +5 -0
  14. package/lib/src/generated/api/AgentWithIdentity.d.ts +14 -0
  15. package/lib/src/generated/api/AgentWithIdentity.js +1 -0
  16. package/lib/src/generated/api/BotView.d.ts +7 -0
  17. package/lib/src/generated/api/BotView.js +2 -0
  18. package/lib/src/generated/api/ClaimOfferParams.d.ts +13 -0
  19. package/lib/src/generated/api/ClaimOfferParams.js +2 -0
  20. package/lib/src/generated/api/ClaimOfferResult.d.ts +14 -0
  21. package/lib/src/generated/api/ClaimOfferResult.js +1 -0
  22. package/lib/src/generated/api/ClaimView.d.ts +11 -0
  23. package/lib/src/generated/api/ClaimView.js +2 -0
  24. package/lib/src/generated/api/CosignInceptParams.d.ts +10 -0
  25. package/lib/src/generated/api/CosignInceptParams.js +1 -0
  26. package/lib/src/generated/api/DeviceView.d.ts +17 -0
  27. package/lib/src/generated/api/DeviceView.js +1 -0
  28. package/lib/src/generated/api/DidBotScope.d.ts +7 -0
  29. package/lib/src/generated/api/DidBotScope.js +2 -0
  30. package/lib/src/generated/api/DidDocument.d.ts +16 -0
  31. package/lib/src/generated/api/DidDocument.js +1 -0
  32. package/lib/src/generated/api/DidDocumentMetadata.d.ts +18 -0
  33. package/lib/src/generated/api/DidDocumentMetadata.js +2 -0
  34. package/lib/src/generated/api/DidResolutionMetadata.d.ts +51 -0
  35. package/lib/src/generated/api/DidResolutionMetadata.js +1 -0
  36. package/lib/src/generated/api/DidResolutionResult.d.ts +16 -0
  37. package/lib/src/generated/api/DidResolutionResult.js +1 -0
  38. package/lib/src/generated/api/DidVerificationMethod.d.ts +17 -0
  39. package/lib/src/generated/api/DidVerificationMethod.js +1 -0
  40. package/lib/src/generated/api/Events.d.ts +2 -0
  41. package/lib/src/generated/api/ForkRecord.d.ts +11 -0
  42. package/lib/src/generated/api/ForkRecord.js +2 -0
  43. package/lib/src/generated/api/IdentityForkEvent.d.ts +10 -0
  44. package/lib/src/generated/api/IdentityForkEvent.js +2 -0
  45. package/lib/src/generated/api/IdentityLog.d.ts +18 -0
  46. package/lib/src/generated/api/IdentityLog.js +1 -0
  47. package/lib/src/generated/api/IdentityStatus.d.ts +48 -0
  48. package/lib/src/generated/api/IdentityStatus.js +1 -0
  49. package/lib/src/generated/api/JoinStatus.d.ts +10 -0
  50. package/lib/src/generated/api/JoinStatus.js +2 -0
  51. package/lib/src/generated/api/JoinStatusParams.d.ts +6 -0
  52. package/lib/src/generated/api/JoinStatusParams.js +2 -0
  53. package/lib/src/generated/api/LogParams.d.ts +17 -0
  54. package/lib/src/generated/api/LogParams.js +2 -0
  55. package/lib/src/generated/api/Offer.d.ts +14 -0
  56. package/lib/src/generated/api/Offer.js +1 -0
  57. package/lib/src/generated/api/OfferKind.d.ts +4 -0
  58. package/lib/src/generated/api/OfferKind.js +2 -0
  59. package/lib/src/generated/api/OfferListing.d.ts +9 -0
  60. package/lib/src/generated/api/OfferListing.js +1 -0
  61. package/lib/src/generated/api/OfferOpened.d.ts +6 -0
  62. package/lib/src/generated/api/OfferOpened.js +2 -0
  63. package/lib/src/generated/api/OfferState.d.ts +21 -0
  64. package/lib/src/generated/api/OfferState.js +1 -0
  65. package/lib/src/generated/api/OffersParams.d.ts +11 -0
  66. package/lib/src/generated/api/OffersParams.js +1 -0
  67. package/lib/src/generated/api/OpenOfferParams.d.ts +7 -0
  68. package/lib/src/generated/api/OpenOfferParams.js +1 -0
  69. package/lib/src/generated/api/PublishParams.d.ts +11 -0
  70. package/lib/src/generated/api/PublishParams.js +1 -0
  71. package/lib/src/generated/api/RequestBody.d.ts +15 -0
  72. package/lib/src/generated/api/RequestBody.js +2 -0
  73. package/lib/src/generated/api/ResetLogParams.d.ts +9 -0
  74. package/lib/src/generated/api/ResetLogParams.js +2 -0
  75. package/lib/src/generated/api/ResolveParams.d.ts +18 -0
  76. package/lib/src/generated/api/ResolveParams.js +2 -0
  77. package/lib/src/generated/api/RpcMethods.d.ts +68 -1
  78. package/lib/src/generated/api/RpcMethods.js +6 -0
  79. package/lib/src/generated/api/SignedBy.d.ts +8 -0
  80. package/lib/src/generated/api/SignedBy.js +2 -0
  81. package/lib/src/generated/api/SignedHead.d.ts +14 -0
  82. package/lib/src/generated/api/SignedHead.js +2 -0
  83. package/lib/src/generated/api/SignedOffer.d.ts +10 -0
  84. package/lib/src/generated/api/SignedOffer.js +1 -0
  85. package/lib/src/generated/api/SignedRequest.d.ts +8 -0
  86. package/lib/src/generated/api/SignedRequest.js +1 -0
  87. package/lib/src/generated/api/SkippedSource.d.ts +7 -0
  88. package/lib/src/generated/api/SkippedSource.js +2 -0
  89. package/lib/src/generated/api/StoreBehind.d.ts +13 -0
  90. package/lib/src/generated/api/StoreBehind.js +2 -0
  91. package/lib/src/generated/api/StoreInfo.d.ts +15 -0
  92. package/lib/src/generated/api/StoreInfo.js +2 -0
  93. package/lib/src/generated/api/index.d.ts +38 -0
  94. package/lib/src/identity/IdentityClient.d.ts +70 -0
  95. package/lib/src/identity/IdentityClient.js +97 -0
  96. package/lib/src/index.d.ts +1 -0
  97. package/lib/src/index.js +1 -0
  98. package/lib/src/model/Ad4mModel.d.ts +4 -0
  99. package/lib/src/model/Ad4mModel.js +12 -1
  100. package/lib/src/neighbourhood/MeshManager.d.ts +24 -0
  101. package/lib/src/neighbourhood/MeshManager.js +42 -1
  102. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +10 -0
  103. package/lib/src/neighbourhood/NeighbourhoodClient.js +16 -0
  104. package/lib/src/neighbourhood/Session.js +2 -0
  105. package/lib/src/neighbourhood/SfuManager.d.ts +30 -3
  106. package/lib/src/neighbourhood/SfuManager.js +78 -41
  107. package/lib/src/perspectives/FlowInstance.js +6 -4
  108. package/lib/src/shacl/SHACLFlow.d.ts +5 -3
  109. package/lib/src/shacl/SHACLFlow.js +121 -5
  110. package/package.json +2 -2
  111. package/src/Ad4mClient.test.ts +64 -4
  112. package/src/Ad4mClient.ts +8 -0
  113. package/src/agent/Agent.ts +9 -1
  114. package/src/agent/AgentClient.ts +5 -1
  115. package/src/agent/AgentStatus.ts +4 -0
  116. package/src/apiClient.test.ts +302 -0
  117. package/src/apiClient.ts +136 -1
  118. package/src/generated/api/AgentStatus.ts +6 -1
  119. package/src/generated/api/AgentWithIdentity.ts +12 -0
  120. package/src/generated/api/BotView.ts +6 -0
  121. package/src/generated/api/ClaimOfferParams.ts +14 -0
  122. package/src/generated/api/ClaimOfferResult.ts +11 -0
  123. package/src/generated/api/ClaimView.ts +6 -0
  124. package/src/generated/api/CosignInceptParams.ts +11 -0
  125. package/src/generated/api/DeviceView.ts +12 -0
  126. package/src/generated/api/DidBotScope.ts +6 -0
  127. package/src/generated/api/DidDocument.ts +8 -0
  128. package/src/generated/api/DidDocumentMetadata.ts +19 -0
  129. package/src/generated/api/DidResolutionMetadata.ts +52 -0
  130. package/src/generated/api/DidResolutionResult.ts +13 -0
  131. package/src/generated/api/DidVerificationMethod.ts +15 -0
  132. package/src/generated/api/Events.ts +2 -0
  133. package/src/generated/api/ForkRecord.ts +9 -0
  134. package/src/generated/api/IdentityForkEvent.ts +7 -0
  135. package/src/generated/api/IdentityLog.ts +17 -0
  136. package/src/generated/api/IdentityStatus.ts +49 -0
  137. package/src/generated/api/JoinStatus.ts +7 -0
  138. package/src/generated/api/JoinStatusParams.ts +6 -0
  139. package/src/generated/api/LogParams.ts +18 -0
  140. package/src/generated/api/Offer.ts +8 -0
  141. package/src/generated/api/OfferKind.ts +6 -0
  142. package/src/generated/api/OfferListing.ts +8 -0
  143. package/src/generated/api/OfferOpened.ts +6 -0
  144. package/src/generated/api/OfferState.ts +7 -0
  145. package/src/generated/api/OffersParams.ts +11 -0
  146. package/src/generated/api/OpenOfferParams.ts +7 -0
  147. package/src/generated/api/PublishParams.ts +12 -0
  148. package/src/generated/api/RequestBody.ts +7 -0
  149. package/src/generated/api/ResetLogParams.ts +10 -0
  150. package/src/generated/api/ResolveParams.ts +19 -0
  151. package/src/generated/api/RpcMethods.ts +38 -1
  152. package/src/generated/api/SignedBy.ts +6 -0
  153. package/src/generated/api/SignedHead.ts +10 -0
  154. package/src/generated/api/SignedOffer.ts +8 -0
  155. package/src/generated/api/SignedRequest.ts +7 -0
  156. package/src/generated/api/SkippedSource.ts +6 -0
  157. package/src/generated/api/StoreBehind.ts +14 -0
  158. package/src/generated/api/StoreInfo.ts +16 -0
  159. package/src/generated/api/index.ts +39 -0
  160. package/src/identity/IdentityClient.ts +111 -0
  161. package/src/index.ts +1 -0
  162. package/src/model/Ad4mModel.ts +11 -1
  163. package/src/model/write-round-trips.test.ts +111 -2
  164. package/src/neighbourhood/MeshManager.test.ts +87 -0
  165. package/src/neighbourhood/MeshManager.ts +50 -1
  166. package/src/neighbourhood/NeighbourhoodClient.test.ts +27 -0
  167. package/src/neighbourhood/NeighbourhoodClient.ts +19 -0
  168. package/src/neighbourhood/Session.test.ts +5 -0
  169. package/src/neighbourhood/Session.ts +2 -0
  170. package/src/neighbourhood/SfuManager.test.ts +293 -0
  171. package/src/neighbourhood/SfuManager.ts +92 -45
  172. package/src/perspectives/FlowInstance.ts +6 -4
  173. package/src/shacl/SHACLFlow.test.ts +221 -0
  174. package/src/shacl/SHACLFlow.ts +121 -5
@@ -505,6 +505,290 @@ describe('ApiClient notices a socket that went silent', () => {
505
505
  })
506
506
  })
507
507
 
508
+ describe('ApiClient checkConnection', () => {
509
+ // A network switch the platform says nothing about (no `online`): the
510
+ // socket stays OPEN and silent. Something else noticed (ICE went
511
+ // disconnected) and asks the client to check its socket now.
512
+ beforeEach(() => {
513
+ TestSocket.autoOpen = false
514
+ TestSocket.closeHangs = true
515
+ TestSocket.answersPings = false
516
+ jest.useFakeTimers()
517
+ })
518
+ afterEach(() => jest.useRealTimers())
519
+
520
+ const pings = (i: number) => socket(i).sent.filter(m => m.type === 'ping').length
521
+
522
+ it('pings at once; a socket silent for the deadline is dropped, the next dialled at once, and onNetworkChange fires when it opens', async () => {
523
+ const changed = jest.fn()
524
+ client.onNetworkChange(changed)
525
+ open()
526
+ socket(0).open()
527
+ const read = call<string[]>('perspective.all', {}, { timeoutMs: 120_000 })
528
+
529
+ client.checkConnection()
530
+ expect(pings(0)).toBe(1)
531
+ await jest.advanceTimersByTimeAsync(1_999)
532
+ expect(TestSocket.instances).toHaveLength(1)
533
+ expect(socket(0).readyState).toBe(1)
534
+
535
+ await jest.advanceTimersByTimeAsync(1)
536
+ // No backoff: the next socket is dialled now.
537
+ expect(socket(0).readyState).toBe(2)
538
+ expect(TestSocket.instances).toHaveLength(2)
539
+ expect(changed).not.toHaveBeenCalled()
540
+
541
+ socket(1).open()
542
+ expect(changed).toHaveBeenCalledTimes(1)
543
+ const sent = socket(1).sent.map(m => m.type)
544
+ expect(sent[0]).toBe('events.watch')
545
+ expect(sent).toContain('perspective.all')
546
+ socket(1).reply({ id: socket(1).sent.find(m => m.type === 'perspective.all')!.id, result: ['p'] })
547
+ await expect(read).resolves.toEqual(['p'])
548
+ })
549
+
550
+ it('gives the probe\'s pong time to come back after a large write sent before it could have crossed', async () => {
551
+ // The write could have crossed at about 37.5 s; the pong comes back 100 ms later.
552
+ open()
553
+ socket(0).open()
554
+ const write = outcomeOf(call('perspective.addLink', { uuid: 'u', blob: 'x'.repeat(600_000) }, { timeoutMs: 120_000 }))
555
+ await jest.advanceTimersByTimeAsync(1_000)
556
+ client.checkConnection()
557
+ await jest.advanceTimersByTimeAsync(36_600)
558
+ expect(socket(0).readyState).toBe(1)
559
+ socket(0).reply({ type: 'pong' })
560
+ await jest.advanceTimersByTimeAsync(5_000)
561
+ expect(socket(0).readyState).toBe(1)
562
+ expect(write()).toBe('pending')
563
+ })
564
+
565
+ it('keeps a socket that answers the ping', async () => {
566
+ TestSocket.answersPings = true
567
+ const changed = jest.fn()
568
+ client.onNetworkChange(changed)
569
+ open()
570
+ socket(0).open()
571
+ client.checkConnection()
572
+ await jest.advanceTimersByTimeAsync(5_000)
573
+ expect(TestSocket.instances).toHaveLength(1)
574
+ expect(socket(0).readyState).toBe(1)
575
+ expect(changed).not.toHaveBeenCalled()
576
+ })
577
+
578
+ it('keeps a socket that sends anything else within the deadline', async () => {
579
+ open()
580
+ socket(0).open()
581
+ client.checkConnection(3_000)
582
+ await jest.advanceTimersByTimeAsync(2_500)
583
+ socket(0).reply({ type: 'agent-updated' })
584
+ await jest.advanceTimersByTimeAsync(5_000)
585
+ expect(TestSocket.instances).toHaveLength(1)
586
+ expect(socket(0).readyState).toBe(1)
587
+ })
588
+
589
+ it('sends one probe for several calls while one is pending', async () => {
590
+ const changed = jest.fn()
591
+ client.onNetworkChange(changed)
592
+ open()
593
+ socket(0).open()
594
+ client.checkConnection()
595
+ await jest.advanceTimersByTimeAsync(500)
596
+ client.checkConnection()
597
+ client.checkConnection()
598
+ expect(pings(0)).toBe(1)
599
+ await jest.advanceTimersByTimeAsync(1_500)
600
+ expect(TestSocket.instances).toHaveLength(2)
601
+ socket(1).open()
602
+ expect(changed).toHaveBeenCalledTimes(1)
603
+ await jest.advanceTimersByTimeAsync(10_000)
604
+ expect(TestSocket.instances).toHaveLength(2)
605
+ })
606
+
607
+ it('a probe answered after the periodic ping fell due is not dropped by that ping', async () => {
608
+ open()
609
+ socket(0).open()
610
+ // The periodic ping is due at 10 s; the probe starts just before it.
611
+ await jest.advanceTimersByTimeAsync(9_500)
612
+ client.checkConnection()
613
+ await jest.advanceTimersByTimeAsync(1_000)
614
+ socket(0).reply({ type: 'pong' })
615
+ expect(TestSocket.instances).toHaveLength(1)
616
+ expect(socket(0).readyState).toBe(1)
617
+ // The periodic deadline still runs after the probe.
618
+ socket(0).reply({ type: 'pong' })
619
+ await jest.advanceTimersByTimeAsync(30_000)
620
+ expect(socket(0).readyState).toBe(2)
621
+ })
622
+
623
+ it('does nothing without an open socket', async () => {
624
+ client.checkConnection()
625
+ expect(TestSocket.instances).toHaveLength(0)
626
+ open()
627
+ client.checkConnection()
628
+ await jest.advanceTimersByTimeAsync(5_000)
629
+ expect(TestSocket.instances).toHaveLength(1)
630
+ expect(socket(0).sent).toEqual([])
631
+ })
632
+
633
+ it('leaves no timers after closeAll during a probe', async () => {
634
+ const promise = call('agent.status')
635
+ socket(0).open()
636
+ socket(0).reply({ id: socket(0).sent[0].id, result: 1 })
637
+ await promise
638
+ client.checkConnection()
639
+ expect(pings(0)).toBe(1)
640
+ client.closeAll()
641
+ expect(jest.getTimerCount()).toBe(0)
642
+ })
643
+ })
644
+
645
+ describe('ApiClient on a network change', () => {
646
+ // A browser says the network changed with `online` on the window and
647
+ // `change` on `navigator.connection` (Chromium). Node has neither, so the
648
+ // tests install both, then take them away again.
649
+ let window: EventTarget
650
+ let connection: EventTarget
651
+ const navigatorBefore = Object.getOwnPropertyDescriptor(globalThis, 'navigator')
652
+ const g = globalThis as unknown as Record<string, unknown>
653
+
654
+ beforeEach(() => {
655
+ window = new EventTarget()
656
+ connection = new EventTarget()
657
+ g.addEventListener = window.addEventListener.bind(window)
658
+ g.removeEventListener = window.removeEventListener.bind(window)
659
+ Object.defineProperty(globalThis, 'navigator', { value: { connection }, configurable: true })
660
+ // The old socket's close event never comes, as on a dead network.
661
+ TestSocket.autoOpen = false
662
+ TestSocket.closeHangs = true
663
+ TestSocket.answersPings = false
664
+ jest.useFakeTimers()
665
+ })
666
+ afterEach(() => {
667
+ jest.useRealTimers()
668
+ delete g.addEventListener
669
+ delete g.removeEventListener
670
+ if (navigatorBefore) Object.defineProperty(globalThis, 'navigator', navigatorBefore)
671
+ })
672
+
673
+ const online = () => window.dispatchEvent(new Event('online'))
674
+
675
+ it('redials at once on "online": a sent write fails, a sent read is resent, and onNetworkChange fires once the new socket opens', async () => {
676
+ const changed = jest.fn()
677
+ client.onNetworkChange(changed)
678
+ open()
679
+ socket(0).open()
680
+ const write = outcomeOf(call('perspective.addLink', { uuid: 'u' }, { timeoutMs: 120_000 }))
681
+ const read = call<string[]>('perspective.all', {}, { timeoutMs: 120_000 })
682
+
683
+ online()
684
+ // No ping deadline and no backoff: the next socket is dialled now.
685
+ expect(socket(0).readyState).toBe(2)
686
+ expect(TestSocket.instances).toHaveLength(2)
687
+ await jest.advanceTimersByTimeAsync(0)
688
+ expect(write()).toMatchObject({ name: 'RpcError', status: 503 })
689
+ expect(changed).not.toHaveBeenCalled()
690
+
691
+ socket(1).open()
692
+ expect(changed).toHaveBeenCalledTimes(1)
693
+ const sent = socket(1).sent.map(m => m.type)
694
+ expect(sent[0]).toBe('events.watch')
695
+ expect(sent).toContain('perspective.all')
696
+ socket(1).reply({ id: socket(1).sent.find(m => m.type === 'perspective.all')!.id, result: ['p'] })
697
+ await expect(read).resolves.toEqual(['p'])
698
+ })
699
+
700
+ it('checks the socket on a change of navigator.connection: one that answers stays, as on a bandwidth estimate update', () => {
701
+ const changed = jest.fn()
702
+ client.onNetworkChange(changed)
703
+ open()
704
+ socket(0).open()
705
+
706
+ connection.dispatchEvent(new Event('change'))
707
+ expect(socket(0).sent.at(-1)?.type).toBe('ping')
708
+ socket(0).reply({ type: 'pong' })
709
+ jest.advanceTimersByTime(5_000)
710
+ expect(socket(0).readyState).toBe(1)
711
+ expect(TestSocket.instances).toHaveLength(1)
712
+ expect(changed).not.toHaveBeenCalled()
713
+ })
714
+
715
+ it('redials on a change of navigator.connection when the socket stays silent', () => {
716
+ const changed = jest.fn()
717
+ client.onNetworkChange(changed)
718
+ open()
719
+ socket(0).open()
720
+
721
+ connection.dispatchEvent(new Event('change'))
722
+ connection.dispatchEvent(new Event('change'))
723
+ expect(TestSocket.instances).toHaveLength(1)
724
+ jest.advanceTimersByTime(2_000)
725
+ expect(TestSocket.instances).toHaveLength(2)
726
+ socket(1).open()
727
+ expect(changed).toHaveBeenCalledTimes(1)
728
+ })
729
+
730
+ it('dials once for a burst of change events while the new socket connects', () => {
731
+ const changed = jest.fn()
732
+ client.onNetworkChange(changed)
733
+ open()
734
+ socket(0).open()
735
+
736
+ online()
737
+ connection.dispatchEvent(new Event('change'))
738
+ online()
739
+ expect(TestSocket.instances).toHaveLength(2)
740
+ socket(1).open()
741
+ expect(changed).toHaveBeenCalledTimes(1)
742
+ })
743
+
744
+ it('skips the reconnect backoff when the change comes while waiting to redial', async () => {
745
+ open()
746
+ socket(0).open()
747
+ socket(0).drop()
748
+ jest.advanceTimersByTime(500)
749
+ socket(1).drop()
750
+ // Backing off for 1 s now; the network change cuts it short.
751
+ expect(TestSocket.instances).toHaveLength(2)
752
+ online()
753
+ expect(TestSocket.instances).toHaveLength(3)
754
+ })
755
+
756
+ it('fires onNetworkChange at once when no socket is wanted', () => {
757
+ const changed = jest.fn()
758
+ client.onNetworkChange(changed)
759
+ online()
760
+ expect(TestSocket.instances).toHaveLength(0)
761
+ expect(changed).toHaveBeenCalledTimes(1)
762
+ })
763
+
764
+ it('stops listening once unsubscribed, and after closeAll', () => {
765
+ const changed = jest.fn()
766
+ const unsubscribe = client.onNetworkChange(changed)
767
+ open()
768
+ socket(0).open()
769
+ unsubscribe()
770
+ online()
771
+ socket(1).open()
772
+ expect(changed).not.toHaveBeenCalled()
773
+
774
+ client.closeAll()
775
+ online()
776
+ connection.dispatchEvent(new Event('change'))
777
+ jest.advanceTimersByTime(60_000)
778
+ expect(TestSocket.instances).toHaveLength(2)
779
+ })
780
+
781
+ it('works without a global event target or navigator.connection, as in Node', () => {
782
+ delete g.addEventListener
783
+ delete g.removeEventListener
784
+ Object.defineProperty(globalThis, 'navigator', { value: {}, configurable: true })
785
+ open()
786
+ socket(0).open()
787
+ expect(socket(0).sent.map(m => m.type)).toEqual(['events.watch'])
788
+ client.closeAll()
789
+ })
790
+ })
791
+
508
792
  describe('ApiClient.onReconnect', () => {
509
793
  beforeEach(() => { TestSocket.autoOpen = false })
510
794
 
@@ -773,6 +1057,24 @@ describe('ApiClient.reconnectNow', () => {
773
1057
  expect(win.live + doc.live).toBe(0)
774
1058
  })
775
1059
 
1060
+ it('dials once on `online` during the wait, though the network-change listener hears it too', () => {
1061
+ // In a browser `window` is the global object, so both listeners get the event.
1062
+ g.addEventListener = win.addEventListener.bind(win)
1063
+ g.removeEventListener = win.removeEventListener.bind(win)
1064
+ try {
1065
+ open()
1066
+ socket(0).open()
1067
+ socket(0).drop() // waiting to reconnect
1068
+ win.dispatchEvent(new Event('online'))
1069
+ expect(TestSocket.instances).toHaveLength(2)
1070
+ expect(socket(1).readyState).toBe(0)
1071
+ } finally {
1072
+ client.closeAll()
1073
+ delete g.addEventListener
1074
+ delete g.removeEventListener
1075
+ }
1076
+ })
1077
+
776
1078
  it('stops listening when the last subscriber leaves during the wait', () => {
777
1079
  const unsubscribe = client.on('perspective-added', () => {})
778
1080
  socket(0).open()
package/src/apiClient.ts CHANGED
@@ -79,6 +79,13 @@ const SLOWEST_LINK_BYTES_PER_MS = 16 // 16 kB/s
79
79
  * frame adds before a ping on an idle socket never cost a ping interval. */
80
80
  const PONG_RETURN_MS = 5_000
81
81
 
82
+ /** How long `checkConnection` waits for the open socket to say anything
83
+ * after its ping. If a large write sent before it may still be on the way,
84
+ * the wait lasts until that write could have crossed, as for the periodic
85
+ * ping, and half of this more for the pong. On a working path the pong is
86
+ * one round trip away. */
87
+ const CHECK_CONNECTION_DEADLINE_MS = 2_000
88
+
82
89
  /** The bytes `text` takes as UTF-8, as a WebSocket text frame sends it. */
83
90
  function utf8Length(text: string): number {
84
91
  let bytes = text.length
@@ -172,6 +179,8 @@ export class ApiClient {
172
179
  * A message from the socket does not move it back: hearing from the executor says nothing
173
180
  * about how much of a large upload has reached it. */
174
181
  private _wsSentBy = 0
182
+ /** A `checkConnection` probe waiting for the open socket to say anything; null when none. */
183
+ private _wsProbeTimer: ReturnType<typeof setTimeout> | null = null
175
184
  // The executor sends a socket only the events it asked for (`events.watch`).
176
185
  // What the executor has for the open socket, as sent; a new socket has `{}`.
177
186
  private _watching: string | null = '{}'
@@ -181,6 +190,13 @@ export class ApiClient {
181
190
  private _watchSent: Promise<void> = Promise.resolve()
182
191
  private _watchRetries = 0
183
192
  private _watchRetryTimer: ReturnType<typeof setTimeout> | null = null
193
+ private _networkCallbacks = new Set<() => void>()
194
+ /** Removes the network-change listeners; null while not listening. */
195
+ private _unlistenNetwork: (() => void) | null = null
196
+ /** A network change waits for its socket to open, then tells `onNetworkChange`. */
197
+ private _networkChanged = false
198
+ /** The socket dialled for the last network change. */
199
+ private _networkDial: WebSocket | null = null
184
200
 
185
201
  private _getWsUrl(): string {
186
202
  const wsBase = this.baseUrl
@@ -193,6 +209,7 @@ export class ApiClient {
193
209
  private _ensureWs(): void {
194
210
  if (this._ws) return
195
211
  if (this._authFailed !== null) throw new RpcError(401, this._authFailed)
212
+ this._listenForNetworkChanges()
196
213
  // A dial ends any wait for one: a call or subscriber that dials during the backoff
197
214
  // leaves no timer behind to swallow the retry after this socket's own drop.
198
215
  this._cancelReconnect()
@@ -220,7 +237,10 @@ export class ApiClient {
220
237
  this._wsOpen.catch(() => {})
221
238
 
222
239
  ws.onmessage = (event) => {
223
- if (this._ws === ws) this._wsPingedAt = null
240
+ if (this._ws === ws) {
241
+ this._wsPingedAt = null
242
+ this._endProbe()
243
+ }
224
244
  let parsed: Record<string, unknown>
225
245
  try { parsed = JSON.parse(event.data) } catch (e) {
226
246
  console.error('Error parsing WebSocket data:', e)
@@ -282,6 +302,68 @@ export class ApiClient {
282
302
  }
283
303
  }
284
304
  this._hasConnectedOnce = true
305
+ if (this._networkChanged) {
306
+ this._networkChanged = false
307
+ this._notifyNetworkChange()
308
+ }
309
+ }
310
+
311
+ /**
312
+ * Hear of network changes where the platform says so: `online` on the
313
+ * global object (browsers, Deno) redials at once, and `change` on
314
+ * `navigator.connection` (Chromium) runs `checkConnection`. Elsewhere,
315
+ * e.g. Node, nothing is heard and the ping deadline notices a dead
316
+ * socket on its own.
317
+ */
318
+ private _listenForNetworkChanges(): void {
319
+ if (this._unlistenNetwork) return
320
+ const handler = () => this._onNetworkChange()
321
+ const removers: (() => void)[] = []
322
+ const target = globalThis as unknown as Partial<EventTarget>
323
+ if (typeof target.addEventListener === 'function') {
324
+ target.addEventListener('online', handler)
325
+ removers.push(() => target.removeEventListener?.('online', handler))
326
+ }
327
+ const connection = (globalThis as { navigator?: { connection?: Partial<EventTarget> } }).navigator?.connection
328
+ if (typeof connection?.addEventListener === 'function') {
329
+ // `change` also fires when Chromium's downlink or rtt estimate
330
+ // moves, as a busy call makes it do: probe rather than drop.
331
+ const probe = () => this.checkConnection()
332
+ connection.addEventListener('change', probe)
333
+ removers.push(() => connection.removeEventListener?.('change', probe))
334
+ }
335
+ this._unlistenNetwork = () => { for (const remove of removers) remove() }
336
+ }
337
+
338
+ /**
339
+ * The network changed: the open socket most likely runs over a path that
340
+ * is gone, and nothing would say so before the ping deadline. Drop it as
341
+ * a silent socket is dropped and dial the next one now, without backoff.
342
+ * `onNetworkChange` callbacks fire once that socket opens.
343
+ */
344
+ private _onNetworkChange(): void {
345
+ if (this._authFailed !== null) return
346
+ const ws = this._ws
347
+ // A socket dialled for an earlier change is on the new network already.
348
+ if (ws && ws === this._networkDial && ws.readyState === 0 /* CONNECTING */) return
349
+ if (ws) {
350
+ console.info('Network changed; reconnecting the WebSocket')
351
+ this._onClose(ws)
352
+ ws.close()
353
+ }
354
+ this._cancelReconnect()
355
+ this._wsReconnectDelay = INITIAL_RECONNECT_DELAY_MS
356
+ if (this._handlers.size === 0 && this._pendingCalls.size === 0) {
357
+ this._notifyNetworkChange()
358
+ return
359
+ }
360
+ this._networkChanged = true
361
+ this._ensureWs()
362
+ this._networkDial = this._ws
363
+ }
364
+
365
+ private _notifyNetworkChange(): void {
366
+ for (const cb of [...this._networkCallbacks]) callSafely(cb, 'Error in network-change callback:')
285
367
  }
286
368
 
287
369
  /** `reason` is set when the executor asked to try again later; calls that fail carry it. */
@@ -320,6 +402,8 @@ export class ApiClient {
320
402
  this._wsSentBy = 0
321
403
  this._wsPingTimer = setInterval(() => {
322
404
  if (this._ws !== ws) return
405
+ // A probe has its own, shorter deadline and decides for this ping.
406
+ if (this._wsProbeTimer) return
323
407
  const ping = JSON.stringify({ type: 'ping' })
324
408
  if (this._wsPingedAt === null) {
325
409
  this._wsPingedAt = performance.now()
@@ -355,6 +439,14 @@ export class ApiClient {
355
439
  clearInterval(this._wsPingTimer)
356
440
  this._wsPingTimer = null
357
441
  }
442
+ this._endProbe()
443
+ }
444
+
445
+ private _endProbe(): void {
446
+ if (this._wsProbeTimer) {
447
+ clearTimeout(this._wsProbeTimer)
448
+ this._wsProbeTimer = null
449
+ }
358
450
  }
359
451
 
360
452
  private _scheduleReconnect(): void {
@@ -617,6 +709,44 @@ export class ApiClient {
617
709
  return () => { this._reconnectCallbacks.delete(callback) }
618
710
  }
619
711
 
712
+ /** Register a callback that fires after the network changed (`online`,
713
+ * or a socket that failed `checkConnection`), once the socket dialled for the
714
+ * new network is open and its event watch sent. Calls made from it go
715
+ * out on that socket. Returns an unsubscribe function. */
716
+ onNetworkChange(callback: () => void): () => void {
717
+ this._networkCallbacks.add(callback)
718
+ this._listenForNetworkChanges()
719
+ return () => { this._networkCallbacks.delete(callback) }
720
+ }
721
+
722
+ /**
723
+ * Check the open socket now rather than at the next ping: send a ping,
724
+ * and if nothing at all arrives on that socket within `deadlineMs`,
725
+ * treat it as a network change (drop it, dial the next one at once,
726
+ * `onNetworkChange` callbacks fire when it opens). Any message keeps it.
727
+ * For a caller that has seen its network path break, e.g. ICE going
728
+ * disconnected, where the platform fired no `online` event. Without an
729
+ * open socket, or while a check runs, this does nothing.
730
+ */
731
+ checkConnection(deadlineMs = CHECK_CONNECTION_DEADLINE_MS): void {
732
+ const ws = this._ws
733
+ if (!ws || ws.readyState !== 1 /* OPEN */ || this._wsProbeTimer) return
734
+ const first = this._wsPingedAt === null
735
+ if (first) this._wsPingedAt = performance.now()
736
+ this._send(ws, JSON.stringify({ type: 'ping' }))
737
+ if (first) this._wsPingArrivesBy = this._wsSentBy
738
+ // Any message from the socket ends the probe (`onmessage` → `_endProbe`).
739
+ // The ping reaches the executor only after what was sent before it,
740
+ // and its pong gets half the deadline to come back after that.
741
+ const wait = Math.max(deadlineMs, this._wsSentBy - performance.now() + deadlineMs / 2)
742
+ this._wsProbeTimer = setTimeout(() => {
743
+ this._wsProbeTimer = null
744
+ if (this._ws !== ws) return
745
+ console.warn(`WebSocket silent for ${wait} ms after a check; reconnecting`)
746
+ this._onNetworkChange()
747
+ }, wait)
748
+ }
749
+
620
750
  /** Register a callback that fires once when the executor refuses this
621
751
  * client's token: a 401 reply, or a socket closed with code 1008. Every
622
752
  * call then fails with a 401 `RpcError` and the client does not reconnect;
@@ -635,6 +765,11 @@ export class ApiClient {
635
765
  this._handlers.clear()
636
766
  this._reconnectCallbacks.clear()
637
767
  this._authFailedCallbacks.clear()
768
+ this._networkCallbacks.clear()
769
+ this._unlistenNetwork?.()
770
+ this._unlistenNetwork = null
771
+ this._networkChanged = false
772
+ this._networkDial = null
638
773
  // A reused client must not fire onReconnect on its next first open.
639
774
  this._hasConnectedOnce = false
640
775
  }
@@ -1,4 +1,9 @@
1
1
  // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
2
  import type { JsonValue } from "./serde_json/JsonValue";
3
3
 
4
- export type AgentStatus = { did: string | null, didDocument: JsonValue | null, error: string | null, isInitialized: boolean, isUnlocked: boolean, };
4
+ export type AgentStatus = { did: string | null, didDocument: JsonValue | null, error: string | null, isInitialized: boolean, isUnlocked: boolean,
5
+ /**
6
+ * The `did:scid` the agent's device key speaks for, or `null`. `did` stays the device
7
+ * `did:key`, so links and profiles keep the author they had.
8
+ */
9
+ identity: string | null, };
@@ -0,0 +1,12 @@
1
+ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
+ import type { DecoratedPerspective } from "./DecoratedPerspective";
3
+
4
+ /**
5
+ * `agent.get`: the agent's profile, and the identity its device key speaks for (`did`
6
+ * stays the device `did:key`).
7
+ */
8
+ export type AgentWithIdentity = {
9
+ /**
10
+ * The `did:scid` this agent speaks for, or `null`.
11
+ */
12
+ identity: string | null, did: string, directMessageLanguage: string | null, perspective: DecoratedPerspective | null, };
@@ -0,0 +1,6 @@
1
+ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
+
3
+ /**
4
+ * A bot key's scope.
5
+ */
6
+ export type BotView = { can: Array<string>, expires: number, };
@@ -0,0 +1,14 @@
1
+ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
+
3
+ /**
4
+ * `identity.claimOffer` params.
5
+ */
6
+ export type ClaimOfferParams = {
7
+ /**
8
+ * The offer string (`coasys:offer:1:…`) or the offer link (`https://id.coasys.org/o#…`).
9
+ */
10
+ offer: string,
11
+ /**
12
+ * A name for this device the holder sees on the confirm card (at most 64 characters).
13
+ */
14
+ hint?: string, };
@@ -0,0 +1,11 @@
1
+ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
+ import type { OfferKind } from "./OfferKind";
3
+
4
+ /**
5
+ * `identity.claimOffer`: the claim is made; the holder confirms with the same match code.
6
+ */
7
+ export type ClaimOfferResult = { did: string, offerId: string,
8
+ /**
9
+ * "R7K Q2M": the holder shows the same code.
10
+ */
11
+ matchCode: string, kind: OfferKind, expires: number, };
@@ -0,0 +1,6 @@
1
+ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
+
3
+ /**
4
+ * What the holder sees of a claim; the secret is gone.
5
+ */
6
+ export type ClaimView = { deviceKey: string, encKey: string, canKeepMaster: boolean, hint: string | null, coSig: string, claimedAt: number, };
@@ -0,0 +1,11 @@
1
+ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
+ import type { JsonValue } from "./serde_json/JsonValue";
3
+
4
+ /**
5
+ * `identity.cosignIncept` params.
6
+ */
7
+ export type CosignInceptParams = {
8
+ /**
9
+ * An `incept` that lists this agent's device key, with the master's proof.
10
+ */
11
+ event: JsonValue, };
@@ -0,0 +1,12 @@
1
+ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
+ import type { BotView } from "./BotView";
3
+
4
+ /**
5
+ * One device key of the identity, from its log. Names, places and the master-key holders
6
+ * will come from the private record, which the executor does not have yet.
7
+ */
8
+ export type DeviceView = { keyId: string, sign: string, bot: BotView | null, expires: number | null, addedSeq: number, revokedSeq: number | null,
9
+ /**
10
+ * The key is this agent's device key.
11
+ */
12
+ thisDevice: boolean, };
@@ -0,0 +1,6 @@
1
+ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
+
3
+ /**
4
+ * `coasys:bot`: what a bot key may do, until when.
5
+ */
6
+ export type DidBotScope = { can: Array<string>, expires: number, };
@@ -0,0 +1,8 @@
1
+ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
+ import type { DidVerificationMethod } from "./DidVerificationMethod";
3
+
4
+ /**
5
+ * The JSON-LD of a `did:scid:coasys:1` DID document (the TypeScript contract of
6
+ * `DidResolutionResult.didDocument`; the executor passes on the core's own JSON).
7
+ */
8
+ export type DidDocument = { "@context": Array<string>, id: string, controller: string, verificationMethod: Array<DidVerificationMethod>, authentication: Array<string>, assertionMethod: Array<string>, keyAgreement: Array<string>, capabilityInvocation: Array<string>, alsoKnownAs?: Array<string>, };
@@ -0,0 +1,19 @@
1
+ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
+
3
+ /**
4
+ * DID document metadata: seqs as decimal strings (DID Core makes them strings). Empty on an
5
+ * error.
6
+ */
7
+ export type DidDocumentMetadata = {
8
+ /**
9
+ * The seq whose state the document shows.
10
+ */
11
+ versionId?: string,
12
+ /**
13
+ * The seq after it, when the log holds one.
14
+ */
15
+ nextVersionId?: string,
16
+ /**
17
+ * The log has ended (whatever the version).
18
+ */
19
+ deactivated?: boolean, };