websocket-ts 1.1.0 → 2.1.1

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 (76) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +211 -138
  3. package/package.json +46 -33
  4. package/src/backoff/backoff.ts +26 -18
  5. package/src/backoff/constantbackoff.ts +38 -20
  6. package/src/backoff/exponentialbackoff.ts +78 -38
  7. package/src/backoff/linearbackoff.ts +88 -37
  8. package/src/index.ts +23 -9
  9. package/src/queue/array_queue.ts +41 -0
  10. package/src/queue/queue.ts +46 -0
  11. package/src/queue/ring_queue.ts +69 -0
  12. package/src/websocket.ts +487 -162
  13. package/src/websocket_buffer.ts +18 -0
  14. package/src/websocket_builder.ts +274 -0
  15. package/src/websocket_event.ts +88 -0
  16. package/src/websocket_options.ts +23 -0
  17. package/src/websocket_retry_options.ts +22 -0
  18. package/{tsconfig.json → tsconfig.cjs.json} +71 -71
  19. package/tsconfig.esm.json +71 -0
  20. package/jest.config.js +0 -8
  21. package/lib/backoff/backoff.d.ts +0 -18
  22. package/lib/backoff/backoff.d.ts.map +0 -1
  23. package/lib/backoff/backoff.js +0 -3
  24. package/lib/backoff/backoff.js.map +0 -1
  25. package/lib/backoff/constantbackoff.d.ts +0 -11
  26. package/lib/backoff/constantbackoff.d.ts.map +0 -1
  27. package/lib/backoff/constantbackoff.js +0 -20
  28. package/lib/backoff/constantbackoff.js.map +0 -1
  29. package/lib/backoff/exponentialbackoff.d.ts +0 -22
  30. package/lib/backoff/exponentialbackoff.d.ts.map +0 -1
  31. package/lib/backoff/exponentialbackoff.js +0 -35
  32. package/lib/backoff/exponentialbackoff.js.map +0 -1
  33. package/lib/backoff/linearbackoff.d.ts +0 -19
  34. package/lib/backoff/linearbackoff.d.ts.map +0 -1
  35. package/lib/backoff/linearbackoff.js +0 -34
  36. package/lib/backoff/linearbackoff.js.map +0 -1
  37. package/lib/buffer/buffer.d.ts +0 -41
  38. package/lib/buffer/buffer.d.ts.map +0 -1
  39. package/lib/buffer/buffer.js +0 -3
  40. package/lib/buffer/buffer.js.map +0 -1
  41. package/lib/buffer/lrubuffer.d.ts +0 -24
  42. package/lib/buffer/lrubuffer.d.ts.map +0 -1
  43. package/lib/buffer/lrubuffer.js +0 -76
  44. package/lib/buffer/lrubuffer.js.map +0 -1
  45. package/lib/buffer/timebuffer.d.ts +0 -25
  46. package/lib/buffer/timebuffer.d.ts.map +0 -1
  47. package/lib/buffer/timebuffer.js +0 -92
  48. package/lib/buffer/timebuffer.js.map +0 -1
  49. package/lib/index.d.ts +0 -10
  50. package/lib/index.d.ts.map +0 -1
  51. package/lib/index.js +0 -22
  52. package/lib/index.js.map +0 -1
  53. package/lib/websocket.d.ts +0 -47
  54. package/lib/websocket.d.ts.map +0 -1
  55. package/lib/websocket.js +0 -120
  56. package/lib/websocket.js.map +0 -1
  57. package/lib/websocketBuilder.d.ts +0 -32
  58. package/lib/websocketBuilder.d.ts.map +0 -1
  59. package/lib/websocketBuilder.js +0 -68
  60. package/lib/websocketBuilder.js.map +0 -1
  61. package/lib/wsbuilder.d.ts +0 -29
  62. package/lib/wsbuilder.d.ts.map +0 -1
  63. package/lib/wsbuilder.js +0 -88
  64. package/lib/wsbuilder.js.map +0 -1
  65. package/src/buffer/buffer.ts +0 -45
  66. package/src/buffer/lrubuffer.ts +0 -80
  67. package/src/buffer/timebuffer.ts +0 -105
  68. package/src/websocketBuilder.ts +0 -98
  69. package/test/backoff/constantbackoff.test.ts +0 -21
  70. package/test/backoff/exponentialbackoff.test.ts +0 -13
  71. package/test/backoff/linearbackoff.test.ts +0 -32
  72. package/test/buffer/common.ts +0 -10
  73. package/test/buffer/lrubuffer.test.ts +0 -128
  74. package/test/buffer/timebuffer.test.ts +0 -115
  75. package/test/websocket.test.ts +0 -341
  76. package/test/websocketBuilder.test.ts +0 -36
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2020 J. Behrmann
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Joscha Behrmann
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,138 +1,211 @@
1
- # websocket-ts
2
- A client-websocket written in TypeScript meant to be used from within browsers with focus on simplicity, reliability and extensibility. It provides convenient features to automatically reconnect and buffer pending messages.
3
-
4
- [![Build Status](https://travis-ci.org/jjxxs/websocket-ts.svg?branch=master)](https://travis-ci.org/jjxxs/websocket-ts)
5
- [![Coverage Status](https://coveralls.io/repos/github/jjxxs/websocket-ts/badge.svg?branch=master)](https://coveralls.io/github/jjxxs/websocket-ts?branch=master)
6
- [![Release](https://img.shields.io/github/v/release/jjxxs/websocket-ts)](https://github.com/jjxxs/websocket-ts/releases/latest)
7
- [![License](https://img.shields.io/github/license/jjxxs/websocket-ts)](/LICENSE)
8
-
9
- ## Features
10
- - Dependency-free and small in size
11
- - Uses the browser-native WebSocket-functionality
12
- - Copies the event-based WebSocket-API
13
- - Provides access to the underlying WebSocket
14
- - When the connection is lost, it can optionally be configured to
15
- - Automatically try to reconnect in a smart way
16
- - Buffer messages that are sent when the connection is re-established
17
- - Builder-class for easy initialization and configuration
18
- - High test-coverage and in-code documentation
19
- - Enables you to easily modify and extend the code
20
-
21
- ## Installation
22
- In your project-root:
23
- ```
24
- $ npm install websocket-ts
25
- ```
26
-
27
- In your project-code:
28
- ```typescript
29
- import {WebsocketBuilder} from 'websocket-ts';
30
- ```
31
-
32
- ## Usage
33
-
34
- #### Initialization
35
- New instances are most easily created with the provided `WebsocketBuilder`:
36
-
37
- ```typescript
38
- const ws = new WebsocketBuilder('ws://localhost:42421').build();
39
- ```
40
-
41
- #### Events & Callbacks
42
- There are five events which can be subscribed to through callbacks:
43
- ```typescript
44
- export enum WebsocketEvents {
45
- open = 'open', // Connection is opened or re-opened
46
- close = 'close', // Connection is closed
47
- error = 'error', // An error occurred
48
- message = 'message', // A message was received
49
- retry = 'retry' // A try to re-connect is made
50
- }
51
- ```
52
- The callbacks are called with the issuing websocket-instance and the causing event as arguments:
53
- ```typescript
54
- const ws = new WebsocketBuilder('ws://localhost:42421')
55
- .onOpen((i, ev) => { console.log("opened") })
56
- .onClose((i, ev) => { console.log("closed") })
57
- .onError((i, ev) => { console.log("error") })
58
- .onMessage((i, ev) => { console.log("message") })
59
- .onRetry((i, ev) => { console.log("retry") })
60
- .build();
61
- ```
62
-
63
- You can register multiple callbacks for the same event. They will be called in stack-order:
64
- ```typescript
65
- const ws = new WebsocketBuilder('ws://localhost:42421')
66
- .onMessage((i, e) => { console.log("echo sent") })
67
- .onMessage((i, e) => { i.send(e.data) })
68
- .onMessage((i, e) => { console.log("message received") })
69
- .build();
70
- ```
71
-
72
- #### Send & buffer messages
73
- To send messages, use the websockets `send()`-method:
74
- ```typescript
75
- let ws: Websocket;
76
- /* ... */
77
- ws.send("Hello World!");
78
- ```
79
-
80
- If you want to buffer to-be-send messages while the websocket is disconnected, you can provide it with a `Buffer`.
81
- The websocket will then use the buffer to temporarily keep your messages and send them in correct order once the
82
- connection is re-established. There are currently two `Buffer`-implementations. You can also implement your own
83
- by inheriting from the `Buffer`-interface.
84
-
85
- ##### LRUBuffer
86
- The `LRUBuffer` keeps the last `n` messages. When the buffer is full, the oldest message in the buffer will be replaced.
87
- It uses an array as a circular-buffer for linear space- and time-requirements. To use the `LRUBuffer` with a capacity of `1000`:
88
- ```typescript
89
- const ws = new WebsocketBuilder('ws://localhost:42421')
90
- .withBuffer(new LRUBuffer(1000))
91
- .build();
92
- ```
93
-
94
- ##### TimeBuffer
95
- The `TimeBuffer` will keep all messages that were written within the last `n` milliseconds. It will drop messages that are
96
- older than the specified amount. To use the `TimeBuffer` that keeps messages from the last `5 minutes`:
97
- ```typescript
98
- const ws = new WebsocketBuilder('ws://localhost:42421')
99
- .withBuffer(new TimeBuffer(5 * 60 * 1000))
100
- .build();
101
- ```
102
-
103
- #### Reconnect & Backoff
104
- If you want the websocket to automatically try to re-connect when the connection is lost, you can provide it with a `Backoff`.
105
- The websocket will use the `Backoff` to determine how long it should wait between re-tries. There are currently three
106
- `Backoff`-implementations. You can also implement your own by inheriting from the `Backoff`-interface.
107
-
108
- ##### ConstantBackoff
109
- The `ConstantBackoff` will make the websocket wait a constant time between each connection retry. To use the `ConstantBackoff`
110
- with a wait-time of `1 second`:
111
- ```typescript
112
- const ws = new WebsocketBuilder('ws://localhost:42421')
113
- .withBackoff(new ConstantBackoff(500))
114
- .build();
115
- ```
116
-
117
- ##### LinearBackoff
118
- The `LinearBackoff` linearly increases the wait-time between connection-retries until an optional maximum is reached.
119
- To use the `LinearBackoff` to initially wait `0 seconds` and increase the wait-time by `1 second` with every retry until
120
- a maximum of `8 seconds` is reached:
121
- ```typescript
122
- const ws = new WebsocketBuilder('ws://localhost:42421')
123
- .withBackoff(new LinearBackoff(0, 1000, 8000))
124
- .build();
125
- ```
126
-
127
- ##### ExponentialBackoff
128
- The `ExponentialBackoff` doubles the backoff with every retry until a maximum is reached. This is modelled after the binary
129
- exponential-backoff algorithm used in computer-networking. To use the `ExponentialBackoff` that will produce the series
130
- `[100, 200, 400, 800, 1600, 3200, 6400]`:
131
- ```typescript
132
- const ws = new WebsocketBuilder('ws://localhost:42421')
133
- .withBackoff(new ExponentialBackoff(100, 7))
134
- .build();
135
- ```
136
-
137
- #### Build & Tests
138
- To build the project run `yarn build`. All provided components are covered with unit-tests. To run the tests run `yarn test`.
1
+ <div>
2
+ <div align="center">
3
+ <img src="https://raw.githubusercontent.com/jjxxs/websocket-ts/gh-pages/websocket-ts-logo.svg" alt="websocket-ts" width="300" height="65" />
4
+ </div>
5
+ <p align="center">
6
+ <img src="https://github.com/jjxxs/websocket-ts/actions/workflows/build.yml/badge.svg" alt="Build Status" />
7
+ <img src="https://github.com/jjxxs/websocket-ts/actions/workflows/test.yml/badge.svg" alt="Build Status" />
8
+ <a href="https://coveralls.io/github/jjxxs/websocket-ts?branch=master">
9
+ <img src="https://coveralls.io/repos/github/jjxxs/websocket-ts/badge.svg?branch=master&service=github" alt="Coverage Status" />
10
+ </a>
11
+ <a href="https://github.com/jjxxs/websocket-ts/releases/latest">
12
+ <img src="https://img.shields.io/github/v/release/jjxxs/websocket-ts" alt="Release" />
13
+ </a>
14
+ <a href="/LICENSE">
15
+ <img src="https://img.shields.io/github/license/jjxxs/websocket-ts" alt="License" />
16
+ </a>
17
+ </p>
18
+ </div>
19
+
20
+ <div align="center">
21
+ A <b>WebSocket</b> for browsers with <b>auto-reconnect</b> and <b>message buffering</b> written in <b>TypeScript</b>.
22
+ </div>
23
+
24
+ ## Features
25
+
26
+ - **Lightweight & Standalone**: No dependencies, 2.1 kB minified & gzipped.
27
+ - **Browser-native**: Utilizes WebSocket API, offers direct access.
28
+ - **Smart Reconnect**: Optional auto-reconnect and message buffering.
29
+ - **Easy Setup**: Optional builder class for quick initialization.
30
+ - **Well-Tested**: High test coverage, well-documented for extensibility.
31
+ - **Module Support**: Supports CommonJS, and ES6 modules.
32
+
33
+ ## Installation
34
+
35
+ Install `websocket-ts` with npm:
36
+
37
+ ```bash
38
+ $ npm install websocket-ts
39
+ ```
40
+
41
+ ## Quickstart
42
+ This example shows how to use the package, complete with message buffering and automatic reconnection.
43
+ The created websocket will echo back any received messages. It will buffer messages when disconnected
44
+ and attempt to reconnect every 1 second.
45
+
46
+ ```typescript
47
+ import {
48
+ ArrayQueue,
49
+ ConstantBackoff,
50
+ Websocket,
51
+ WebsocketBuilder,
52
+ WebsocketEvent,
53
+ } from "websocket-ts";
54
+
55
+ // Initialize WebSocket with buffering and 1s reconnection delay
56
+ const ws = new WebsocketBuilder("ws://localhost:8080")
57
+ .withBuffer(new ArrayQueue()) // buffer messages when disconnected
58
+ .withBackoff(new ConstantBackoff(1000)) // retry every 1s
59
+ .build();
60
+
61
+ // Function to output & echo received messages
62
+ const echoOnMessage = (i: Websocket, ev: MessageEvent) => {
63
+ console.log(`received message: ${ev.data}`);
64
+ i.send(`echo: ${ev.data}`);
65
+ };
66
+
67
+ // Add event listeners
68
+ ws.addEventListener(WebsocketEvent.open, () => console.log("opened!"));
69
+ ws.addEventListener(WebsocketEvent.close, () => console.log("closed!"));
70
+ ws.addEventListener(WebsocketEvent.message, echoOnMessage);
71
+ ```
72
+
73
+ ## Usage
74
+ This will demonstrate how to use `websocket-ts` in your project using the provided `WebsocketBuild`-class.
75
+
76
+ For a more detailed description of the API, please refer to the [API Documentation](https://jjxxs.github.io/websocket-ts/).
77
+
78
+ #### Initialization
79
+
80
+ Create a new instance with the `WebsocketBuilder`:
81
+
82
+ ```typescript
83
+ const ws = new WebsocketBuilder("ws://localhost:42421").build();
84
+ ```
85
+
86
+ #### Events
87
+
88
+ There are six events which can be subscribed to through with event listeners:
89
+
90
+ ```typescript
91
+ export enum WebsocketEvent {
92
+ open = "open", // Connection opened
93
+ close = "close", // Connection closed
94
+ error = "error", // Error-induced closure
95
+ message = "message", // Message received
96
+ retry = "retry", // Reconnect attempt
97
+ reconnect = "reconnect" // Successful reconnect
98
+ }
99
+ ```
100
+
101
+ #### Add Event Listeners
102
+ Event listeners receive the websocket instance (`i`) and the triggering event (`ev`) as arguments.
103
+
104
+ ```typescript
105
+ const ws = new WebsocketBuilder("ws://localhost:42421")
106
+ .onOpen((i, ev) => console.log("opened"))
107
+ .onClose((i, ev) => console.log("closed"))
108
+ .onError((i, ev) => console.log("error"))
109
+ .onMessage((i, ev) => console.log("message"))
110
+ .onRetry((i, ev) => console.log("retry"))
111
+ .onReconnect((i, ev) => console.log("reconnect"))
112
+ .build();
113
+ ```
114
+
115
+ #### Remove Event Listeners
116
+
117
+ To unregister a specific event listener, use `removeEventListener`:
118
+
119
+ ```typescript
120
+ let ws: Websocket
121
+ /* ... */
122
+ ws.removeEventListener(WebsocketEvent.open, openEventListener);
123
+ ```
124
+
125
+ #### Send Message
126
+
127
+ Use the `send` method to send a message to the server:
128
+
129
+ ```typescript
130
+ let ws: Websocket;
131
+ /* ... */
132
+ ws.send("Hello World!");
133
+ ```
134
+
135
+ #### Reconnect & Backoff (Optional)
136
+
137
+ If you'd like the websocket to automatically reconnect upon disconnection, you can optionally provide a `Backoff` strategy.
138
+ This sets the delay between reconnection attempts. There are three built-in `Backoff` implementations, or you can create
139
+ your own by implementing the `Backoff` interface. If no Backoff is provided, the websocket will not attempt to reconnect.
140
+
141
+ ##### ConstantBackoff
142
+
143
+ The `ConstantBackoff` strategy enforces a fixed delay between each reconnection attempt.
144
+ To set a constant 1-second wait time, use:
145
+
146
+ ```typescript
147
+ const ws = new WebsocketBuilder("ws://localhost:42421")
148
+ .withBackoff(new ConstantBackoff(1000)) // 1000ms = 1s
149
+ .build();
150
+ ```
151
+
152
+ ##### LinearBackoff
153
+
154
+ The `LinearBackoff` strategy increases the delay between reconnection attempts linearly,
155
+ up to an optional maximum. For example, to start with a 0-second delay and increase by
156
+ 10 second for each retry, capping at 60 seconds, use:
157
+
158
+ ```typescript
159
+ const ws = new WebsocketBuilder("ws://localhost:42421")
160
+ .withBackoff(new LinearBackoff(0, 10000, 60000)) // 0ms, 10s, 20s, 30s, 40s, 50s, 60s
161
+ .build();
162
+ ```
163
+
164
+ ##### ExponentialBackoff
165
+
166
+ The `ExponentialBackoff` strategy doubles the delay between each reconnection attempt, up
167
+ to a specified maximum. This approach is inspired by the binary exponential backoff algorithm
168
+ commonly used in networking. For example, to generate a backoff series like `[1s, 2s, 4s, 8s]`, use:
169
+
170
+ ```typescript
171
+ const ws = new WebsocketBuilder("ws://localhost:42421")
172
+ .withBackoff(new ExponentialBackoff(1000, 6)) // 1s, 2s, 4s, 8s, 16s, 32s, 64s
173
+ .build();
174
+ ```
175
+
176
+ #### Buffer (Optional)
177
+
178
+ To buffer outgoing messages when the websocket is disconnected, you can optionally specify
179
+ a `Queue`. This queue will temporarily store your messages and send them in sequence when
180
+ the websocket (re)connects. Two built-in `Queue` implementations are available, or you can
181
+ create your own by implementing the `Queue` interface. If no queue is provided, messages
182
+ won't be buffered.
183
+
184
+ ##### RingQueue
185
+
186
+ The `RingQueue` is a fixed-capacity, first-in-first-out (FIFO) queue. When it reaches capacity,
187
+ the oldest element is removed to accommodate new ones. Reading from the queue returns and
188
+ removes the oldest element. For instance, to set up a `RingQueue` with a 100-element capacity,
189
+ use:
190
+
191
+ ```typescript
192
+ const ws = new WebsocketBuilder("ws://localhost:42421")
193
+ .withBuffer(new RingQueue(100))
194
+ .build();
195
+ ```
196
+
197
+ ##### ArrayQueue
198
+
199
+ The ArrayQueue offers an unbounded capacity, functioning as a first-in-first-out (FIFO) queue.
200
+ Reading from this queue returns and removes the oldest element. To use an `ArrayQueue`, use:
201
+
202
+ ```typescript
203
+ const ws = new WebsocketBuilder("ws://localhost:42421")
204
+ .withBuffer(new ArrayQueue())
205
+ .build();
206
+ ```
207
+
208
+ ## Build & Tests
209
+
210
+ To compile the project, execute `npm run build`. The codebase includes unit tests for all
211
+ components. To run these tests, use `npm run test`.
package/package.json CHANGED
@@ -1,33 +1,46 @@
1
- {
2
- "name": "websocket-ts",
3
- "version": "1.1.0",
4
- "main": "lib/index.js",
5
- "types": "lib/",
6
- "license": "MIT",
7
- "keywords": [
8
- "websocket",
9
- "browser",
10
- "client",
11
- "typescript",
12
- "reconnecting",
13
- "buffered"
14
- ],
15
- "repository": {
16
- "url": "github:jjxxs/websocket-ts"
17
- },
18
- "scripts": {
19
- "build": "tsc -p .",
20
- "compile": "tsc",
21
- "test": "jest",
22
- "coveralls": "jest --coverage && cat ./coverage/lcov.info | coveralls"
23
- },
24
- "devDependencies": {
25
- "@types/jest": "^26.0.13",
26
- "@types/ws": "^7.2.6",
27
- "coveralls": "^3.1.0",
28
- "jest": "^26.4.2",
29
- "ts-jest": "^26.3.0",
30
- "typescript": "^4.0.2",
31
- "ws": "^7.3.1"
32
- }
33
- }
1
+ {
2
+ "name": "websocket-ts",
3
+ "version": "2.1.1",
4
+ "main": "dist/cjs/src/index.js",
5
+ "types": "dist/cjs/src/index.d.ts",
6
+ "module": "dist/esm/src/index.js",
7
+ "license": "MIT",
8
+ "keywords": [
9
+ "websocket",
10
+ "browser",
11
+ "client",
12
+ "typescript",
13
+ "reconnecting",
14
+ "buffered"
15
+ ],
16
+ "sideEffects": false,
17
+ "repository": {
18
+ "url": "github:jjxxs/websocket-ts"
19
+ },
20
+ "scripts": {
21
+ "build:cjs": "tsc -p tsconfig.cjs.json",
22
+ "build:esm": "tsc -p tsconfig.esm.json",
23
+ "build": "npm run build:cjs && npm run build:esm",
24
+ "test": "jest",
25
+ "test:coverage": "jest --coverage",
26
+ "coveralls": "cat ./coverage/lcov.info | coveralls",
27
+ "lint": "cross-env-shell eslint './src/{**/*,*}.{js,ts}' './tests/{**/*,*}.{js,ts}'"
28
+ },
29
+ "devDependencies": {
30
+ "@typescript-eslint/eslint-plugin": "^6.6.0",
31
+ "@typescript-eslint/parser": "^6.6.0",
32
+ "eslint-config-prettier": "^9.0.0",
33
+ "eslint-plugin-prettier": "^5.0.0",
34
+ "coveralls": "^3.1.1",
35
+ "eslint": "^8.49.0",
36
+ "@types/jest": "^29.5.4",
37
+ "jest": "^29.7.0",
38
+ "jest-environment-jsdom": "^29.7.0",
39
+ "ts-jest": "^29.1.1",
40
+ "ts-node": "^10.9.1",
41
+ "typescript": "^5.2.2",
42
+ "@types/ws": "^8.5.5",
43
+ "ws": "^7.0.0",
44
+ "cross-env": "^7.0.3"
45
+ }
46
+ }
@@ -1,18 +1,26 @@
1
- /**
2
- * Backoff provides a series of numbers. This series follows
3
- * a concrete pattern, e.g. be constant, linearly increasing,
4
- * exponentially increasing etc.
5
- */
6
- export interface Backoff {
7
- /**
8
- * Provides the callee with the next number in the
9
- * series.
10
- * @return the next number
11
- */
12
- next(): number
13
-
14
- /**
15
- * Resets the series to its starting-value.
16
- */
17
- reset(): void
18
- }
1
+ /**
2
+ * A Backoff produces a series of numbers that are used to determine
3
+ * the delay between connection-retries. Values are expected to be in milliseconds.
4
+ */
5
+ export interface Backoff {
6
+ /**
7
+ * The number of retries. Starts at 0, increases by 1 for each call to next(). Resets to 0 when reset() is called.
8
+ */
9
+ readonly retries: number;
10
+
11
+ /**
12
+ * Current number in the series.
13
+ */
14
+ readonly current: number;
15
+
16
+ /**
17
+ * Advances the series to the next number and returns it.
18
+ * @return the next number in the series
19
+ */
20
+ next(): number;
21
+
22
+ /**
23
+ * Resets the series to its initial state.
24
+ */
25
+ reset(): void;
26
+ }
@@ -1,20 +1,38 @@
1
- import {Backoff} from "./backoff";
2
-
3
- /**
4
- * ConstantBackoff always returns the same value.
5
- */
6
- export class ConstantBackoff implements Backoff {
7
- private readonly backoff: number;
8
-
9
- constructor(backoff: number) {
10
- this.backoff = backoff;
11
- }
12
-
13
- next(): number {
14
- return this.backoff;
15
- }
16
-
17
- reset = () => {
18
- // no-op
19
- }
20
- }
1
+ import { Backoff } from "./backoff";
2
+
3
+ /**
4
+ * ConstantBackoff always returns the same backoff-time.
5
+ */
6
+ export class ConstantBackoff implements Backoff {
7
+ private readonly backoff: number;
8
+ private _retries: number = 0;
9
+
10
+ /**
11
+ * Creates a new ConstantBackoff.
12
+ * @param backoff the backoff-time to return
13
+ */
14
+ constructor(backoff: number) {
15
+ if (!Number.isInteger(backoff) || backoff < 0) {
16
+ throw new Error("Backoff must be a positive integer");
17
+ }
18
+
19
+ this.backoff = backoff;
20
+ }
21
+
22
+ get retries(): number {
23
+ return this._retries;
24
+ }
25
+
26
+ get current(): number {
27
+ return this.backoff;
28
+ }
29
+
30
+ next(): number {
31
+ this._retries++;
32
+ return this.backoff;
33
+ }
34
+
35
+ reset(): void {
36
+ this._retries = 0;
37
+ }
38
+ }