|
1 | | -import type { GreatWebSocketEventMap } from "./events"; |
| 1 | +import type { WebSocketEventMap } from "./events"; |
2 | 2 | import type { PendingCommand } from "./internal"; |
3 | | -import { AlwaysConnected } from "./keep-online"; |
4 | 3 | import { ConnectionState, type heartbeatFn } from "./models"; |
5 | 4 | import type { RemoteCommand } from "./rpc"; |
6 | | -import { createWebSocket, type Operator } from "./websocket-factory"; |
7 | | - |
8 | | -export class GreatWebSocket implements Operator { |
9 | | - #ws: AlwaysConnected | null = null; |
| 5 | +import { WsConnectionMonitor, type WsConnectionOptions } from "./state-machine"; |
| 6 | +import { |
| 7 | + type ConnectionLifecycleHandler, |
| 8 | + createDefaultWebSocket, |
| 9 | +} from "./websocket-factory"; |
| 10 | + |
| 11 | +export const DEFAULT_CONNECTION_OPTIONS = { |
| 12 | + heartbeatInterval: 15000, |
| 13 | + reconnectDelay: 2000, |
| 14 | + connectionTimeout: 15000, |
| 15 | +} as const satisfies WsConnectionOptions; |
| 16 | + |
| 17 | +export class GreatWebSocket implements ConnectionLifecycleHandler { |
| 18 | + #ws: WsConnectionMonitor | null = null; |
10 | 19 | #pendingCommands: PendingCommand[] = []; |
11 | 20 |
|
12 | 21 | constructor( |
13 | 22 | url: string, |
14 | 23 | private readonly onConnectedFn: () => Promise<boolean>, |
15 | 24 | private readonly onMessageFn: (ws: WebSocket, ev: MessageEvent) => void, |
16 | 25 | private readonly sendHeartbeat: heartbeatFn, |
| 26 | + private readonly options: WsConnectionOptions = DEFAULT_CONNECTION_OPTIONS, |
17 | 27 | ) { |
18 | | - this.#ws = new AlwaysConnected( |
| 28 | + this.#ws = new WsConnectionMonitor( |
19 | 29 | () => |
20 | | - createWebSocket( |
| 30 | + createDefaultWebSocket( |
21 | 31 | url, |
22 | 32 | this, |
23 | 33 | this.onMessageFn as (ws: unknown, ev: MessageEvent) => void, |
24 | 34 | ), |
25 | 35 | this.onConnectedFn, |
26 | 36 | this.sendHeartbeat, |
27 | | - { |
28 | | - heartbeatInterval: 15000, |
29 | | - reconnectDelay: 2000, |
30 | | - connectionTimeout: 15000, |
31 | | - }, |
| 37 | + this.options, |
32 | 38 | ); |
33 | 39 | } |
34 | 40 |
|
@@ -76,15 +82,15 @@ export class GreatWebSocket implements Operator { |
76 | 82 |
|
77 | 83 | //#region Events |
78 | 84 |
|
79 | | - addEventListener<K extends keyof GreatWebSocketEventMap>( |
| 85 | + addEventListener<K extends keyof WebSocketEventMap>( |
80 | 86 | type: K, |
81 | 87 | listener: EventListenerOrEventListenerObject, |
82 | 88 | options?: boolean | AddEventListenerOptions, |
83 | 89 | ): void { |
84 | 90 | this.#ws?.addEventListener(type, listener, options); |
85 | 91 | } |
86 | 92 |
|
87 | | - removeEventListener<K extends keyof GreatWebSocketEventMap>( |
| 93 | + removeEventListener<K extends keyof WebSocketEventMap>( |
88 | 94 | type: K, |
89 | 95 | listener: EventListenerOrEventListenerObject, |
90 | 96 | options?: boolean | EventListenerOptions, |
|
0 commit comments