@upbit-official/upbit-sdk 1.0.0 → 1.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.
- package/CHANGELOG.md +5 -0
- package/README.md +21 -0
- package/client.d.mts +10 -4
- package/client.d.mts.map +1 -1
- package/client.d.ts +10 -4
- package/client.d.ts.map +1 -1
- package/client.js +23 -5
- package/client.js.map +1 -1
- package/client.mjs +23 -5
- package/client.mjs.map +1 -1
- package/index.d.mts +3 -1
- package/index.d.mts.map +1 -1
- package/index.d.ts +3 -1
- package/index.d.ts.map +1 -1
- package/index.js +2 -1
- package/index.js.map +1 -1
- package/index.mjs +1 -1
- package/index.mjs.map +1 -1
- package/internal/ws-parser.d.mts +40 -0
- package/internal/ws-parser.d.mts.map +1 -0
- package/internal/ws-parser.d.ts +40 -0
- package/internal/ws-parser.d.ts.map +1 -0
- package/internal/ws-parser.js +125 -0
- package/internal/ws-parser.js.map +1 -0
- package/internal/ws-parser.mjs +118 -0
- package/internal/ws-parser.mjs.map +1 -0
- package/internal/ws-simple-types.d.mts +8 -0
- package/internal/ws-simple-types.d.mts.map +1 -0
- package/internal/ws-simple-types.d.ts +8 -0
- package/internal/ws-simple-types.d.ts.map +1 -0
- package/internal/ws-simple-types.js +3 -0
- package/internal/ws-simple-types.js.map +1 -0
- package/internal/ws-simple-types.mjs +2 -0
- package/internal/ws-simple-types.mjs.map +1 -0
- package/internal/ws.d.mts +1 -0
- package/internal/ws.d.mts.map +1 -1
- package/internal/ws.d.ts +1 -0
- package/internal/ws.d.ts.map +1 -1
- package/internal/ws.js.map +1 -1
- package/internal/ws.mjs.map +1 -1
- package/lib/index.d.mts +4 -2
- package/lib/index.d.mts.map +1 -1
- package/lib/index.d.ts +4 -2
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +2 -1
- package/lib/index.js.map +1 -1
- package/lib/index.mjs +1 -1
- package/lib/index.mjs.map +1 -1
- package/lib/jsonParseFloat.d.mts +5 -5
- package/lib/jsonParseFloat.d.mts.map +1 -1
- package/lib/jsonParseFloat.d.ts +5 -5
- package/lib/jsonParseFloat.d.ts.map +1 -1
- package/lib/jsonParseFloat.js +30 -12
- package/lib/jsonParseFloat.js.map +1 -1
- package/lib/jsonParseFloat.mjs +30 -12
- package/lib/jsonParseFloat.mjs.map +1 -1
- package/lib/ws.d.mts +102 -15
- package/lib/ws.d.mts.map +1 -1
- package/lib/ws.d.ts +102 -15
- package/lib/ws.d.ts.map +1 -1
- package/lib/ws.js +208 -34
- package/lib/ws.js.map +1 -1
- package/lib/ws.mjs +204 -33
- package/lib/ws.mjs.map +1 -1
- package/package.json +1 -1
- package/resources/index.d.mts +3 -2
- package/resources/index.d.mts.map +1 -1
- package/resources/index.d.ts +3 -2
- package/resources/index.d.ts.map +1 -1
- package/resources/index.js +3 -1
- package/resources/index.js.map +1 -1
- package/resources/index.mjs +3 -2
- package/resources/index.mjs.map +1 -1
- package/resources/ws-info/index.d.mts +6 -0
- package/resources/ws-info/index.d.mts.map +1 -0
- package/resources/ws-info/index.d.ts +6 -0
- package/resources/ws-info/index.d.ts.map +1 -0
- package/resources/ws-info/index.js +6 -0
- package/resources/ws-info/index.js.map +1 -0
- package/resources/ws-info/index.mjs +2 -0
- package/resources/ws-info/index.mjs.map +1 -0
- package/resources/ws-info/internal-base.d.mts +63 -0
- package/resources/ws-info/internal-base.d.mts.map +1 -0
- package/resources/ws-info/internal-base.d.ts +63 -0
- package/resources/ws-info/internal-base.d.ts.map +1 -0
- package/resources/ws-info/internal-base.js +47 -0
- package/resources/ws-info/internal-base.js.map +1 -0
- package/resources/ws-info/internal-base.mjs +41 -0
- package/resources/ws-info/internal-base.mjs.map +1 -0
- package/resources/ws-info/ws-info.d.mts +1180 -0
- package/resources/ws-info/ws-info.d.mts.map +1 -0
- package/resources/ws-info/ws-info.d.ts +1180 -0
- package/resources/ws-info/ws-info.d.ts.map +1 -0
- package/resources/ws-info/ws-info.js +8 -0
- package/resources/ws-info/ws-info.js.map +1 -0
- package/resources/ws-info/ws-info.mjs +4 -0
- package/resources/ws-info/ws-info.mjs.map +1 -0
- package/resources/ws-info/ws.d.mts +91 -0
- package/resources/ws-info/ws.d.mts.map +1 -0
- package/resources/ws-info/ws.d.ts +91 -0
- package/resources/ws-info/ws.d.ts.map +1 -0
- package/resources/ws-info/ws.js +463 -0
- package/resources/ws-info/ws.js.map +1 -0
- package/resources/ws-info/ws.mjs +458 -0
- package/resources/ws-info/ws.mjs.map +1 -0
- package/resources/ws-info.d.mts +2 -0
- package/resources/ws-info.d.mts.map +1 -0
- package/resources/ws-info.d.ts +2 -0
- package/resources/ws-info.d.ts.map +1 -0
- package/resources/ws-info.js +5 -0
- package/resources/ws-info.js.map +1 -0
- package/resources/ws-info.mjs +2 -0
- package/resources/ws-info.mjs.map +1 -0
- package/resources/ws-private/index.d.mts +3 -1
- package/resources/ws-private/index.d.mts.map +1 -1
- package/resources/ws-private/index.d.ts +3 -1
- package/resources/ws-private/index.d.ts.map +1 -1
- package/resources/ws-private/index.js.map +1 -1
- package/resources/ws-private/index.mjs +1 -1
- package/resources/ws-private/index.mjs.map +1 -1
- package/resources/ws-private/internal-base.d.mts.map +1 -1
- package/resources/ws-private/internal-base.d.ts.map +1 -1
- package/resources/ws-private/internal-base.js.map +1 -1
- package/resources/ws-private/internal-base.mjs.map +1 -1
- package/resources/ws-private/ws-private.d.mts +301 -9
- package/resources/ws-private/ws-private.d.mts.map +1 -1
- package/resources/ws-private/ws-private.d.ts +301 -9
- package/resources/ws-private/ws-private.d.ts.map +1 -1
- package/resources/ws-private/ws-private.js.map +1 -1
- package/resources/ws-private/ws-private.mjs.map +1 -1
- package/resources/ws-private/ws.d.mts +2 -2
- package/resources/ws-private/ws.d.mts.map +1 -1
- package/resources/ws-private/ws.d.ts +2 -2
- package/resources/ws-private/ws.d.ts.map +1 -1
- package/resources/ws-private/ws.js +15 -20
- package/resources/ws-private/ws.js.map +1 -1
- package/resources/ws-private/ws.mjs +15 -20
- package/resources/ws-private/ws.mjs.map +1 -1
- package/resources/ws-public/index.d.mts +3 -1
- package/resources/ws-public/index.d.mts.map +1 -1
- package/resources/ws-public/index.d.ts +3 -1
- package/resources/ws-public/index.d.ts.map +1 -1
- package/resources/ws-public/index.js.map +1 -1
- package/resources/ws-public/index.mjs +1 -1
- package/resources/ws-public/index.mjs.map +1 -1
- package/resources/ws-public/internal-base.d.mts.map +1 -1
- package/resources/ws-public/internal-base.d.ts.map +1 -1
- package/resources/ws-public/internal-base.js.map +1 -1
- package/resources/ws-public/internal-base.mjs.map +1 -1
- package/resources/ws-public/ws-public.d.mts +355 -5
- package/resources/ws-public/ws-public.d.mts.map +1 -1
- package/resources/ws-public/ws-public.d.ts +355 -5
- package/resources/ws-public/ws-public.d.ts.map +1 -1
- package/resources/ws-public/ws.d.mts +2 -2
- package/resources/ws-public/ws.d.mts.map +1 -1
- package/resources/ws-public/ws.d.ts +2 -2
- package/resources/ws-public/ws.d.ts.map +1 -1
- package/resources/ws-public/ws.js +15 -20
- package/resources/ws-public/ws.js.map +1 -1
- package/resources/ws-public/ws.mjs +15 -20
- package/resources/ws-public/ws.mjs.map +1 -1
- package/src/client.ts +92 -5
- package/src/index.ts +24 -1
- package/src/internal/ws-parser.ts +164 -0
- package/src/internal/ws-simple-types.ts +34 -0
- package/src/internal/ws.ts +1 -0
- package/src/lib/index.ts +17 -2
- package/src/lib/jsonParseFloat.ts +37 -12
- package/src/lib/ws.ts +367 -55
- package/src/resources/index.ts +42 -2
- package/src/resources/ws-info/index.ts +44 -0
- package/src/resources/ws-info/internal-base.ts +96 -0
- package/src/resources/ws-info/ws-info.ts +1855 -0
- package/src/resources/ws-info/ws.ts +574 -0
- package/src/resources/ws-info.ts +1 -0
- package/src/resources/ws-private/index.ts +12 -1
- package/src/resources/ws-private/internal-base.ts +0 -1
- package/src/resources/ws-private/ws-private.ts +420 -18
- package/src/resources/ws-private/ws.ts +16 -23
- package/src/resources/ws-public/index.ts +16 -1
- package/src/resources/ws-public/internal-base.ts +0 -1
- package/src/resources/ws-public/ws-public.ts +459 -4
- package/src/resources/ws-public/ws.ts +16 -23
- package/src/version.ts +1 -1
- package/version.d.mts +1 -1
- package/version.d.ts +1 -1
- package/version.js +1 -1
- package/version.js.map +1 -1
- package/version.mjs +1 -1
- package/version.mjs.map +1 -1
|
@@ -0,0 +1,574 @@
|
|
|
1
|
+
import {
|
|
2
|
+
WsInfoEmitter,
|
|
3
|
+
type WsInfoServerMessage,
|
|
4
|
+
WsInfoStreamMessage,
|
|
5
|
+
WebSocketError,
|
|
6
|
+
buildURL,
|
|
7
|
+
} from './internal-base';
|
|
8
|
+
import { InternalEventEmitter } from '../../core/EventEmitter';
|
|
9
|
+
import { sleep } from '../../internal/utils/sleep';
|
|
10
|
+
import * as WS from 'ws';
|
|
11
|
+
import { isRecoverableClose, type ReconnectingEvent, type ReconnectingOverrides } from '../../internal/ws';
|
|
12
|
+
import * as WsInfoAPI from './ws-info';
|
|
13
|
+
import { Upbit } from '../../client';
|
|
14
|
+
import { UpbitError } from '../../core/error';
|
|
15
|
+
import { createJwtToken } from '../../lib/jwtAuth';
|
|
16
|
+
import { isRecord, parseWebSocketValue } from '../../internal/ws-parser';
|
|
17
|
+
|
|
18
|
+
export interface WsInfoWSReconnectOptions {
|
|
19
|
+
/**
|
|
20
|
+
* Called before each reconnect attempt. Return an object with
|
|
21
|
+
* `parameters` to override query parameters for the next connection.
|
|
22
|
+
*/
|
|
23
|
+
onReconnecting(
|
|
24
|
+
event: ReconnectingEvent<Record<string, unknown>>,
|
|
25
|
+
): ReconnectingOverrides<Record<string, unknown>> | void;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Maximum number of reconnection attempts. Default: 5.
|
|
29
|
+
* Set to 0 to disable reconnection entirely.
|
|
30
|
+
*/
|
|
31
|
+
maxRetries?: number;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Initial backoff delay in milliseconds. Default: 500.
|
|
35
|
+
*/
|
|
36
|
+
initialDelay?: number;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Maximum backoff delay in milliseconds. Default: 8000.
|
|
40
|
+
*/
|
|
41
|
+
maxDelay?: number;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface WsInfoWSClientOptions extends WS.ClientOptions {
|
|
45
|
+
/**
|
|
46
|
+
* Options for automatic reconnection on recoverable close codes.
|
|
47
|
+
* Automatic reconnection is only enabled when this has a non-null value.
|
|
48
|
+
*/
|
|
49
|
+
reconnect?: WsInfoWSReconnectOptions | null | undefined;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export class WsInfoWS extends WsInfoEmitter {
|
|
53
|
+
url!: URL;
|
|
54
|
+
socket!: WS.WebSocket;
|
|
55
|
+
|
|
56
|
+
private _client: Upbit;
|
|
57
|
+
private _parameters: Record<string, unknown> | null | undefined;
|
|
58
|
+
private _wsOptions: WS.ClientOptions | null | undefined;
|
|
59
|
+
private _reconnectOptions: WsInfoWSReconnectOptions | null;
|
|
60
|
+
private _sendQueue: string[] = [];
|
|
61
|
+
private _isReconnecting: boolean = false;
|
|
62
|
+
private _intentionallyClosed = false;
|
|
63
|
+
private _closeCode: number = 1000;
|
|
64
|
+
private _closeReason: string = 'OK';
|
|
65
|
+
private _lastCloseCode: number = 1006;
|
|
66
|
+
private _lastCloseReason: string = '';
|
|
67
|
+
|
|
68
|
+
// Necessary to keep the public event interface clean while we manage reconnecting
|
|
69
|
+
private _internalEvents = new InternalEventEmitter<{
|
|
70
|
+
socketSwap: (oldSocket: WS.WebSocket, newSocket: WS.WebSocket) => void;
|
|
71
|
+
reconnecting: (event: ReconnectingEvent<Record<string, unknown>>) => void;
|
|
72
|
+
reconnected: () => void;
|
|
73
|
+
close: (code: number, reason: string) => void;
|
|
74
|
+
}>();
|
|
75
|
+
|
|
76
|
+
constructor(
|
|
77
|
+
client: Upbit,
|
|
78
|
+
parameters?: Record<string, unknown> | undefined,
|
|
79
|
+
options?: WsInfoWSClientOptions | null | undefined,
|
|
80
|
+
) {
|
|
81
|
+
super();
|
|
82
|
+
if (!WS?.WebSocket) {
|
|
83
|
+
throw new Error('WsInfoWS requires the "ws" package but it could not be loaded');
|
|
84
|
+
}
|
|
85
|
+
this._client = client;
|
|
86
|
+
this._parameters = parameters;
|
|
87
|
+
const { reconnect, ...wsOptions } = options ?? {};
|
|
88
|
+
this._wsOptions = wsOptions;
|
|
89
|
+
this._reconnectOptions = reconnect ?? null;
|
|
90
|
+
this.url = buildURL(client, parameters);
|
|
91
|
+
this.socket = this._connect();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
send(event: WsInfoAPI.ConnectInfoClientEvent) {
|
|
95
|
+
if (!this.socket) {
|
|
96
|
+
throw new UpbitError('Internal error: failed to initialize socket. Please report this issue.');
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if (this._isReconnecting || this.socket.readyState === WS.WebSocket.CONNECTING) {
|
|
100
|
+
this._sendQueue.push(JSON.stringify(event));
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
if (this.socket.readyState !== WS.WebSocket.OPEN) {
|
|
104
|
+
this._onError(null, 'cannot send on a closed WebSocket', undefined);
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
try {
|
|
108
|
+
this.socket.send(JSON.stringify(event));
|
|
109
|
+
} catch (err) {
|
|
110
|
+
this._onError(null, 'could not send data', err);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
close(props?: { code: number; reason: string }) {
|
|
115
|
+
if (!this.socket) {
|
|
116
|
+
throw new UpbitError('Internal error: failed to initialize socket. Please report this issue.');
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
this._intentionallyClosed = true;
|
|
120
|
+
this._closeCode = props?.code ?? 1000;
|
|
121
|
+
this._closeReason = props?.reason ?? 'OK';
|
|
122
|
+
try {
|
|
123
|
+
this.socket.close(this._closeCode, this._closeReason);
|
|
124
|
+
} catch (err) {
|
|
125
|
+
this._onError(null, 'could not close the connection', err);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Returns an async iterator over WebSocket lifecycle and message events,
|
|
131
|
+
* providing an alternative to the event-based `.on()` API.
|
|
132
|
+
* The iterator will exit if the socket closes but exiting the iterator
|
|
133
|
+
* does not close the socket.
|
|
134
|
+
*
|
|
135
|
+
* @example
|
|
136
|
+
* ```ts
|
|
137
|
+
* for await (const event of client.stream()) {
|
|
138
|
+
* switch (event.type) {
|
|
139
|
+
* case 'message':
|
|
140
|
+
* console.log('received:', event.message);
|
|
141
|
+
* break;
|
|
142
|
+
* case 'error':
|
|
143
|
+
* console.error(event.error);
|
|
144
|
+
* break;
|
|
145
|
+
* case 'close':
|
|
146
|
+
* console.log('connection closed');
|
|
147
|
+
* break;
|
|
148
|
+
* }
|
|
149
|
+
* }
|
|
150
|
+
* ```
|
|
151
|
+
*/
|
|
152
|
+
stream(): AsyncIterableIterator<WsInfoStreamMessage> {
|
|
153
|
+
return this[Symbol.asyncIterator]();
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
[Symbol.asyncIterator](): AsyncIterableIterator<WsInfoStreamMessage> {
|
|
157
|
+
if (!this.socket) {
|
|
158
|
+
throw new UpbitError('Internal error: failed to initialize socket. Please report this issue.');
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Two-queue async iterator: `queue` buffers incoming messages,
|
|
162
|
+
// `resolvers` buffers waiting next() calls. A push wakes the
|
|
163
|
+
// oldest next(); a next() drains the oldest message.
|
|
164
|
+
const queue: WsInfoStreamMessage[] = [];
|
|
165
|
+
const resolvers: (() => void)[] = [];
|
|
166
|
+
let done = false;
|
|
167
|
+
let currentSocket = this.socket;
|
|
168
|
+
|
|
169
|
+
const push = (msg: WsInfoStreamMessage) => {
|
|
170
|
+
queue.push(msg);
|
|
171
|
+
resolvers.shift()?.();
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
const onEvent = (event: WsInfoServerMessage) => {
|
|
175
|
+
push({ type: 'message', message: event });
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
// Connection and transport errors funnel through _onError → 'error' event
|
|
179
|
+
const onEmitterError = (err: WebSocketError) => {
|
|
180
|
+
push({ type: 'error', error: err });
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
const onOpen = () => {
|
|
184
|
+
push({ type: 'open' });
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
const onReconnecting = (evt: ReconnectingEvent<Record<string, unknown>>) => {
|
|
188
|
+
push({ type: 'reconnecting', reconnect: evt });
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
const onReconnected = () => {
|
|
192
|
+
push({ type: 'reconnected' });
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
const flushResolvers = () => {
|
|
196
|
+
for (let resolver = resolvers.shift(); resolver; resolver = resolvers.shift()) {
|
|
197
|
+
resolver();
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
const onClose = (code: number, reason: string) => {
|
|
202
|
+
push({ type: 'close', code, reason });
|
|
203
|
+
done = true;
|
|
204
|
+
flushResolvers();
|
|
205
|
+
cleanup();
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
const onSocketSwap = (oldSocket: WS.WebSocket, newSocket: WS.WebSocket) => {
|
|
209
|
+
oldSocket.off('open', onOpen);
|
|
210
|
+
newSocket.on('open', onOpen);
|
|
211
|
+
currentSocket = newSocket;
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
const cleanup = () => {
|
|
215
|
+
this.off('event', onEvent);
|
|
216
|
+
this.off('error', onEmitterError);
|
|
217
|
+
currentSocket.off('open', onOpen);
|
|
218
|
+
this._internalEvents.off('close', onClose);
|
|
219
|
+
this._internalEvents.off('socketSwap', onSocketSwap);
|
|
220
|
+
this._internalEvents.off('reconnecting', onReconnecting);
|
|
221
|
+
this._internalEvents.off('reconnected', onReconnected);
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
this.on('event', onEvent);
|
|
225
|
+
this.on('error', onEmitterError);
|
|
226
|
+
this.socket.on('open', onOpen);
|
|
227
|
+
this._internalEvents.on('close', onClose);
|
|
228
|
+
this._internalEvents.on('socketSwap', onSocketSwap);
|
|
229
|
+
this._internalEvents.on('reconnecting', onReconnecting);
|
|
230
|
+
this._internalEvents.on('reconnected', onReconnected);
|
|
231
|
+
|
|
232
|
+
if (this._isReconnecting) {
|
|
233
|
+
// A reconnect is already in flight. The socket may be CLOSED but the
|
|
234
|
+
// instance is still alive. Emit 'reconnecting' so the iterator stays
|
|
235
|
+
// open and receives the upcoming reconnected/message events.
|
|
236
|
+
push({
|
|
237
|
+
type: 'reconnecting',
|
|
238
|
+
reconnect: { attempt: 0, maxAttempts: 0, delay: 0, closeCode: 0, parameters: undefined },
|
|
239
|
+
});
|
|
240
|
+
} else {
|
|
241
|
+
switch (this.socket.readyState) {
|
|
242
|
+
case WS.WebSocket.CONNECTING:
|
|
243
|
+
push({ type: 'connecting' });
|
|
244
|
+
break;
|
|
245
|
+
case WS.WebSocket.OPEN:
|
|
246
|
+
push({ type: 'open' });
|
|
247
|
+
break;
|
|
248
|
+
case WS.WebSocket.CLOSING:
|
|
249
|
+
push({ type: 'closing' });
|
|
250
|
+
break;
|
|
251
|
+
case WS.WebSocket.CLOSED:
|
|
252
|
+
push({
|
|
253
|
+
type: 'close',
|
|
254
|
+
code: this._lastCloseCode,
|
|
255
|
+
reason: this._lastCloseReason,
|
|
256
|
+
});
|
|
257
|
+
done = true;
|
|
258
|
+
cleanup();
|
|
259
|
+
break;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const resolve = (res: (value: IteratorResult<WsInfoStreamMessage>) => void) => {
|
|
264
|
+
if (queue.length > 0) {
|
|
265
|
+
res({ value: queue.shift()!, done: false });
|
|
266
|
+
} else if (done) {
|
|
267
|
+
res({ value: undefined, done: true });
|
|
268
|
+
} else {
|
|
269
|
+
return false;
|
|
270
|
+
}
|
|
271
|
+
return true;
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
const next = (): Promise<IteratorResult<WsInfoStreamMessage>> =>
|
|
275
|
+
new Promise((res) => {
|
|
276
|
+
if (resolve(res)) return;
|
|
277
|
+
resolvers.push(() => {
|
|
278
|
+
resolve(res);
|
|
279
|
+
});
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
return {
|
|
283
|
+
next,
|
|
284
|
+
return: (): Promise<IteratorReturnResult<undefined>> => {
|
|
285
|
+
done = true;
|
|
286
|
+
cleanup();
|
|
287
|
+
flushResolvers();
|
|
288
|
+
return Promise.resolve({ value: undefined, done: true });
|
|
289
|
+
},
|
|
290
|
+
[Symbol.asyncIterator]() {
|
|
291
|
+
return this;
|
|
292
|
+
},
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
private _connect(): WS.WebSocket {
|
|
297
|
+
this.url = buildURL(this._client, this._parameters ?? {});
|
|
298
|
+
|
|
299
|
+
const socket = new WS.WebSocket(this.url, {
|
|
300
|
+
...this._wsOptions,
|
|
301
|
+
headers: this._client._buildWebSocketHandshakeHeaders(this._authHeaders(), this._wsOptions?.headers),
|
|
302
|
+
});
|
|
303
|
+
let pingTimer: ReturnType<typeof setInterval> | undefined;
|
|
304
|
+
socket.on('open', () => {
|
|
305
|
+
pingTimer = setInterval(() => {
|
|
306
|
+
if (socket.readyState === WS.WebSocket.OPEN) socket.ping();
|
|
307
|
+
}, 30_000);
|
|
308
|
+
});
|
|
309
|
+
socket.on('close', () => {
|
|
310
|
+
if (pingTimer !== undefined) clearInterval(pingTimer);
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
socket.on('message', (data: WS.RawData, _isBinary: boolean) => {
|
|
314
|
+
let event: unknown;
|
|
315
|
+
try {
|
|
316
|
+
event = parseWebSocketValue(data);
|
|
317
|
+
} catch {
|
|
318
|
+
this._onError(null, 'could not parse WebSocket message', new SyntaxError('Invalid WebSocket JSON'));
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
this._emit('event', event as WsInfoServerMessage);
|
|
322
|
+
if (isRecord(event) && (event['type'] === 'indicator' || event['type'] === 'indicator_signal')) {
|
|
323
|
+
// @ts-ignore The discriminator is checked at runtime.
|
|
324
|
+
this._emit(event['type'], event);
|
|
325
|
+
}
|
|
326
|
+
});
|
|
327
|
+
|
|
328
|
+
socket.on('error', (err: Error) => {
|
|
329
|
+
// Suppress transient errors during reconnection — the retry loop
|
|
330
|
+
// already handles them and will surface a close if retries exhaust.
|
|
331
|
+
if (this._isReconnecting) return;
|
|
332
|
+
this._onError(null, err.message, err);
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
socket.on('open', () => {
|
|
336
|
+
this._flushSendQueue();
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
socket.on('close', (code: number, reason: Buffer) => {
|
|
340
|
+
// Ignore close events from superseded sockets — a stale socket's
|
|
341
|
+
// late close must not kick off a second reconnect loop.
|
|
342
|
+
if (socket !== this.socket) return;
|
|
343
|
+
if (!this._intentionallyClosed && this._canReconnect(code)) {
|
|
344
|
+
this._reconnect(code);
|
|
345
|
+
} else if (!this._isReconnecting) {
|
|
346
|
+
this._emitPermanentClose(code, reason.toString());
|
|
347
|
+
}
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
return socket;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// Reconnect is opt-in via onReconnecting so callers can pass
|
|
354
|
+
// state (e.g. session IDs) into the new connection.
|
|
355
|
+
private _canReconnect(code: number): boolean {
|
|
356
|
+
if (this._intentionallyClosed) return false;
|
|
357
|
+
if (!this._reconnectOptions) return false;
|
|
358
|
+
if (this._reconnectOptions.maxRetries === 0) return false;
|
|
359
|
+
if (!this._reconnectOptions.onReconnecting) return false;
|
|
360
|
+
return isRecoverableClose(code);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
private async _reconnect(closeCode: number): Promise<void> {
|
|
364
|
+
if (!this.socket) {
|
|
365
|
+
throw new UpbitError('Internal error: failed to initialize socket. Please report this issue.');
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
if (this._isReconnecting || !this._reconnectOptions) return;
|
|
369
|
+
this._isReconnecting = true;
|
|
370
|
+
|
|
371
|
+
const maxRetries = this._reconnectOptions.maxRetries ?? 5;
|
|
372
|
+
const initialDelay = this._reconnectOptions.initialDelay ?? 500;
|
|
373
|
+
const maxDelay = this._reconnectOptions.maxDelay ?? 8000;
|
|
374
|
+
|
|
375
|
+
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
|
376
|
+
if (!this._canReconnect(closeCode)) {
|
|
377
|
+
this._isReconnecting = false;
|
|
378
|
+
if (!this._intentionallyClosed) {
|
|
379
|
+
this._onError(
|
|
380
|
+
null,
|
|
381
|
+
`WebSocket reconnect aborted: non-recoverable close code ${closeCode}`,
|
|
382
|
+
undefined,
|
|
383
|
+
);
|
|
384
|
+
}
|
|
385
|
+
this._emitPermanentClose(
|
|
386
|
+
this._intentionallyClosed ? this._closeCode : closeCode,
|
|
387
|
+
this._intentionallyClosed ? this._closeReason : 'reconnect aborted',
|
|
388
|
+
);
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
const baseDelay = Math.min(initialDelay * Math.pow(2, attempt - 1), maxDelay);
|
|
393
|
+
// Jitter: rand [0.75, 1.0] to spread out connection attempts without over-delaying
|
|
394
|
+
const jitter = 0.75 + Math.random() * 0.25;
|
|
395
|
+
const actualDelay = Math.round(baseDelay * jitter);
|
|
396
|
+
|
|
397
|
+
let reconnectingEvent: ReconnectingEvent<Record<string, unknown>> = {
|
|
398
|
+
attempt,
|
|
399
|
+
maxAttempts: maxRetries,
|
|
400
|
+
delay: actualDelay,
|
|
401
|
+
closeCode,
|
|
402
|
+
parameters: this._parameters ? { ...this._parameters } : undefined,
|
|
403
|
+
};
|
|
404
|
+
|
|
405
|
+
let overrides: ReconnectingOverrides<Record<string, unknown>> | void;
|
|
406
|
+
try {
|
|
407
|
+
overrides = this._reconnectOptions.onReconnecting(reconnectingEvent);
|
|
408
|
+
} catch (err) {
|
|
409
|
+
this._isReconnecting = false;
|
|
410
|
+
this._onError(null, 'onReconnecting callback threw', err);
|
|
411
|
+
this._emitPermanentClose(closeCode, 'onReconnecting callback threw');
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
if (overrides && 'abort' in overrides && overrides.abort) {
|
|
416
|
+
this._isReconnecting = false;
|
|
417
|
+
this._emitPermanentClose(closeCode, 'reconnect aborted by handler');
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
if (overrides && 'parameters' in overrides) {
|
|
422
|
+
this._parameters = overrides.parameters;
|
|
423
|
+
reconnectingEvent = { ...reconnectingEvent, parameters: this._parameters };
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
try {
|
|
427
|
+
this._emit('reconnecting', reconnectingEvent);
|
|
428
|
+
} catch (err) {
|
|
429
|
+
this._onError(null, 'onReconnecting callback threw', err);
|
|
430
|
+
}
|
|
431
|
+
this._internalEvents._emit('reconnecting', reconnectingEvent);
|
|
432
|
+
|
|
433
|
+
if (!this._canReconnect(closeCode)) {
|
|
434
|
+
this._isReconnecting = false;
|
|
435
|
+
if (!this._intentionallyClosed) {
|
|
436
|
+
this._onError(
|
|
437
|
+
null,
|
|
438
|
+
`WebSocket reconnect aborted: non-recoverable close code ${closeCode}`,
|
|
439
|
+
undefined,
|
|
440
|
+
);
|
|
441
|
+
}
|
|
442
|
+
this._emitPermanentClose(
|
|
443
|
+
this._intentionallyClosed ? this._closeCode : closeCode,
|
|
444
|
+
this._intentionallyClosed ? this._closeReason : 'reconnect aborted',
|
|
445
|
+
);
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
await sleep(actualDelay);
|
|
450
|
+
|
|
451
|
+
if (!this._canReconnect(closeCode)) {
|
|
452
|
+
this._isReconnecting = false;
|
|
453
|
+
if (!this._intentionallyClosed) {
|
|
454
|
+
this._onError(
|
|
455
|
+
null,
|
|
456
|
+
`WebSocket reconnect aborted: non-recoverable close code ${closeCode}`,
|
|
457
|
+
undefined,
|
|
458
|
+
);
|
|
459
|
+
}
|
|
460
|
+
this._emitPermanentClose(
|
|
461
|
+
this._intentionallyClosed ? this._closeCode : closeCode,
|
|
462
|
+
this._intentionallyClosed ? this._closeReason : 'reconnect aborted',
|
|
463
|
+
);
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
let closeCodePromise: Promise<number> | undefined;
|
|
468
|
+
try {
|
|
469
|
+
const oldSocket = this.socket;
|
|
470
|
+
this.socket = this._connect();
|
|
471
|
+
// Registered synchronously after _connect() and before any
|
|
472
|
+
// await so the code is captured even when ws emits 'close'
|
|
473
|
+
// in the same tick as 'error' (e.g. abortHandshake).
|
|
474
|
+
closeCodePromise = new Promise<number>((resolve) => {
|
|
475
|
+
this.socket.once('close', resolve);
|
|
476
|
+
});
|
|
477
|
+
|
|
478
|
+
await this._awaitOpen(this.socket);
|
|
479
|
+
|
|
480
|
+
this._internalEvents._emit('socketSwap', oldSocket, this.socket);
|
|
481
|
+
this._isReconnecting = false;
|
|
482
|
+
this._flushSendQueue();
|
|
483
|
+
this._emit('reconnected');
|
|
484
|
+
this._internalEvents._emit('reconnected');
|
|
485
|
+
return;
|
|
486
|
+
} catch {
|
|
487
|
+
if (closeCodePromise) {
|
|
488
|
+
// ws may emit 'error' before 'close', so await the code
|
|
489
|
+
// rather than reading it synchronously.
|
|
490
|
+
closeCode = await closeCodePromise;
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
// All retries exhausted — surface an error so consumers can
|
|
496
|
+
// distinguish retry failure from a clean close.
|
|
497
|
+
this._isReconnecting = false;
|
|
498
|
+
this._onError(
|
|
499
|
+
null,
|
|
500
|
+
`WebSocket reconnect failed after ${maxRetries} attempts (close code: ${closeCode})`,
|
|
501
|
+
undefined,
|
|
502
|
+
);
|
|
503
|
+
this._emitPermanentClose(closeCode, `reconnect failed after ${maxRetries} attempts`);
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* Resolves once the socket is open, rejects if it errors or closes first
|
|
508
|
+
*/
|
|
509
|
+
private _awaitOpen(socket: WS.WebSocket): Promise<void> {
|
|
510
|
+
return new Promise<void>((resolve, reject) => {
|
|
511
|
+
const cleanup = () => {
|
|
512
|
+
socket.off('open', onOpen);
|
|
513
|
+
socket.off('error', onError);
|
|
514
|
+
socket.off('close', onFail);
|
|
515
|
+
};
|
|
516
|
+
const onOpen = () => {
|
|
517
|
+
cleanup();
|
|
518
|
+
resolve();
|
|
519
|
+
};
|
|
520
|
+
const onError = (err: Error) => {
|
|
521
|
+
cleanup();
|
|
522
|
+
reject(err);
|
|
523
|
+
};
|
|
524
|
+
const onFail = () => {
|
|
525
|
+
cleanup();
|
|
526
|
+
reject(new Error('socket closed before open'));
|
|
527
|
+
};
|
|
528
|
+
socket.once('open', onOpen);
|
|
529
|
+
socket.once('error', onError);
|
|
530
|
+
socket.once('close', onFail);
|
|
531
|
+
});
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
private _flushSendQueue(): void {
|
|
535
|
+
if (!this.socket) {
|
|
536
|
+
throw new UpbitError('Internal error: failed to initialize socket. Please report this issue.');
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
const pending = this._sendQueue.splice(0);
|
|
540
|
+
for (let i = 0; i < pending.length; i++) {
|
|
541
|
+
try {
|
|
542
|
+
if (this.socket.readyState !== WS.WebSocket.OPEN) {
|
|
543
|
+
// Avoid dropping messages by sending them out over a closing socket
|
|
544
|
+
this._sendQueue.unshift(...pending.slice(i));
|
|
545
|
+
return;
|
|
546
|
+
} else {
|
|
547
|
+
this.socket.send(pending[i]!);
|
|
548
|
+
}
|
|
549
|
+
} catch (err) {
|
|
550
|
+
// Re-queue remaining for next open/reconnect
|
|
551
|
+
this._sendQueue.unshift(...pending.slice(i));
|
|
552
|
+
this._onError(null, 'could not send queued data', err);
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/** Close the iterator even when a public close listener throws. */
|
|
559
|
+
private _emitPermanentClose(code: number, reason: string): void {
|
|
560
|
+
this._lastCloseCode = code;
|
|
561
|
+
this._lastCloseReason = reason;
|
|
562
|
+
this._sendQueue = [];
|
|
563
|
+
this._internalEvents._emit('close', code, reason);
|
|
564
|
+
this._emit('close', code, reason);
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
protected _authHeaders(): Record<string, string> {
|
|
568
|
+
const { accessKey, secretKey } = this._client;
|
|
569
|
+
if (!accessKey || !secretKey) {
|
|
570
|
+
throw new UpbitError('Info WebSocket requires accessKey and secretKey');
|
|
571
|
+
}
|
|
572
|
+
return { Authorization: `Bearer ${createJwtToken(accessKey, secretKey)}` };
|
|
573
|
+
}
|
|
574
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './ws-info/index';
|
|
@@ -1,2 +1,13 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export {
|
|
2
|
+
WsPrivate,
|
|
3
|
+
type Announcement,
|
|
4
|
+
type AnnouncementCategory,
|
|
5
|
+
type AnnouncementEventType,
|
|
6
|
+
type ConnectPrivateClientEvent,
|
|
7
|
+
type ConnectPrivateServerEvent,
|
|
8
|
+
type ConnectPrivateServerMessage,
|
|
9
|
+
} from './ws-private';
|
|
2
10
|
export { type WsPrivateWSClientOptions, type WsPrivateWSReconnectOptions } from './ws';
|
|
11
|
+
|
|
12
|
+
export type { SimplePrivateServerEvent } from '../../internal/ws-simple-types';
|
|
13
|
+
export type { SimpleMyOrder, SimpleMyAsset, SimpleAnnouncement } from '../../internal/ws-simple-types';
|
|
@@ -5,7 +5,6 @@ import { UpbitError } from '../../core/error';
|
|
|
5
5
|
import { stringifyQuery } from '../../internal/utils';
|
|
6
6
|
|
|
7
7
|
import type { ReconnectingEvent } from '../../internal/ws';
|
|
8
|
-
|
|
9
8
|
export type WsPrivateStreamMessage =
|
|
10
9
|
| { type: 'connecting' | 'open' | 'closing' | 'close' }
|
|
11
10
|
| { type: 'reconnecting'; reconnect: ReconnectingEvent }
|