@stomp/stompjs 6.1.1 → 7.0.0-beta1

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 (57) hide show
  1. package/bundles/stomp.umd.js +325 -308
  2. package/bundles/stomp.umd.min.js +1 -2
  3. package/esm6/augment-websocket.js +4 -3
  4. package/esm6/augment-websocket.js.map +1 -0
  5. package/esm6/byte.js.map +1 -0
  6. package/esm6/client.d.ts +29 -13
  7. package/esm6/client.js +75 -16
  8. package/esm6/client.js.map +1 -0
  9. package/esm6/compatibility/compat-client.d.ts +26 -20
  10. package/esm6/compatibility/compat-client.js.map +1 -0
  11. package/esm6/compatibility/heartbeat-info.d.ts +4 -2
  12. package/esm6/compatibility/heartbeat-info.js.map +1 -0
  13. package/esm6/compatibility/stomp.js.map +1 -0
  14. package/esm6/frame-impl.d.ts +2 -2
  15. package/esm6/frame-impl.js +2 -1
  16. package/esm6/frame-impl.js.map +1 -0
  17. package/esm6/i-frame.js +1 -0
  18. package/esm6/i-frame.js.map +1 -0
  19. package/esm6/i-message.js +1 -0
  20. package/esm6/i-message.js.map +1 -0
  21. package/esm6/i-transaction.js +1 -0
  22. package/esm6/i-transaction.js.map +1 -0
  23. package/esm6/index.js +3 -0
  24. package/esm6/index.js.map +1 -0
  25. package/esm6/parser.js +10 -2
  26. package/esm6/parser.js.map +1 -0
  27. package/esm6/stomp-config.js.map +1 -0
  28. package/esm6/stomp-handler.d.ts +5 -8
  29. package/esm6/stomp-handler.js +33 -15
  30. package/esm6/stomp-handler.js.map +1 -0
  31. package/esm6/stomp-headers.js.map +1 -0
  32. package/esm6/stomp-subscription.d.ts +1 -1
  33. package/esm6/stomp-subscription.js +1 -7
  34. package/esm6/stomp-subscription.js.map +1 -0
  35. package/esm6/types.d.ts +28 -2
  36. package/esm6/types.js.map +1 -0
  37. package/esm6/versions.js +2 -2
  38. package/esm6/versions.js.map +1 -0
  39. package/package.json +26 -24
  40. package/src/augment-websocket.ts +39 -0
  41. package/src/byte.ts +13 -0
  42. package/src/client.ts +858 -0
  43. package/src/compatibility/compat-client.ts +269 -0
  44. package/src/compatibility/heartbeat-info.ts +26 -0
  45. package/src/compatibility/stomp.ts +118 -0
  46. package/src/frame-impl.ts +254 -0
  47. package/src/i-frame.ts +41 -0
  48. package/src/i-message.ts +35 -0
  49. package/src/i-transaction.ts +23 -0
  50. package/src/index.ts +15 -0
  51. package/src/parser.ts +267 -0
  52. package/src/stomp-config.ts +152 -0
  53. package/src/stomp-handler.ts +555 -0
  54. package/src/stomp-headers.ts +12 -0
  55. package/src/stomp-subscription.ts +18 -0
  56. package/src/types.ts +183 -0
  57. package/src/versions.ts +50 -0
