mobility-toolbox-js 2.0.0 → 2.1.0

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 (271) hide show
  1. package/api/RealtimeAPI.d.ts +279 -0
  2. package/api/RealtimeAPI.d.ts.map +1 -0
  3. package/api/RealtimeAPI.js +466 -0
  4. package/api/RoutingAPI.d.ts +37 -0
  5. package/api/RoutingAPI.d.ts.map +1 -0
  6. package/api/RoutingAPI.js +35 -0
  7. package/api/StopsAPI.d.ts +38 -0
  8. package/api/StopsAPI.d.ts.map +1 -0
  9. package/api/StopsAPI.js +36 -0
  10. package/api/index.d.ts +4 -0
  11. package/api/index.d.ts.map +1 -0
  12. package/api/index.js +3 -3
  13. package/api/typedefs.d.ts +179 -0
  14. package/api/typedefs.d.ts.map +1 -0
  15. package/api/{tralis/typedefs.js → typedefs.js} +4 -10
  16. package/common/api/HttpAPI.d.ts +31 -0
  17. package/common/api/HttpAPI.d.ts.map +1 -0
  18. package/common/api/HttpAPI.js +57 -0
  19. package/common/api/WebSocketAPI.d.ts +153 -0
  20. package/common/api/WebSocketAPI.d.ts.map +1 -0
  21. package/common/api/WebSocketAPI.js +341 -0
  22. package/common/controls/ControlCommon.d.ts +76 -0
  23. package/common/controls/ControlCommon.d.ts.map +1 -0
  24. package/common/controls/ControlCommon.js +150 -0
  25. package/common/controls/CopyrightControlCommon.d.ts +13 -0
  26. package/common/controls/CopyrightControlCommon.d.ts.map +1 -0
  27. package/common/controls/CopyrightControlCommon.js +34 -0
  28. package/common/controls/StopFinderControlCommon.d.ts +55 -0
  29. package/common/controls/StopFinderControlCommon.d.ts.map +1 -0
  30. package/common/controls/StopFinderControlCommon.js +144 -0
  31. package/common/index.d.ts +3 -0
  32. package/common/index.d.ts.map +1 -0
  33. package/common/index.js +2 -0
  34. package/common/layers/LayerCommon.d.ts +94 -0
  35. package/common/layers/LayerCommon.d.ts.map +1 -0
  36. package/common/layers/LayerCommon.js +244 -0
  37. package/common/mixins/RealtimeLayerMixin.d.ts +286 -0
  38. package/common/mixins/RealtimeLayerMixin.d.ts.map +1 -0
  39. package/common/mixins/RealtimeLayerMixin.js +776 -0
  40. package/common/mixins/UserInteractionsLayerMixin.d.ts +60 -0
  41. package/common/mixins/UserInteractionsLayerMixin.d.ts.map +1 -0
  42. package/common/mixins/UserInteractionsLayerMixin.js +241 -0
  43. package/common/styles/index.d.ts +5 -0
  44. package/common/styles/index.d.ts.map +1 -0
  45. package/common/styles/index.js +4 -4
  46. package/common/styles/realtimeDefaultStyle.d.ts +36 -0
  47. package/common/styles/realtimeDefaultStyle.d.ts.map +1 -0
  48. package/common/styles/realtimeDefaultStyle.js +275 -0
  49. package/common/styles/{trackerDelayStyle.js → realtimeDelayStyle.d.ts} +4 -9
  50. package/common/styles/realtimeDelayStyle.d.ts.map +1 -0
  51. package/common/styles/realtimeDelayStyle.js +13 -0
  52. package/common/styles/realtimeHeadingStyle.d.ts +12 -0
  53. package/common/styles/realtimeHeadingStyle.d.ts.map +1 -0
  54. package/common/styles/realtimeHeadingStyle.js +85 -0
  55. package/common/styles/realtimeSimpleStyle.d.ts +4 -0
  56. package/common/styles/realtimeSimpleStyle.d.ts.map +1 -0
  57. package/common/styles/realtimeSimpleStyle.js +23 -0
  58. package/common/typedefs.d.ts +111 -0
  59. package/common/typedefs.d.ts.map +1 -0
  60. package/common/typedefs.js +35 -6
  61. package/common/utils/compareDepartures.d.ts +11 -0
  62. package/common/utils/compareDepartures.d.ts.map +1 -0
  63. package/common/utils/compareDepartures.js +35 -0
  64. package/common/utils/createCanvas.d.ts +10 -0
  65. package/common/utils/createCanvas.d.ts.map +1 -0
  66. package/common/utils/createCanvas.js +27 -0
  67. package/common/utils/createRealtimeFilters.d.ts +13 -0
  68. package/common/utils/createRealtimeFilters.d.ts.map +1 -0
  69. package/common/utils/createRealtimeFilters.js +74 -0
  70. package/common/utils/debounceDeparturesMessages.d.ts +12 -0
  71. package/common/utils/debounceDeparturesMessages.d.ts.map +1 -0
  72. package/common/utils/debounceDeparturesMessages.js +24 -0
  73. package/common/utils/debounceWebsocketMessages.d.ts +11 -0
  74. package/common/utils/debounceWebsocketMessages.d.ts.map +1 -0
  75. package/common/utils/debounceWebsocketMessages.js +29 -0
  76. package/common/utils/getLayersAsFlatArray.d.ts +3 -0
  77. package/common/utils/getLayersAsFlatArray.d.ts.map +1 -0
  78. package/common/utils/getLayersAsFlatArray.js +15 -0
  79. package/common/utils/getMapboxMapCopyrights.d.ts +18 -0
  80. package/common/utils/getMapboxMapCopyrights.d.ts.map +1 -0
  81. package/common/utils/getMapboxMapCopyrights.js +21 -23
  82. package/common/utils/getMapboxRender.d.ts +7 -0
  83. package/common/utils/getMapboxRender.d.ts.map +1 -0
  84. package/common/utils/getMapboxRender.js +87 -0
  85. package/common/utils/getMaplibreRender.d.ts +7 -0
  86. package/common/utils/getMaplibreRender.d.ts.map +1 -0
  87. package/common/utils/getMaplibreRender.js +38 -0
  88. package/common/utils/getRealtimeModeSuffix.d.ts +10 -0
  89. package/common/utils/getRealtimeModeSuffix.d.ts.map +1 -0
  90. package/common/utils/getRealtimeModeSuffix.js +7 -0
  91. package/common/utils/getUrlWithParams.d.ts +9 -0
  92. package/common/utils/getUrlWithParams.d.ts.map +1 -0
  93. package/common/utils/getUrlWithParams.js +18 -0
  94. package/common/utils/getVehiclePosition.d.ts +16 -0
  95. package/common/utils/getVehiclePosition.d.ts.map +1 -0
  96. package/common/utils/getVehiclePosition.js +60 -60
  97. package/common/utils/index.d.ts +17 -0
  98. package/common/utils/index.d.ts.map +1 -0
  99. package/common/utils/index.js +13 -2
  100. package/common/utils/realtimeConfig.d.ts +49 -0
  101. package/common/utils/realtimeConfig.d.ts.map +1 -0
  102. package/common/utils/realtimeConfig.js +173 -0
  103. package/common/utils/removeDuplicate.d.ts +10 -0
  104. package/common/utils/removeDuplicate.d.ts.map +1 -0
  105. package/common/utils/removeDuplicate.js +5 -12
  106. package/common/utils/renderTrajectories.d.ts +17 -0
  107. package/common/utils/renderTrajectories.d.ts.map +1 -0
  108. package/common/utils/renderTrajectories.js +110 -0
  109. package/common/utils/sortAndFilterDepartures.d.ts +16 -0
  110. package/common/utils/sortAndFilterDepartures.d.ts.map +1 -0
  111. package/common/utils/sortAndFilterDepartures.js +58 -0
  112. package/common/utils/sortByDelay.d.ts +3 -0
  113. package/common/utils/sortByDelay.d.ts.map +1 -0
  114. package/common/utils/sortByDelay.js +17 -20
  115. package/common/utils/timeUtils.d.ts +24 -0
  116. package/common/utils/timeUtils.d.ts.map +1 -0
  117. package/common/utils/timeUtils.js +13 -18
  118. package/iife.d.ts +3 -0
  119. package/iife.d.ts.map +1 -0
  120. package/iife.js +5 -0
  121. package/index.d.ts +10 -0
  122. package/index.d.ts.map +1 -0
  123. package/index.js +10 -2
  124. package/mapbox/controls/CopyrightControl.d.ts +29 -0
  125. package/mapbox/controls/CopyrightControl.d.ts.map +1 -0
  126. package/mapbox/controls/CopyrightControl.js +25 -35
  127. package/mapbox/controls/index.d.ts +2 -0
  128. package/mapbox/controls/index.d.ts.map +1 -0
  129. package/mapbox/controls/index.js +2 -0
  130. package/mapbox/index.d.ts +6 -0
  131. package/mapbox/index.d.ts.map +1 -0
  132. package/mapbox/index.js +5 -3
  133. package/mapbox/layers/Layer.d.ts +59 -0
  134. package/mapbox/layers/Layer.d.ts.map +1 -0
  135. package/mapbox/layers/Layer.js +78 -95
  136. package/mapbox/layers/RealtimeLayer.d.ts +181 -0
  137. package/mapbox/layers/RealtimeLayer.d.ts.map +1 -0
  138. package/mapbox/layers/RealtimeLayer.js +276 -0
  139. package/mapbox/layers/index.d.ts +3 -0
  140. package/mapbox/layers/index.d.ts.map +1 -0
  141. package/mapbox/layers/index.js +2 -0
  142. package/mapbox/utils/getMercatorResolution.d.ts +9 -0
  143. package/mapbox/utils/getMercatorResolution.d.ts.map +1 -0
  144. package/mapbox/utils/getMercatorResolution.js +18 -0
  145. package/mapbox/utils/getSourceCoordinates.d.ts +9 -0
  146. package/mapbox/utils/getSourceCoordinates.d.ts.map +1 -0
  147. package/mapbox/utils/getSourceCoordinates.js +27 -0
  148. package/mapbox/utils/index.d.ts +3 -0
  149. package/mapbox/utils/index.d.ts.map +1 -0
  150. package/mapbox/utils/index.js +2 -0
  151. package/mbt.js +60005 -0
  152. package/mbt.js.map +7 -0
  153. package/mbt.min.js +1084 -0
  154. package/mbt.min.js.map +7 -0
  155. package/ol/controls/CopyrightControl.d.ts +31 -0
  156. package/ol/controls/CopyrightControl.d.ts.map +1 -0
  157. package/ol/controls/CopyrightControl.js +44 -56
  158. package/ol/controls/RoutingControl.d.ts +193 -0
  159. package/ol/controls/RoutingControl.d.ts.map +1 -0
  160. package/ol/controls/RoutingControl.js +546 -667
  161. package/ol/controls/StopFinderControl.d.ts +30 -0
  162. package/ol/controls/StopFinderControl.d.ts.map +1 -0
  163. package/ol/controls/StopFinderControl.js +10 -16
  164. package/ol/controls/index.d.ts +4 -0
  165. package/ol/controls/index.d.ts.map +1 -0
  166. package/ol/controls/index.js +3 -0
  167. package/ol/index.d.ts +6 -0
  168. package/ol/index.d.ts.map +1 -0
  169. package/ol/index.js +4 -12
  170. package/ol/layers/Layer.d.ts +86 -0
  171. package/ol/layers/Layer.d.ts.map +1 -0
  172. package/ol/layers/Layer.js +147 -166
  173. package/ol/layers/MapGlLayer.d.ts +67 -0
  174. package/ol/layers/MapGlLayer.d.ts.map +1 -0
  175. package/ol/layers/MapGlLayer.js +218 -0
  176. package/ol/layers/MapboxLayer.d.ts +50 -0
  177. package/ol/layers/MapboxLayer.d.ts.map +1 -0
  178. package/ol/layers/MapboxLayer.js +79 -348
  179. package/ol/layers/MapboxStyleLayer.d.ts +129 -0
  180. package/ol/layers/MapboxStyleLayer.d.ts.map +1 -0
  181. package/ol/layers/MapboxStyleLayer.js +329 -368
  182. package/ol/layers/MaplibreLayer.d.ts +28 -0
  183. package/ol/layers/MaplibreLayer.d.ts.map +1 -0
  184. package/ol/layers/MaplibreLayer.js +13 -259
  185. package/ol/layers/RealtimeLayer.d.ts +202 -0
  186. package/ol/layers/RealtimeLayer.d.ts.map +1 -0
  187. package/ol/layers/RealtimeLayer.js +340 -0
  188. package/ol/layers/RoutingLayer.d.ts +34 -0
  189. package/ol/layers/RoutingLayer.d.ts.map +1 -0
  190. package/ol/layers/RoutingLayer.js +62 -68
  191. package/ol/layers/VectorLayer.d.ts +25 -0
  192. package/ol/layers/VectorLayer.d.ts.map +1 -0
  193. package/ol/layers/VectorLayer.js +27 -32
  194. package/ol/layers/WMSLayer.d.ts +42 -0
  195. package/ol/layers/WMSLayer.d.ts.map +1 -0
  196. package/ol/layers/WMSLayer.js +74 -66
  197. package/ol/layers/index.d.ts +9 -0
  198. package/ol/layers/index.d.ts.map +1 -0
  199. package/ol/layers/index.js +8 -0
  200. package/ol/styles/fullTrajectoryDelayStyle.d.ts +4 -0
  201. package/ol/styles/fullTrajectoryDelayStyle.d.ts.map +1 -0
  202. package/ol/styles/fullTrajectoryDelayStyle.js +23 -25
  203. package/ol/styles/fullTrajectoryStyle.d.ts +5 -0
  204. package/ol/styles/fullTrajectoryStyle.d.ts.map +1 -0
  205. package/ol/styles/fullTrajectoryStyle.js +37 -44
  206. package/ol/styles/index.d.ts +3 -0
  207. package/ol/styles/index.d.ts.map +1 -0
  208. package/package.json +98 -177
  209. package/setupTests.d.ts +2 -0
  210. package/setupTests.d.ts.map +1 -0
  211. package/setupTests.js +26 -0
  212. package/types/common.d.ts +122 -0
  213. package/types/index.d.ts +11 -0
  214. package/types/realtime.d.ts +320 -0
  215. package/types/routing.d.ts +206 -0
  216. package/types/stops.d.ts +143 -0
  217. package/README.md +0 -23
  218. package/api/routing/RoutingAPI.js +0 -44
  219. package/api/routing/RoutingAPI.test.js +0 -41
  220. package/api/stops/StopsAPI.js +0 -41
  221. package/api/stops/StopsAPI.test.js +0 -34
  222. package/api/tralis/TralisAPI.js +0 -731
  223. package/api/tralis/TralisAPI.test.js +0 -75
  224. package/api/tralis/TralisAPIUtils.js +0 -73
  225. package/api/tralis/WebSocketConnector.js +0 -338
  226. package/api/tralis/WebSocketConnector.test.js +0 -356
  227. package/common/Tracker.js +0 -197
  228. package/common/api/api.js +0 -64
  229. package/common/api/api.test.js +0 -68
  230. package/common/controls/Control.js +0 -146
  231. package/common/controls/Control.test.js +0 -98
  232. package/common/layers/Layer.js +0 -404
  233. package/common/layers/Layer.test.js +0 -585
  234. package/common/mixins/CopyrightMixin.js +0 -48
  235. package/common/mixins/SearchMixin.js +0 -176
  236. package/common/mixins/TralisLayerMixin.js +0 -930
  237. package/common/styles/trackerDefaultStyle.js +0 -333
  238. package/common/styles/trackerSimpleStyle.js +0 -22
  239. package/common/trackerConfig.js +0 -190
  240. package/common/trackerConfig.test.js +0 -25
  241. package/common/utils/createTrackerFilters.js +0 -87
  242. package/common/utils/createTrackerFilters.test.js +0 -95
  243. package/common/utils/getMapboxMapCopyrights.test.js +0 -47
  244. package/common/utils/getMapboxStyleUrl.js +0 -32
  245. package/common/utils/removeDuplicate.test.js +0 -22
  246. package/common/utils/timeUtils.test.js +0 -16
  247. package/index.js.map +0 -1
  248. package/mapbox/layers/Layer.test.js +0 -202
  249. package/mapbox/layers/TralisLayer.js +0 -329
  250. package/mapbox/layers/TralisLayer.test.js +0 -40
  251. package/mapbox/utils.js +0 -46
  252. package/module.js +0 -23
  253. package/ol/README.md +0 -0
  254. package/ol/controls/CopyrightControl.test.js +0 -211
  255. package/ol/controls/RoutingControl.test.js +0 -216
  256. package/ol/controls/StopFinderControl.test.js +0 -59
  257. package/ol/controls/snapshots/RoutingControlRouteGen10.json +0 -58
  258. package/ol/controls/snapshots/RoutingControlRouteGen100.json +0 -292
  259. package/ol/controls/snapshots/RoutingControlRouteGen30.json +0 -69
  260. package/ol/controls/snapshots/RoutingControlRouteGen5.json +0 -58
  261. package/ol/controls/snapshots/RoutingControlRouteOSM.json +0 -759
  262. package/ol/controls/snapshots/RoutingControlStation1.json +0 -60
  263. package/ol/controls/snapshots/RoutingControlStation2.json +0 -49
  264. package/ol/layers/Layer.test.js +0 -197
  265. package/ol/layers/MapboxLayer.test.js +0 -186
  266. package/ol/layers/MapboxStyleLayer.test.js +0 -262
  267. package/ol/layers/RoutingLayer.test.js +0 -49
  268. package/ol/layers/TralisLayer.js +0 -359
  269. package/ol/layers/TralisLayer.test.js +0 -97
  270. package/ol/layers/VectorLayer.test.js +0 -98
  271. package/ol/layers/WMSLayer.test.js +0 -84