package/src/client.ts ADDED
@@ -0,0 +1,858 @@
1
+ import { ITransaction } from './i-transaction';
2
+ import { StompConfig } from './stomp-config';
3
+ import { StompHandler } from './stomp-handler';
4
+ import { StompHeaders } from './stomp-headers';
5
+ import { StompSubscription } from './stomp-subscription';
6
+ import {
7
+ ActivationState,
8
+ closeEventCallbackType,
9
+ debugFnType,
10
+ frameCallbackType,
11
+ IPublishParams,
12
+ IStompSocket,
13
+ messageCallbackType,
14
+ StompSocketState,
15
+ wsErrorCallbackType,
16
+ } from './types';
17
+ import { Versions } from './versions';
18
+
19
+ /**
20
+ * @internal
21
+ */
22
+ declare const WebSocket: {
23
+ prototype: IStompSocket;
24
+ new (url: string, protocols?: string | string[]): IStompSocket;
25
+ };
26
+
27
+ /**
28
+ * STOMP Client Class.
29
+ *
30
+ * Part of `@stomp/stompjs`.
31
+ */
32
+ export class Client {
33
+ /**
34
+ * The URL for the STOMP broker to connect to.
35
+ * Typically like `"ws://broker.329broker.com:15674/ws"` or `"wss://broker.329broker.com:15674/ws"`.
36
+ *
37
+ * Only one of this or [Client#webSocketFactory]{@link Client#webSocketFactory} need to be set.
38
+ * If both are set, [Client#webSocketFactory]{@link Client#webSocketFactory} will be used.
39
+ *
40
+ * If your environment does not support WebSockets natively, please refer to
41
+ * [Polyfills]{@link https://stomp-js.github.io/guide/stompjs/rx-stomp/ng2-stompjs/pollyfils-for-stompjs-v5.html}.
42
+ */
43
+ public brokerURL: string | undefined;
44
+
45
+ /**
46
+ * STOMP versions to attempt during STOMP handshake. By default versions `1.0`, `1.1`, and `1.2` are attempted.
47
+ *
48
+ * Example:
49
+ * ```javascript
50
+ * // Try only versions 1.0 and 1.1
51
+ * client.stompVersions = new Versions(['1.0', '1.1'])
52
+ * ```
53
+ */
54
+ public stompVersions = Versions.default;
55
+
56
+ /**
57
+ * This function should return a WebSocket or a similar (e.g. SockJS) object.
58
+ * If your environment does not support WebSockets natively, please refer to
59
+ * [Polyfills]{@link https://stomp-js.github.io/guide/stompjs/rx-stomp/ng2-stompjs/pollyfils-for-stompjs-v5.html}.
60
+ * If your STOMP Broker supports WebSockets, prefer setting [Client#brokerURL]{@link Client#brokerURL}.
61
+ *
62
+ * If both this and [Client#brokerURL]{@link Client#brokerURL} are set, this will be used.
63
+ *
64
+ * Example:
65
+ * ```javascript
66
+ * // use a WebSocket
67
+ * client.webSocketFactory= function () {
68
+ * return new WebSocket("wss://broker.329broker.com:15674/ws");
69
+ * };
70
+ *
71
+ * // Typical usage with SockJS
72
+ * client.webSocketFactory= function () {
73
+ * return new SockJS("http://broker.329broker.com/stomp");
74
+ * };
75
+ * ```
76
+ */
77
+ public webSocketFactory: (() => IStompSocket) | undefined;
78
+
79
+ /**
80
+ * Will retry if Stomp connection is not established in specified milliseconds.
81
+ * Default 0, which implies wait for ever.
82
+ */
83
+ public connectionTimeout: number = 0;
84
+
85
+ // As per https://stackoverflow.com/questions/45802988/typescript-use-correct-version-of-settimeout-node-vs-window/56239226#56239226
86
+ private _connectionWatcher: ReturnType<typeof setTimeout> | undefined; // Timer
87
+
88
+ /**
89
+ * automatically reconnect with delay in milliseconds, set to 0 to disable.
90
+ */
91
+ public reconnectDelay: number = 5000;
92
+
93
+ /**
94
+ * Incoming heartbeat interval in milliseconds. Set to 0 to disable.
95
+ */
96
+ public heartbeatIncoming: number = 10000;
97
+
98
+ /**
99
+ * Outgoing heartbeat interval in milliseconds. Set to 0 to disable.
100
+ */
101
+ public heartbeatOutgoing: number = 10000;
102
+
103
+ /**
104
+ * This switches on a non standard behavior while sending WebSocket packets.
105
+ * It splits larger (text) packets into chunks of [maxWebSocketChunkSize]{@link Client#maxWebSocketChunkSize}.
106
+ * Only Java Spring brokers seems to use this mode.
107
+ *
108
+ * WebSockets, by itself, split large (text) packets,
109
+ * so it is not needed with a truly compliant STOMP/WebSocket broker.
110
+ * Actually setting it for such broker will cause large messages to fail.
111
+ *
112
+ * `false` by default.
113
+ *
114
+ * Binary frames are never split.
115
+ */
116
+ public splitLargeFrames: boolean = false;
117
+
118
+ /**
119
+ * See [splitLargeFrames]{@link Client#splitLargeFrames}.
120
+ * This has no effect if [splitLargeFrames]{@link Client#splitLargeFrames} is `false`.
121
+ */
122
+ public maxWebSocketChunkSize: number = 8 * 1024;
123
+
124
+ /**
125
+ * Usually the
126
+ * [type of WebSocket frame]{@link https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send#Parameters}
127
+ * is automatically decided by type of the payload.
128
+ * Default is `false`, which should work with all compliant brokers.
129
+ *
130
+ * Set this flag to force binary frames.
131
+ */
132
+ public forceBinaryWSFrames: boolean = false;
133
+
134
+ /**
135
+ * A bug in ReactNative chops a string on occurrence of a NULL.
136
+ * See issue [https://github.com/stomp-js/stompjs/issues/89]{@link https://github.com/stomp-js/stompjs/issues/89}.
137
+ * This makes incoming WebSocket messages invalid STOMP packets.
138
+ * Setting this flag attempts to reverse the damage by appending a NULL.
139
+ * If the broker splits a large message into multiple WebSocket messages,
140
+ * this flag will cause data loss and abnormal termination of connection.
141
+ *
142
+ * This is not an ideal solution, but a stop gap until the underlying issue is fixed at ReactNative library.
143
+ */
144
+ public appendMissingNULLonIncoming: boolean = false;
145
+
146
+ /**
147
+ * Underlying WebSocket instance, READONLY.
148
+ */
149
+ get webSocket(): IStompSocket | undefined {
150
+ return this._stompHandler?._webSocket;
151
+ }
152
+
153
+ /**
154
+ * Connection headers, important keys - `login`, `passcode`, `host`.
155
+ * Though STOMP 1.2 standard marks these keys to be present, check your broker documentation for
156
+ * details specific to your broker.
157
+ */
158
+ public connectHeaders: StompHeaders;
159
+
160
+ /**
161
+ * Disconnection headers.
162
+ */
163
+ get disconnectHeaders(): StompHeaders {
164
+ return this._disconnectHeaders;
165
+ }
166
+
167
+ set disconnectHeaders(value: StompHeaders) {
168
+ this._disconnectHeaders = value;
169
+ if (this._stompHandler) {
170
+ this._stompHandler.disconnectHeaders = this._disconnectHeaders;
171
+ }
172
+ }
173
+ private _disconnectHeaders: StompHeaders;
174
+
175
+ /**
176
+ * This function will be called for any unhandled messages.
177
+ * It is useful for receiving messages sent to RabbitMQ temporary queues.
178
+ *
179
+ * It can also get invoked with stray messages while the server is processing
180
+ * a request to [Client#unsubscribe]{@link Client#unsubscribe}
181
+ * from an endpoint.
182
+ *
183
+ * The actual {@link IMessage} will be passed as parameter to the callback.
184
+ */
185
+ public onUnhandledMessage: messageCallbackType;
186
+
187
+ /**
188
+ * STOMP brokers can be requested to notify when an operation is actually completed.
189
+ * Prefer using [Client#watchForReceipt]{@link Client#watchForReceipt}. See
190
+ * [Client#watchForReceipt]{@link Client#watchForReceipt} for examples.
191
+ *
192
+ * The actual {@link FrameImpl} will be passed as parameter to the callback.
193
+ */
194
+ public onUnhandledReceipt: frameCallbackType;
195
+
196
+ /**
197
+ * Will be invoked if {@link FrameImpl} of unknown type is received from the STOMP broker.
198
+ *
199
+ * The actual {@link IFrame} will be passed as parameter to the callback.
200
+ */
201
+ public onUnhandledFrame: frameCallbackType;
202
+
203
+ /**
204
+ * `true` if there is a active connection with STOMP Broker
205
+ */
206
+ get connected(): boolean {
207
+ return !!this._stompHandler && this._stompHandler.connected;
208
+ }
209
+
210
+ /**
211
+ * Callback, invoked on before a connection connection to the STOMP broker.
212
+ *
213
+ * You can change options on the client, which will impact the immediate connect.
214
+ * It is valid to call [Client#decativate]{@link Client#deactivate} in this callback.
215
+ *
216
+ * As of version 5.1, this callback can be
217
+ * [async](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)
218
+ * (i.e., it can return a
219
+ * [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)).
220
+ * In that case connect will be called only after the Promise is resolved.
221
+ * This can be used to reliably fetch credentials, access token etc. from some other service
222
+ * in an asynchronous way.
223
+ */
224
+ public beforeConnect: () => void | Promise<void>;
225
+
226
+ /**
227
+ * Callback, invoked on every successful connection to the STOMP broker.
228
+ *
229
+ * The actual {@link FrameImpl} will be passed as parameter to the callback.
230
+ * Sometimes clients will like to use headers from this frame.
231
+ */
232
+ public onConnect: frameCallbackType;
233
+
234
+ /**
235
+ * Callback, invoked on every successful disconnection from the STOMP broker. It will not be invoked if
236
+ * the STOMP broker disconnected due to an error.
237
+ *
238
+ * The actual Receipt {@link FrameImpl} acknowledging the DISCONNECT will be passed as parameter to the callback.
239
+ *
240
+ * The way STOMP protocol is designed, the connection may close/terminate without the client
241
+ * receiving the Receipt {@link FrameImpl} acknowledging the DISCONNECT.
242
+ * You might find [Client#onWebSocketClose]{@link Client#onWebSocketClose} more appropriate to watch
243
+ * STOMP broker disconnects.
244
+ */
245
+ public onDisconnect: frameCallbackType;
246
+
247
+ /**
248
+ * Callback, invoked on an ERROR frame received from the STOMP Broker.
249
+ * A compliant STOMP Broker will close the connection after this type of frame.
250
+ * Please check broker specific documentation for exact behavior.
251
+ *
252
+ * The actual {@link IFrame} will be passed as parameter to the callback.
253
+ */
254
+ public onStompError: frameCallbackType;
255
+
256
+ /**
257
+ * Callback, invoked when underlying WebSocket is closed.
258
+ *
259
+ * Actual [CloseEvent]{@link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent}
260
+ * is passed as parameter to the callback.
261
+ */
262
+ public onWebSocketClose: closeEventCallbackType;
263
+
264
+ /**
265
+ * Callback, invoked when underlying WebSocket raises an error.
266
+ *
267
+ * Actual [Event]{@link https://developer.mozilla.org/en-US/docs/Web/API/Event}
268
+ * is passed as parameter to the callback.
269
+ */
270
+ public onWebSocketError: wsErrorCallbackType;
271
+
272
+ /**
273
+ * Set it to log the actual raw communication with the broker.
274
+ * When unset, it logs headers of the parsed frames.
275
+ *
276
+ * Change in this effects from next broker reconnect.
277
+ *
278
+ * **Caution: this assumes that frames only have valid UTF8 strings.**
279
+ */
280
+ public logRawCommunication: boolean;
281
+
282
+ /**
283
+ * By default, debug messages are discarded. To log to `console` following can be used:
284
+ *
285
+ * ```javascript
286
+ * client.debug = function(str) {
287
+ * console.log(str);
288
+ * };
289
+ * ```
290
+ *
291
+ * Currently this method does not support levels of log. Be aware that the output can be quite verbose
292
+ * and may contain sensitive information (like passwords, tokens etc.).
293
+ */
294
+ public debug: debugFnType;
295
+
296
+ /**
297
+ * Browsers do not immediately close WebSockets when `.close` is issued.
298
+ * This may cause reconnection to take a longer on certain type of failures.
299
+ * In case of incoming heartbeat failure, this experimental flag instructs the library
300
+ * to discard the socket immediately (even before it is actually closed).
301
+ */
302
+ public discardWebsocketOnCommFailure: boolean = false;
303
+
304
+ /**
305
+ * version of STOMP protocol negotiated with the server, READONLY
306
+ */
307
+ get connectedVersion(): string | undefined {
308
+ return this._stompHandler ? this._stompHandler.connectedVersion : undefined;
309
+ }
310
+
311
+ private _stompHandler: StompHandler | undefined;
312
+
313
+ /**
314
+ * if the client is active (connected or going to reconnect)
315
+ */
316
+ get active(): boolean {
317
+ return this.state === ActivationState.ACTIVE;
318
+ }
319
+
320
+ /**
321
+ * It will be called on state change.
322
+ *
323
+ * When deactivating it may go from ACTIVE to INACTIVE without entering DEACTIVATING.
324
+ */
325
+ public onChangeState: (state: ActivationState) => void;
326
+
327
+ private _changeState(state: ActivationState) {
328
+ this.state = state;
329
+ this.onChangeState(state);
330
+ }
331
+
332
+ /**
333
+ * Activation state.
334
+ *
335
+ * It will usually be ACTIVE or INACTIVE.
336
+ * When deactivating it may go from ACTIVE to INACTIVE without entering DEACTIVATING.
337
+ */
338
+ public state: ActivationState = ActivationState.INACTIVE;
339
+
340
+ private _reconnector: any;
341
+
342
+ /**
343
+ * Create an instance.
344
+ */
345
+ constructor(conf: StompConfig = {}) {
346
+ // Dummy callbacks
347
+ const noOp = () => {};
348
+ this.debug = noOp;
349
+ this.beforeConnect = noOp;
350
+ this.onConnect = noOp;
351
+ this.onDisconnect = noOp;
352
+ this.onUnhandledMessage = noOp;
353
+ this.onUnhandledReceipt = noOp;
354
+ this.onUnhandledFrame = noOp;
355
+ this.onStompError = noOp;
356
+ this.onWebSocketClose = noOp;
357
+ this.onWebSocketError = noOp;
358
+ this.logRawCommunication = false;
359
+ this.onChangeState = noOp;
360
+
361
+ // These parameters would typically get proper values before connect is called
362
+ this.connectHeaders = {};
363
+ this._disconnectHeaders = {};
364
+
365
+ // Apply configuration
366
+ this.configure(conf);
367
+ }
368
+
369
+ /**
370
+ * Update configuration.
371
+ */
372
+ public configure(conf: StompConfig): void {
373
+ // bulk assign all properties to this
374
+ (Object as any).assign(this, conf);
375
+ }
376
+
377
+ /**
378
+ * Initiate the connection with the broker.
379
+ * If the connection breaks, as per [Client#reconnectDelay]{@link Client#reconnectDelay},
380
+ * it will keep trying to reconnect.
381
+ *
382
+ * Call [Client#deactivate]{@link Client#deactivate} to disconnect and stop reconnection attempts.
383
+ */
384
+ public activate(): void {
385
+ if (this.state === ActivationState.DEACTIVATING) {
386
+ this.debug(
387
+ 'Still DEACTIVATING, please await call to deactivate before trying to re-activate'
388
+ );
389
+ throw new Error('Still DEACTIVATING, can not activate now');
390
+ }
391
+
392
+ if (this.active) {
393
+ this.debug('Already ACTIVE, ignoring request to activate');
394
+ return;
395
+ }
396
+
397
+ this._changeState(ActivationState.ACTIVE);
398
+
399
+ this._connect();
400
+ }
401
+
402
+ private async _connect(): Promise<void> {
403
+ if (this.connected) {
404
+ this.debug('STOMP: already connected, nothing to do');
405
+ return;
406
+ }
407
+
408
+ await this.beforeConnect();
409
+
410
+ if (!this.active) {
411
+ this.debug(
412
+ 'Client has been marked inactive, will not attempt to connect'
413
+ );
414
+ return;
415
+ }
416
+
417
+ // setup connection watcher
418
+ if (this.connectionTimeout > 0) {
419
+ // clear first
420
+ if (this._connectionWatcher) {
421
+ clearTimeout(this._connectionWatcher);
422
+ }
423
+ this._connectionWatcher = setTimeout(() => {
424
+ if (this.connected) {
425
+ return;
426
+ }
427
+ // Connection not established, close the underlying socket
428
+ // a reconnection will be attempted
429
+ this.debug(
430
+ `Connection not established in ${this.connectionTimeout}ms, closing socket`
431
+ );
432
+ this.forceDisconnect();
433
+ }, this.connectionTimeout);
434
+ }
435
+
436
+ this.debug('Opening Web Socket...');
437
+
438
+ // Get the actual WebSocket (or a similar object)
439
+ const webSocket = this._createWebSocket();
440
+
441
+ this._stompHandler = new StompHandler(this, webSocket, {
442
+ debug: this.debug,
443
+ stompVersions: this.stompVersions,
444
+ connectHeaders: this.connectHeaders,
445
+ disconnectHeaders: this._disconnectHeaders,
446
+ heartbeatIncoming: this.heartbeatIncoming,
447
+ heartbeatOutgoing: this.heartbeatOutgoing,
448
+ splitLargeFrames: this.splitLargeFrames,
449
+ maxWebSocketChunkSize: this.maxWebSocketChunkSize,
450
+ forceBinaryWSFrames: this.forceBinaryWSFrames,
451
+ logRawCommunication: this.logRawCommunication,
452
+ appendMissingNULLonIncoming: this.appendMissingNULLonIncoming,
453
+ discardWebsocketOnCommFailure: this.discardWebsocketOnCommFailure,
454
+
455
+ onConnect: frame => {
456
+ // Successfully connected, stop the connection watcher
457
+ if (this._connectionWatcher) {
458
+ clearTimeout(this._connectionWatcher);
459
+ this._connectionWatcher = undefined;
460
+ }
461
+
462
+ if (!this.active) {
463
+ this.debug(
464
+ 'STOMP got connected while deactivate was issued, will disconnect now'
465
+ );
466
+ this._disposeStompHandler();
467
+ return;
468
+ }
469
+ this.onConnect(frame);
470
+ },
471
+ onDisconnect: frame => {
472
+ this.onDisconnect(frame);
473
+ },
474
+ onStompError: frame => {
475
+ this.onStompError(frame);
476
+ },
477
+ onWebSocketClose: evt => {
478
+ this._stompHandler = undefined; // a new one will be created in case of a reconnect
479
+
480
+ if (this.state === ActivationState.DEACTIVATING) {
481
+ // Mark deactivation complete
482
+ this._changeState(ActivationState.INACTIVE);
483
+ }
484
+
485
+ // The callback is called before attempting to reconnect, this would allow the client
486
+ // to be `deactivated` in the callback.
487
+ this.onWebSocketClose(evt);
488
+
489
+ if (this.active) {
490
+ this._schedule_reconnect();
491
+ }
492
+ },
493
+ onWebSocketError: evt => {
494
+ this.onWebSocketError(evt);
495
+ },
496
+ onUnhandledMessage: message => {
497
+ this.onUnhandledMessage(message);
498
+ },
499
+ onUnhandledReceipt: frame => {
500
+ this.onUnhandledReceipt(frame);
501
+ },
502
+ onUnhandledFrame: frame => {
503
+ this.onUnhandledFrame(frame);
504
+ },
505
+ });
506
+
507
+ this._stompHandler.start();
508
+ }
509
+
510
+ private _createWebSocket(): IStompSocket {
511
+ let webSocket: IStompSocket;
512
+
513
+ if (this.webSocketFactory) {
514
+ webSocket = this.webSocketFactory();
515
+ } else if (this.brokerURL) {
516
+ webSocket = new WebSocket(
517
+ this.brokerURL,
518
+ this.stompVersions.protocolVersions()
519
+ );
520
+ } else {
521
+ throw new Error('Either brokerURL or webSocketFactory must be provided');
522
+ }
523
+ webSocket.binaryType = 'arraybuffer';
524
+ return webSocket;
525
+ }
526
+
527
+ private _schedule_reconnect(): void {
528
+ if (this.reconnectDelay > 0) {
529
+ this.debug(`STOMP: scheduling reconnection in ${this.reconnectDelay}ms`);
530
+
531
+ this._reconnector = setTimeout(() => {
532
+ this._connect();
533
+ }, this.reconnectDelay);
534
+ }
535
+ }
536
+
537
+ /**
538
+ * Disconnect if connected and stop auto reconnect loop.
539
+ * Appropriate callbacks will be invoked if there is an underlying STOMP connection.
540
+ *
541
+ * This call is async. It will resolve immediately if there is no underlying active websocket,
542
+ * otherwise, it will resolve after the underlying websocket is properly disposed of.
543
+ *
544
+ * It is not an error to invoke this method more than once.
545
+ * Each of those would resolve on completion of deactivation.
546
+ *
547
+ * To reactivate, you can call [Client#activate]{@link Client#activate}.
548
+ *
549
+ * Experimental: pass `force: true` to immediately discard the underlying connection.
550
+ * This mode will skip both the STOMP and the Websocket shutdown sequences.
551
+ * In some cases, browsers take a long time in the Websocket shutdown if the underlying connection had gone stale.
552
+ * Using this mode can speed up.
553
+ * When this mode is used, the actual Websocket may linger for a while
554
+ * and the broker may not realize that the connection is no longer in use.
555
+ *
556
+ * It is possible to invoke this method initially without the `force` option
557
+ * and subsequently, say after a wait, with the `force` option.
558
+ */
559
+ public async deactivate(options: { force?: boolean } = {}): Promise<void> {
560
+ const force: boolean = options.force || false;
561
+ const needToDispose = this.active;
562
+ let retPromise: Promise<void>;
563
+
564
+ if (this.state === ActivationState.INACTIVE) {
565
+ this.debug(`Already INACTIVE, nothing more to do`);
566
+ return Promise.resolve();
567
+ }
568
+
569
+ this._changeState(ActivationState.DEACTIVATING);
570
+
571
+ // Clear if a reconnection was scheduled
572
+ if (this._reconnector) {
573
+ clearTimeout(this._reconnector);
574
+ this._reconnector = undefined;
575
+ }
576
+
577
+ if (
578
+ this._stompHandler &&
579
+ // @ts-ignore - if there is a _stompHandler, there is the webSocket
580
+ this.webSocket.readyState !== StompSocketState.CLOSED
581
+ ) {
582
+ const origOnWebSocketClose = this._stompHandler.onWebSocketClose;
583
+ // we need to wait for the underlying websocket to close
584
+ retPromise = new Promise<void>((resolve, reject) => {
585
+ // @ts-ignore - there is a _stompHandler
586
+ this._stompHandler.onWebSocketClose = evt => {
587
+ origOnWebSocketClose(evt);
588
+ resolve();
589
+ };
590
+ });
591
+ } else {
592
+ // indicate that auto reconnect loop should terminate
593
+ this._changeState(ActivationState.INACTIVE);
594
+ return Promise.resolve();
595
+ }
596
+
597
+ if (force) {
598
+ this._stompHandler?.discardWebsocket();
599
+ } else if (needToDispose) {
600
+ this._disposeStompHandler();
601
+ }
602
+
603
+ return retPromise;
604
+ }
605
+
606
+ /**
607
+ * Force disconnect if there is an active connection by directly closing the underlying WebSocket.
608
+ * This is different than a normal disconnect where a DISCONNECT sequence is carried out with the broker.
609
+ * After forcing disconnect, automatic reconnect will be attempted.
610
+ * To stop further reconnects call [Client#deactivate]{@link Client#deactivate} as well.
611
+ */
612
+ public forceDisconnect() {
613
+ if (this._stompHandler) {
614
+ this._stompHandler.forceDisconnect();
615
+ }
616
+ }
617
+
618
+ private _disposeStompHandler() {
619
+ // Dispose STOMP Handler
620
+ if (this._stompHandler) {
621
+ this._stompHandler.dispose();
622
+ }
623
+ }
624
+
625
+ /**
626
+ * Send a message to a named destination. Refer to your STOMP broker documentation for types
627
+ * and naming of destinations.
628
+ *
629
+ * STOMP protocol specifies and suggests some headers and also allows broker specific headers.
630
+ *
631
+ * `body` must be String.
632
+ * You will need to covert the payload to string in case it is not string (e.g. JSON).
633
+ *
634
+ * To send a binary message body use binaryBody parameter. It should be a
635
+ * [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array).
636
+ * Sometimes brokers may not support binary frames out of the box.
637
+ * Please check your broker documentation.
638
+ *
639
+ * `content-length` header is automatically added to the STOMP Frame sent to the broker.
640
+ * Set `skipContentLengthHeader` to indicate that `content-length` header should not be added.
641
+ * For binary messages `content-length` header is always added.
642
+ *
643
+ * Caution: The broker will, most likely, report an error and disconnect if message body has NULL octet(s)
644
+ * and `content-length` header is missing.
645
+ *
646
+ * ```javascript
647
+ * client.publish({destination: "/queue/test", headers: {priority: 9}, body: "Hello, STOMP"});
648
+ *
649
+ * // Only destination is mandatory parameter
650
+ * client.publish({destination: "/queue/test", body: "Hello, STOMP"});
651
+ *
652
+ * // Skip content-length header in the frame to the broker
653
+ * client.publish({"/queue/test", body: "Hello, STOMP", skipContentLengthHeader: true});
654
+ *
655
+ * var binaryData = generateBinaryData(); // This need to be of type Uint8Array
656
+ * // setting content-type header is not mandatory, however a good practice
657
+ * client.publish({destination: '/topic/special', binaryBody: binaryData,
658
+ * headers: {'content-type': 'application/octet-stream'}});
659
+ * ```
660
+ */
661
+ public publish(params: IPublishParams) {
662
+ this._checkConnection();
663
+ // @ts-ignore - we already checked that there is a _stompHandler, and it is connected
664
+ this._stompHandler.publish(params);
665
+ }
666
+
667
+ private _checkConnection() {
668
+ if (!this.connected) {
669
+ throw new TypeError('There is no underlying STOMP connection');
670
+ }
671
+ }
672
+
673
+ /**
674
+ * STOMP brokers may carry out operation asynchronously and allow requesting for acknowledgement.
675
+ * To request an acknowledgement, a `receipt` header needs to be sent with the actual request.
676
+ * The value (say receipt-id) for this header needs to be unique for each use. Typically a sequence, a UUID, a
677
+ * random number or a combination may be used.
678
+ *
679
+ * A complaint broker will send a RECEIPT frame when an operation has actually been completed.
680
+ * The operation needs to be matched based in the value of the receipt-id.
681
+ *
682
+ * This method allow watching for a receipt and invoke the callback
683
+ * when corresponding receipt has been received.
684
+ *
685
+ * The actual {@link FrameImpl} will be passed as parameter to the callback.
686
+ *
687
+ * Example:
688
+ * ```javascript
689
+ * // Subscribing with acknowledgement
690
+ * let receiptId = randomText();
691
+ *
692
+ * client.watchForReceipt(receiptId, function() {
693
+ * // Will be called after server acknowledges
694
+ * });
695
+ *
696
+ * client.subscribe(TEST.destination, onMessage, {receipt: receiptId});
697
+ *
698
+ *
699
+ * // Publishing with acknowledgement
700
+ * receiptId = randomText();
701
+ *
702
+ * client.watchForReceipt(receiptId, function() {
703
+ * // Will be called after server acknowledges
704
+ * });
705
+ * client.publish({destination: TEST.destination, headers: {receipt: receiptId}, body: msg});
706
+ * ```
707
+ */
708
+ public watchForReceipt(receiptId: string, callback: frameCallbackType): void {
709
+ this._checkConnection();
710
+ // @ts-ignore - we already checked that there is a _stompHandler, and it is connected
711
+ this._stompHandler.watchForReceipt(receiptId, callback);
712
+ }
713
+
714
+ /**
715
+ * Subscribe to a STOMP Broker location. The callback will be invoked for each received message with
716
+ * the {@link IMessage} as argument.
717
+ *
718
+ * Note: The library will generate an unique ID if there is none provided in the headers.
719
+ * To use your own ID, pass it using the headers argument.
720
+ *
721
+ * ```javascript
722
+ * callback = function(message) {
723
+ * // called when the client receives a STOMP message from the server
724
+ * if (message.body) {
725
+ * alert("got message with body " + message.body)
726
+ * } else {
727
+ * alert("got empty message");
728
+ * }
729
+ * });
730
+ *
731
+ * var subscription = client.subscribe("/queue/test", callback);
732
+ *
733
+ * // Explicit subscription id
734
+ * var mySubId = 'my-subscription-id-001';
735
+ * var subscription = client.subscribe(destination, callback, { id: mySubId });
736
+ * ```
737
+ */
738
+ public subscribe(
739
+ destination: string,
740
+ callback: messageCallbackType,
741
+ headers: StompHeaders = {}
742
+ ): StompSubscription {
743
+ this._checkConnection();
744
+ // @ts-ignore - we already checked that there is a _stompHandler, and it is connected
745
+ return this._stompHandler.subscribe(destination, callback, headers);
746
+ }
747
+
748
+ /**
749
+ * It is preferable to unsubscribe from a subscription by calling
750
+ * `unsubscribe()` directly on {@link StompSubscription} returned by `client.subscribe()`:
751
+ *
752
+ * ```javascript
753
+ * var subscription = client.subscribe(destination, onmessage);
754
+ * // ...
755
+ * subscription.unsubscribe();
756
+ * ```
757
+ *
758
+ * See: http://stomp.github.com/stomp-specification-1.2.html#UNSUBSCRIBE UNSUBSCRIBE Frame
759
+ */
760
+ public unsubscribe(id: string, headers: StompHeaders = {}): void {
761
+ this._checkConnection();
762
+ // @ts-ignore - we already checked that there is a _stompHandler, and it is connected
763
+ this._stompHandler.unsubscribe(id, headers);
764
+ }
765
+
766
+ /**
767
+ * Start a transaction, the returned {@link ITransaction} has methods - [commit]{@link ITransaction#commit}
768
+ * and [abort]{@link ITransaction#abort}.
769
+ *
770
+ * `transactionId` is optional, if not passed the library will generate it internally.
771
+ */
772
+ public begin(transactionId?: string): ITransaction {
773
+ this._checkConnection();
774
+ // @ts-ignore - we already checked that there is a _stompHandler, and it is connected
775
+ return this._stompHandler.begin(transactionId);
776
+ }
777
+
778
+ /**
779
+ * Commit a transaction.
780
+ *
781
+ * It is preferable to commit a transaction by calling [commit]{@link ITransaction#commit} directly on
782
+ * {@link ITransaction} returned by [client.begin]{@link Client#begin}.
783
+ *
784
+ * ```javascript
785
+ * var tx = client.begin(txId);
786
+ * //...
787
+ * tx.commit();
788
+ * ```
789
+ */
790
+ public commit(transactionId: string): void {
791
+ this._checkConnection();
792
+ // @ts-ignore - we already checked that there is a _stompHandler, and it is connected
793
+ this._stompHandler.commit(transactionId);
794
+ }
795
+
796
+ /**
797
+ * Abort a transaction.
798
+ * It is preferable to abort a transaction by calling [abort]{@link ITransaction#abort} directly on
799
+ * {@link ITransaction} returned by [client.begin]{@link Client#begin}.
800
+ *
801
+ * ```javascript
802
+ * var tx = client.begin(txId);
803
+ * //...
804
+ * tx.abort();
805
+ * ```
806
+ */
807
+ public abort(transactionId: string): void {
808
+ this._checkConnection();
809
+ // @ts-ignore - we already checked that there is a _stompHandler, and it is connected
810
+ this._stompHandler.abort(transactionId);
811
+ }
812
+
813
+ /**
814
+ * ACK a message. It is preferable to acknowledge a message by calling [ack]{@link IMessage#ack} directly
815
+ * on the {@link IMessage} handled by a subscription callback:
816
+ *
817
+ * ```javascript
818
+ * var callback = function (message) {
819
+ * // process the message
820
+ * // acknowledge it
821
+ * message.ack();
822
+ * };
823
+ * client.subscribe(destination, callback, {'ack': 'client'});
824
+ * ```
825
+ */
826
+ public ack(
827
+ messageId: string,
828
+ subscriptionId: string,
829
+ headers: StompHeaders = {}
830
+ ): void {
831
+ this._checkConnection();
832
+ // @ts-ignore - we already checked that there is a _stompHandler, and it is connected
833
+ this._stompHandler.ack(messageId, subscriptionId, headers);
834
+ }
835
+
836
+ /**
837
+ * NACK a message. It is preferable to acknowledge a message by calling [nack]{@link IMessage#nack} directly
838
+ * on the {@link IMessage} handled by a subscription callback:
839
+ *
840
+ * ```javascript
841
+ * var callback = function (message) {
842
+ * // process the message
843
+ * // an error occurs, nack it
844
+ * message.nack();
845
+ * };
846
+ * client.subscribe(destination, callback, {'ack': 'client'});
847
+ * ```
848
+ */
849
+ public nack(
850
+ messageId: string,
851
+ subscriptionId: string,
852
+ headers: StompHeaders = {}
853
+ ): void {
854
+ this._checkConnection();
855
+ // @ts-ignore - we already checked that there is a _stompHandler, and it is connected
856
+ this._stompHandler.nack(messageId, subscriptionId, headers);
857
+ }
858
+ }