@@ -1,75 +0,0 @@
1
- import { TralisAPI, TralisModes } from '..';
2
-
3
- describe('TralisAPI', () => {
4
- let tralisAPI;
5
- let get;
6
-
7
- beforeEach(() => {
8
- get = jest.fn((params, cb) => {
9
- cb({ content: 'content' });
10
- });
11
- tralisAPI = new TralisAPI();
12
- tralisAPI.conn = {
13
- get,
14
- };
15
- });
16
-
17
- describe('#getFullTrajectory() calls fullTrajectory channel', () => {
18
- test('without parameters', (done) => {
19
- tralisAPI.getFullTrajectory().then(() => {
20
- expect(get.mock.calls.length).toBe(1);
21
- expect(get.mock.calls[0][0]).toEqual({
22
- channel: 'full_trajectory',
23
- });
24
- done();
25
- });
26
- });
27
-
28
- [null, TralisModes.TOPOGRAPHIC].forEach((mode) => {
29
- describe(`using mode ${mode}`, () => {
30
- test('using id', (done) => {
31
- tralisAPI.getFullTrajectory('foo', mode).then(() => {
32
- expect(get.mock.calls.length).toBe(1);
33
- expect(get.mock.calls[0][0]).toEqual({
34
- channel: 'full_trajectory_foo',
35
- });
36
- done();
37
- });
38
- });
39
-
40
- test('using id and generalizationLevel param', (done) => {
41
- tralisAPI.getFullTrajectory('foo', mode, 5).then(() => {
42
- expect(get.mock.calls.length).toBe(1);
43
- expect(get.mock.calls[0][0]).toEqual({
44
- channel: 'full_trajectory_foo_gen5',
45
- });
46
- done();
47
- });
48
- });
49
- });
50
- });
51
-
52
- describe('using schematic mode ', () => {
53
- test('using id', (done) => {
54
- tralisAPI.getFullTrajectory('foo', TralisModes.SCHEMATIC).then(() => {
55
- expect(get.mock.calls.length).toBe(1);
56
- expect(get.mock.calls[0][0]).toEqual({
57
- channel: 'full_trajectory_schematic_foo',
58
- });
59
- done();
60
- });
61
- });
62
- test("doesn't use generalizationLevel param", (done) => {
63
- tralisAPI
64
- .getFullTrajectory('foo', TralisModes.SCHEMATIC, 10)
65
- .then(() => {
66
- expect(get.mock.calls.length).toBe(1);
67
- expect(get.mock.calls[0][0]).toEqual({
68
- channel: 'full_trajectory_schematic_foo',
69
- });
70
- done();
71
- });
72
- });
73
- });
74
- });
75
- });
@@ -1,73 +0,0 @@
1
- /**
2
- * Get the websocket channel suffix, depending on the current mode.
3
- * @param {String} mode Mode 'topographic' ou 'schematic'.
4
- * @private
5
- */
6
- export const getModeSuffix = (mode, modes) =>
7
- mode === modes.SCHEMATIC ? '_schematic' : '';
8
-
9
- /**
10
- * Compare two given departures for sort alogithm,
11
- * @param {Object} a First departure.
12
- * @param {Object} b Second departure.
13
- * @private
14
- */
15
- export const compareDepartures = (a, b, sortByMinArrivalTime = false) => {
16
- // First LEAVING and HIDDEN, then BOARDING and then sorted by time.
17
- const topStates = ['HIDDEN', 'LEAVING', 'BOARDING'];
18
- const aTop = a.has_fzo && topStates.indexOf(a.state) > -1;
19
- const bTop = b.has_fzo && topStates.indexOf(b.state) > -1;
20
-
21
- if (aTop || bTop) {
22
- if (aTop !== bTop) {
23
- return aTop ? -1 : 1;
24
- }
25
-
26
- if (a.state !== b.state) {
27
- // one is leaving
28
- return topStates.indexOf(a.state) - topStates.indexOf(b.state);
29
- }
30
- }
31
-
32
- let aDuration = null;
33
- let bDuration = null;
34
- const now = Date.now();
35
-
36
- if (sortByMinArrivalTime) {
37
- aDuration = new Date(a.min_arrival_time || a.time).getTime() - now;
38
- bDuration = new Date(b.min_arrival_time || b.time).getTime() - now;
39
- } else {
40
- aDuration = new Date(a.time).getTime() - now;
41
- bDuration = new Date(b.time).getTime() - now;
42
- }
43
-
44
- return aDuration - bDuration;
45
- };
46
-
47
- /**
48
- * Remove the delay from arrivalTime and departureTime
49
- * @private
50
- */
51
- export const cleanStopTime = (content) => {
52
- if (!content) {
53
- return;
54
- }
55
- content.stations.forEach((station) => {
56
- // eslint-disable-next-line no-param-reassign
57
- station.arrivalTimeWithDelay = station.arrivalTime;
58
- if (station.departureTime) {
59
- // eslint-disable-next-line no-param-reassign
60
- station.departureTimeWithDelay = station.departureTime;
61
- }
62
- if (station.arrivalDelay) {
63
- // eslint-disable-next-line no-param-reassign
64
- station.arrivalTime -= station.arrivalDelay;
65
- if (station.departureTime) {
66
- // eslint-disable-next-line no-param-reassign
67
- station.departureTime -= station.arrivalDelay;
68
- }
69
- }
70
- });
71
- // eslint-disable-next-line consistent-return
72
- return content;
73
- };
@@ -1,338 +0,0 @@
1
- /**
2
- * Class used to facilitate connection to a WebSocket and
3
- * also to manage properly messages send to the WebSocket.
4
- * This class must not contain any specific implementation.
5
- *
6
- * @private
7
- */
8
- class WebSocketConnector {
9
- constructor() {
10
- this.defineProperties();
11
- }
12
-
13
- defineProperties() {
14
- Object.defineProperties(this, {
15
- closed: {
16
- get: () =>
17
- !!(
18
- this.websocket &&
19
- this.websocket.readyState === this.websocket.CLOSED
20
- ),
21
- },
22
- closing: {
23
- get: () =>
24
- !!(
25
- this.websocket &&
26
- this.websocket.readyState === this.websocket.CLOSING
27
- ),
28
- },
29
- connecting: {
30
- get: () =>
31
- !!(
32
- this.websocket &&
33
- this.websocket.readyState === this.websocket.CONNECTING
34
- ),
35
- },
36
- open: {
37
- get: () =>
38
- !!(
39
- this.websocket && this.websocket.readyState === this.websocket.OPEN
40
- ),
41
- },
42
- /**
43
- * Array of message to send on open.
44
- * @type {Array<string>}
45
- * @private
46
- */
47
- messagesOnOpen: {
48
- value: [],
49
- writable: true,
50
- },
51
- /**
52
- * Array of subscriptions.
53
- * @type {Array<subscription>}
54
- * @private
55
- */
56
- subscriptions: {
57
- value: [],
58
- writable: true,
59
- },
60
-
61
- /**
62
- * List of channels subscribed.
63
- * @type {Array<subscription>}
64
- * @private
65
- */
66
- subscribed: {
67
- value: {},
68
- writable: true,
69
- },
70
- });
71
- }
72
-
73
- /**
74
- * Get the websocket request string.
75
- *
76
- * @param {string} method Request mehtod {GET, SUB}.
77
- * @param {Object} params Request parameters.
78
- * @param {string} params.channel Channel name
79
- * @param {string} [params.args] Request arguments
80
- * @param {Number} [params.id] Request identifier
81
- * @return {string} request string
82
- * @private
83
- */
84
- static getRequestString(method, params) {
85
- let reqStr = `${method} ${params.channel}`;
86
- reqStr += params.args ? ` ${params.args}` : '';
87
- reqStr += params.id ? ` ${params.id}` : '';
88
- return reqStr.trim();
89
- }
90
-
91
- /**
92
- * (Re)connect the websocket.
93
- *
94
- * @param {strin} url Websocket url.
95
- * @param {function} onOpen Callback called when the websocket connection is opened and before subscriptions of previous subscriptions.
96
- * @private
97
- */
98
- connect(url, onOpen = () => {}) {
99
- if (this.websocket && !this.closed) {
100
- this.websocket.close();
101
- }
102
-
103
- /** @ignore */
104
- this.websocket = new WebSocket(url);
105
-
106
- if (!this.open) {
107
- this.websocket.addEventListener('open', () => {
108
- onOpen();
109
- this.subscribePreviousSubscriptions();
110
- });
111
- } else {
112
- onOpen();
113
- this.subscribePreviousSubscriptions();
114
- }
115
- }
116
-
117
- /**
118
- * Close the websocket definitively.
119
- *
120
- * @private
121
- */
122
- close() {
123
- if (this.websocket) {
124
- this.websocket.onclose = null;
125
- this.websocket.close();
126
- this.websocket = null;
127
- this.messagesOnOpen = [];
128
- }
129
- }
130
-
131
- /**
132
- * Sends a message to the websocket.
133
- *
134
- * @param {message} message Message to send.
135
- * @private
136
- */
137
- send(message) {
138
- if (!this.websocket) {
139
- return;
140
- }
141
- const send = () => {
142
- this.websocket.send(message);
143
- };
144
- if (!this.open) {
145
- // This 'if' avoid sending 2 identical BBOX message on open,
146
- if (!this.messagesOnOpen.includes(message)) {
147
- this.messagesOnOpen.push(message);
148
- this.websocket.addEventListener('open', () => {
149
- this.messagesOnOpen = [];
150
- send();
151
- });
152
- this.websocket.addEventListener('close', () => {
153
- this.messagesOnOpen = [];
154
- });
155
- }
156
- } else if (!this.messagesOnOpen.includes(message)) {
157
- send();
158
- }
159
- }
160
-
161
- /**
162
- * Listen to websocket messages.
163
- *
164
- * @param {Object} params Parameters for the websocket get request
165
- * @param {function} cb callback on listen
166
- * @param {function} errorCb Callback on error
167
- * @return {{onMessage: function, errorCb: function}} Object with onMessage and error callbacks
168
- * @private
169
- */
170
- listen(params, cb, errorCb) {
171
- // Remove the previous identical callback
172
- this.unlisten(params, cb);
173
-
174
- const onMessage = (evt) => {
175
- let data = {};
176
- try {
177
- data = JSON.parse(evt.data);
178
- } catch (err) {
179
- // eslint-disable-next-line no-console
180
- console.error('WebSocket: unable to parse JSON data', err, evt.data);
181
- }
182
- let source = params.channel;
183
- source += params.args ? ` ${params.args}` : '';
184
-
185
- // Buffer channel message return a list of other channels to propagate to proper callbacks.
186
- const contents = data.source === 'buffer' ? data.content : [data];
187
- contents.forEach((content) => {
188
- // Because of backend optimization, the last content is null.
189
- if (
190
- content?.source === source &&
191
- (!params.id || params.id === data.client_reference)
192
- ) {
193
- cb(content);
194
- }
195
- });
196
- };
197
-
198
- if (this.websocket) {
199
- this.websocket.addEventListener('message', onMessage);
200
-
201
- if (errorCb) {
202
- this.websocket.addEventListener('error', errorCb);
203
- this.websocket.addEventListener('close', errorCb);
204
- }
205
- }
206
-
207
- return { onMessageCb: onMessage, onErrorCb: errorCb };
208
- }
209
-
210
- /**
211
- * Unlisten websocket messages.
212
- *
213
- * @param {Object} params Parameters for the websocket get request.
214
- * @param {function} cb Callback used when listen.
215
- * @private
216
- */
217
- unlisten(params, cb) {
218
- if (!this.websocket) {
219
- return;
220
- }
221
- this.subscriptions
222
- .filter(
223
- (s) => s.params.channel === params.channel && (!cb || s.cb === cb),
224
- )
225
- .forEach(({ onMessageCb, onErrorCb }) => {
226
- if (this.websocket) {
227
- this.websocket.removeEventListener('message', onMessageCb);
228
- if (onErrorCb) {
229
- this.websocket.removeEventListener('error', onErrorCb);
230
- this.websocket.removeEventListener('close', onErrorCb);
231
- }
232
- }
233
- });
234
- }
235
-
236
- /**
237
- * Sends a get request to the websocket.
238
- *
239
- * @param {Object} params Parameters for the websocket get request
240
- * @param {function} cb callback on listen
241
- * @param {function} errorCb Callback on error
242
- * @private
243
- */
244
- get(params, cb, errorCb) {
245
- const reqStr = WebSocketConnector.getRequestString('GET', params);
246
- this.send(reqStr);
247
- this.listen(params, cb, errorCb);
248
- }
249
-
250
- /**
251
- * Subscribe to a given channel.
252
- *
253
- * @param {Object} params Parameters for the websocket get request
254
- * @param {function} cb callback on listen
255
- * @param {function} errorCb Callback on error
256
- * @param {boolean} quiet if false, no GET or SUB requests are send, only the callback is registered.
257
- * @private
258
- */
259
- subscribe(params, cb, errorCb, quiet = false) {
260
- const { onMessageCb, onErrorCb } = this.listen(params, cb, errorCb);
261
- const reqStr = WebSocketConnector.getRequestString('', params);
262
-
263
- const index = this.subscriptions.findIndex(
264
- (subcr) => params.channel === subcr.params.channel && cb === subcr.cb,
265
- );
266
- const newSubscr = { params, cb, errorCb, onMessageCb, onErrorCb, quiet };
267
- if (index > -1) {
268
- this.subscriptions[index] = newSubscr;
269
- } else {
270
- this.subscriptions.push(newSubscr);
271
- }
272
-
273
- if (!this.subscribed[reqStr]) {
274
- if (!newSubscr.quiet) {
275
- this.send(`GET ${reqStr}`);
276
- this.send(`SUB ${reqStr}`);
277
- }
278
- this.subscribed[reqStr] = true;
279
- }
280
- }
281
-
282
- /**
283
- * Unsubscribe from a channel.
284
- * @param {string} source source to unsubscribe from
285
- * @param {function} cb Callback function to unsubscribe. If null all subscriptions for the channel will be unsubscribed.
286
- * @private
287
- */
288
- unsubscribe(source, cb) {
289
- const toRemove = this.subscriptions.filter(
290
- (s) => s.params.channel === source && (!cb || s.cb === cb),
291
- );
292
-
293
- toRemove.forEach(({ onMessageCb, onErrorCb }) => {
294
- if (this.websocket) {
295
- this.websocket.removeEventListener('message', onMessageCb);
296
- if (onErrorCb) {
297
- this.websocket.removeEventListener('error', onErrorCb);
298
- this.websocket.removeEventListener('close', onErrorCb);
299
- }
300
- }
301
- });
302
-
303
- this.subscriptions = this.subscriptions.filter(
304
- (s) => s.params.channel !== source || (cb && s.cb !== cb),
305
- );
306
-
307
- // If there is no more subscriptions to this channel, and the removed subscriptions didn't register quietly,
308
- // we DEL it.
309
- if (
310
- source &&
311
- this.subscribed[source] &&
312
- !this.subscriptions.find((s) => s.params.channel === source) &&
313
- toRemove.find((subscr) => !subscr.quiet)
314
- ) {
315
- this.send(`DEL ${source}`);
316
- this.subscribed[source] = false;
317
- }
318
- }
319
-
320
- /**
321
- * After an auto reconnection we need to re-subscribe to the channels.
322
- */
323
- subscribePreviousSubscriptions() {
324
- // Before to subscribe previous subscriptions we make sure they
325
- // are all defined as unsubscribed, because this code is asynchrone
326
- // and a subscription could have been added in between.
327
- Object.keys(this.subscribed).forEach((key) => {
328
- this.subscribed[key] = false;
329
- });
330
-
331
- // Subscribe all previous subscriptions.
332
- [...this.subscriptions].forEach((s) => {
333
- this.subscribe(s.params, s.cb, s.errorCb, s.quiet);
334
- });
335
- }
336
- }
337
-
338
- export default WebSocketConnector;