@stomp/stompjs 7.0.0-beta2 → 7.0.0-beta3

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 (45) hide show
  1. package/README.md +11 -18
  2. package/bundles/package.json +6 -0
  3. package/bundles/stomp.umd.js +47 -47
  4. package/bundles/stomp.umd.js.map +1 -1
  5. package/bundles/stomp.umd.min.js +1 -1
  6. package/bundles/tcp-wrapper.cjs +84 -0
  7. package/bundles/tcp-wrapper.cjs.map +1 -0
  8. package/esm6/client.d.ts +45 -41
  9. package/esm6/client.js +34 -31
  10. package/esm6/client.js.map +1 -1
  11. package/esm6/compatibility/compat-client.d.ts +1 -1
  12. package/esm6/compatibility/compat-client.js +1 -1
  13. package/esm6/i-message.d.ts +2 -2
  14. package/esm6/index-web.d.ts +13 -0
  15. package/esm6/index-web.js +15 -0
  16. package/esm6/index-web.js.map +1 -0
  17. package/esm6/index.d.ts +2 -13
  18. package/esm6/index.js +2 -14
  19. package/esm6/index.js.map +1 -1
  20. package/esm6/parser.js +3 -3
  21. package/esm6/parser.js.map +1 -1
  22. package/esm6/stomp-config.d.ts +1 -4
  23. package/esm6/stomp-config.js +0 -3
  24. package/esm6/stomp-config.js.map +1 -1
  25. package/esm6/stomp-handler.js +6 -6
  26. package/esm6/stomp-handler.js.map +1 -1
  27. package/esm6/tcp-wrapper.d.ts +18 -0
  28. package/esm6/tcp-wrapper.js +61 -0
  29. package/esm6/tcp-wrapper.js.map +1 -0
  30. package/esm6/types.d.ts +10 -9
  31. package/esm6/types.js.map +1 -1
  32. package/esm6/versions.d.ts +3 -3
  33. package/esm6/versions.js +3 -3
  34. package/package.json +9 -6
  35. package/src/client.ts +46 -42
  36. package/src/compatibility/compat-client.ts +1 -1
  37. package/src/i-message.ts +2 -2
  38. package/src/index-web.ts +15 -0
  39. package/src/index.ts +2 -15
  40. package/src/parser.ts +3 -3
  41. package/src/stomp-config.ts +1 -4
  42. package/src/stomp-handler.ts +6 -6
  43. package/src/tcp-wrapper.ts +83 -0
  44. package/src/types.ts +10 -9
  45. package/src/versions.ts +3 -3
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).StompJs={})}(this,(function(e){"use strict";const t="\n",s="\0";class n{constructor(e){const{command:t,headers:s,body:n,binaryBody:i,escapeHeaderValues:o,skipContentLengthHeader:c}=e;this.command=t,this.headers=Object.assign({},s||{}),i?(this._binaryBody=i,this.isBinaryBody=!0):(this._body=n||"",this.isBinaryBody=!1),this.escapeHeaderValues=o||!1,this.skipContentLengthHeader=c||!1}get body(){return!this._body&&this.isBinaryBody&&(this._body=(new TextDecoder).decode(this._binaryBody)),this._body||""}get binaryBody(){return this._binaryBody||this.isBinaryBody||(this._binaryBody=(new TextEncoder).encode(this._body)),this._binaryBody}static fromRawFrame(e,t){const s={},i=e=>e.replace(/^\s+|\s+$/g,"");for(const o of e.headers.reverse()){o.indexOf(":");const c=i(o[0]);let r=i(o[1]);t&&"CONNECT"!==e.command&&"CONNECTED"!==e.command&&(r=n.hdrValueUnEscape(r)),s[c]=r}return new n({command:e.command,headers:s,binaryBody:e.binaryBody,escapeHeaderValues:t})}toString(){return this.serializeCmdAndHeaders()}serialize(){const e=this.serializeCmdAndHeaders();return this.isBinaryBody?n.toUnit8Array(e,this._binaryBody).buffer:e+this._body+s}serializeCmdAndHeaders(){const e=[this.command];this.skipContentLengthHeader&&delete this.headers["content-length"];for(const t of Object.keys(this.headers||{})){const s=this.headers[t];this.escapeHeaderValues&&"CONNECT"!==this.command&&"CONNECTED"!==this.command?e.push(`${t}:${n.hdrValueEscape(`${s}`)}`):e.push(`${t}:${s}`)}return(this.isBinaryBody||!this.isBodyEmpty()&&!this.skipContentLengthHeader)&&e.push(`content-length:${this.bodyLength()}`),e.join(t)+t+t}isBodyEmpty(){return 0===this.bodyLength()}bodyLength(){const e=this.binaryBody;return e?e.length:0}static sizeOfUTF8(e){return e?(new TextEncoder).encode(e).length:0}static toUnit8Array(e,t){const s=(new TextEncoder).encode(e),n=new Uint8Array([0]),i=new Uint8Array(s.length+t.length+n.length);return i.set(s),i.set(t,s.length),i.set(n,s.length+t.length),i}static marshall(e){return new n(e).serialize()}static hdrValueEscape(e){return e.replace(/\\/g,"\\\\").replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/:/g,"\\c")}static hdrValueUnEscape(e){return e.replace(/\\r/g,"\r").replace(/\\n/g,"\n").replace(/\\c/g,":").replace(/\\\\/g,"\\")}}class i{constructor(e,t){this.onFrame=e,this.onIncomingPing=t,this._encoder=new TextEncoder,this._decoder=new TextDecoder,this._token=[],this._initState()}parseChunk(e,t=!1){let s;if(s=e instanceof ArrayBuffer?new Uint8Array(e):this._encoder.encode(e),t&&0!==s[s.length-1]){const e=new Uint8Array(s.length+1);e.set(s,0),e[s.length]=0,s=e}for(let e=0;e<s.length;e++){const t=s[e];this._onByte(t)}}_collectFrame(e){0!==e&&13!==e&&(10!==e?(this._onByte=this._collectCommand,this._reinjectByte(e)):this.onIncomingPing())}_collectCommand(e){if(13!==e)return 10===e?(this._results.command=this._consumeTokenAsUTF8(),void(this._onByte=this._collectHeaders)):void this._consumeByte(e)}_collectHeaders(e){13!==e&&(10!==e?(this._onByte=this._collectHeaderKey,this._reinjectByte(e)):this._setupCollectBody())}_reinjectByte(e){this._onByte(e)}_collectHeaderKey(e){if(58===e)return this._headerKey=this._consumeTokenAsUTF8(),void(this._onByte=this._collectHeaderValue);this._consumeByte(e)}_collectHeaderValue(e){if(13!==e)return 10===e?(this._results.headers.push([this._headerKey,this._consumeTokenAsUTF8()]),this._headerKey=void 0,void(this._onByte=this._collectHeaders)):void this._consumeByte(e)}_setupCollectBody(){const e=this._results.headers.filter((e=>"content-length"===e[0]))[0];e?(this._bodyBytesRemaining=parseInt(e[1],10),this._onByte=this._collectBodyFixedSize):this._onByte=this._collectBodyNullTerminated}_collectBodyNullTerminated(e){0!==e?this._consumeByte(e):this._retrievedBody()}_collectBodyFixedSize(e){0!=this._bodyBytesRemaining--?this._consumeByte(e):this._retrievedBody()}_retrievedBody(){this._results.binaryBody=this._consumeTokenAsRaw();try{this.onFrame(this._results)}catch(e){console.log("Ignoring an exception thrown by a frame handler. Original exception: ",e)}this._initState()}_consumeByte(e){this._token.push(e)}_consumeTokenAsUTF8(){return this._decoder.decode(this._consumeTokenAsRaw())}_consumeTokenAsRaw(){const e=new Uint8Array(this._token);return this._token=[],e}_initState(){this._results={command:void 0,headers:[],binaryBody:void 0},this._token=[],this._headerKey=void 0,this._onByte=this._collectFrame}}var o,c;e.StompSocketState=void 0,(o=e.StompSocketState=e.StompSocketState||(e.StompSocketState={}))[o.CONNECTING=0]="CONNECTING",o[o.OPEN=1]="OPEN",o[o.CLOSING=2]="CLOSING",o[o.CLOSED=3]="CLOSED",e.ActivationState=void 0,(c=e.ActivationState=e.ActivationState||(e.ActivationState={}))[c.ACTIVE=0]="ACTIVE",c[c.DEACTIVATING=1]="DEACTIVATING",c[c.INACTIVE=2]="INACTIVE";class r{constructor(e){this.versions=e}supportedVersions(){return this.versions.join(",")}protocolVersions(){return this.versions.map((e=>`v${e.replace(".","")}.stomp`))}}r.V1_0="1.0",r.V1_1="1.1",r.V1_2="1.2",r.default=new r([r.V1_2,r.V1_1,r.V1_0]);class a{constructor(e,t,s){this._client=e,this._webSocket=t,this._connected=!1,this._serverFrameHandlers={CONNECTED:e=>{this.debug(`connected to server ${e.headers.server}`),this._connected=!0,this._connectedVersion=e.headers.version,this._connectedVersion===r.V1_2&&(this._escapeHeaderValues=!0),this._setupHeartbeat(e.headers),this.onConnect(e)},MESSAGE:e=>{const t=e.headers.subscription,s=this._subscriptions[t]||this.onUnhandledMessage,n=e,i=this,o=this._connectedVersion===r.V1_2?n.headers.ack:n.headers["message-id"];n.ack=(e={})=>i.ack(o,t,e),n.nack=(e={})=>i.nack(o,t,e),s(n)},RECEIPT:e=>{const t=this._receiptWatchers[e.headers["receipt-id"]];t?(t(e),delete this._receiptWatchers[e.headers["receipt-id"]]):this.onUnhandledReceipt(e)},ERROR:e=>{this.onStompError(e)}},this._counter=0,this._subscriptions={},this._receiptWatchers={},this._partialData="",this._escapeHeaderValues=!1,this._lastServerActivityTS=Date.now(),this.debug=s.debug,this.stompVersions=s.stompVersions,this.connectHeaders=s.connectHeaders,this.disconnectHeaders=s.disconnectHeaders,this.heartbeatIncoming=s.heartbeatIncoming,this.heartbeatOutgoing=s.heartbeatOutgoing,this.splitLargeFrames=s.splitLargeFrames,this.maxWebSocketChunkSize=s.maxWebSocketChunkSize,this.forceBinaryWSFrames=s.forceBinaryWSFrames,this.logRawCommunication=s.logRawCommunication,this.appendMissingNULLonIncoming=s.appendMissingNULLonIncoming,this.discardWebsocketOnCommFailure=s.discardWebsocketOnCommFailure,this.onConnect=s.onConnect,this.onDisconnect=s.onDisconnect,this.onStompError=s.onStompError,this.onWebSocketClose=s.onWebSocketClose,this.onWebSocketError=s.onWebSocketError,this.onUnhandledMessage=s.onUnhandledMessage,this.onUnhandledReceipt=s.onUnhandledReceipt,this.onUnhandledFrame=s.onUnhandledFrame}get connectedVersion(){return this._connectedVersion}get connected(){return this._connected}start(){const e=new i((e=>{const t=n.fromRawFrame(e,this._escapeHeaderValues);this.logRawCommunication||this.debug(`<<< ${t}`);(this._serverFrameHandlers[t.command]||this.onUnhandledFrame)(t)}),(()=>{this.debug("<<< PONG")}));this._webSocket.onmessage=t=>{if(this.debug("Received data"),this._lastServerActivityTS=Date.now(),this.logRawCommunication){const e=t.data instanceof ArrayBuffer?(new TextDecoder).decode(t.data):t.data;this.debug(`<<< ${e}`)}e.parseChunk(t.data,this.appendMissingNULLonIncoming)},this._webSocket.onclose=e=>{this.debug(`Connection closed to ${this._client.brokerURL}`),this._cleanUp(),this.onWebSocketClose(e)},this._webSocket.onerror=e=>{this.onWebSocketError(e)},this._webSocket.onopen=()=>{const e=Object.assign({},this.connectHeaders);this.debug("Web Socket Opened..."),e["accept-version"]=this.stompVersions.supportedVersions(),e["heart-beat"]=[this.heartbeatOutgoing,this.heartbeatIncoming].join(","),this._transmit({command:"CONNECT",headers:e})}}_setupHeartbeat(s){if(s.version!==r.V1_1&&s.version!==r.V1_2)return;if(!s["heart-beat"])return;const[n,i]=s["heart-beat"].split(",").map((e=>parseInt(e,10)));if(0!==this.heartbeatOutgoing&&0!==i){const s=Math.max(this.heartbeatOutgoing,i);this.debug(`send PING every ${s}ms`),this._pinger=setInterval((()=>{this._webSocket.readyState===e.StompSocketState.OPEN&&(this._webSocket.send(t),this.debug(">>> PING"))}),s)}if(0!==this.heartbeatIncoming&&0!==n){const e=Math.max(this.heartbeatIncoming,n);this.debug(`check PONG every ${e}ms`),this._ponger=setInterval((()=>{const t=Date.now()-this._lastServerActivityTS;t>2*e&&(this.debug(`did not receive server activity for the last ${t}ms`),this._closeOrDiscardWebsocket())}),e)}}_closeOrDiscardWebsocket(){this.discardWebsocketOnCommFailure?(this.debug("Discarding websocket, the underlying socket may linger for a while"),this.discardWebsocket()):(this.debug("Issuing close on the websocket"),this._closeWebsocket())}forceDisconnect(){this._webSocket&&(this._webSocket.readyState!==e.StompSocketState.CONNECTING&&this._webSocket.readyState!==e.StompSocketState.OPEN||this._closeOrDiscardWebsocket())}_closeWebsocket(){this._webSocket.onmessage=()=>{},this._webSocket.close()}discardWebsocket(){var e,t;"function"!=typeof this._webSocket.terminate&&(e=this._webSocket,t=e=>this.debug(e),e.terminate=function(){const s=()=>{};this.onerror=s,this.onmessage=s,this.onopen=s;const n=new Date,i=Math.random().toString().substring(2,8),o=this.onclose;this.onclose=e=>{const s=(new Date).getTime()-n.getTime();t(`Discarded socket (#${i}) closed after ${s}ms, with code/reason: ${e.code}/${e.reason}`)},this.close(),o?.call(e,{code:4001,reason:`Quick discarding socket (#${i}) without waiting for the shutdown sequence.`,wasClean:!1})}),this._webSocket.terminate()}_transmit(e){const{command:t,headers:s,body:i,binaryBody:o,skipContentLengthHeader:c}=e,r=new n({command:t,headers:s,body:i,binaryBody:o,escapeHeaderValues:this._escapeHeaderValues,skipContentLengthHeader:c});let a=r.serialize();if(this.logRawCommunication?this.debug(`>>> ${a}`):this.debug(`>>> ${r}`),this.forceBinaryWSFrames&&"string"==typeof a&&(a=(new TextEncoder).encode(a)),"string"==typeof a&&this.splitLargeFrames){let e=a;for(;e.length>0;){const t=e.substring(0,this.maxWebSocketChunkSize);e=e.substring(this.maxWebSocketChunkSize),this._webSocket.send(t),this.debug(`chunk sent = ${t.length}, remaining = ${e.length}`)}}else this._webSocket.send(a)}dispose(){if(this.connected)try{const e=Object.assign({},this.disconnectHeaders);e.receipt||(e.receipt="close-"+this._counter++),this.watchForReceipt(e.receipt,(e=>{this._closeWebsocket(),this._cleanUp(),this.onDisconnect(e)})),this._transmit({command:"DISCONNECT",headers:e})}catch(e){this.debug(`Ignoring error during disconnect ${e}`)}else this._webSocket.readyState!==e.StompSocketState.CONNECTING&&this._webSocket.readyState!==e.StompSocketState.OPEN||this._closeWebsocket()}_cleanUp(){this._connected=!1,this._pinger&&(clearInterval(this._pinger),this._pinger=void 0),this._ponger&&(clearInterval(this._ponger),this._ponger=void 0)}publish(e){const{destination:t,headers:s,body:n,binaryBody:i,skipContentLengthHeader:o}=e,c=Object.assign({destination:t},s);this._transmit({command:"SEND",headers:c,body:n,binaryBody:i,skipContentLengthHeader:o})}watchForReceipt(e,t){this._receiptWatchers[e]=t}subscribe(e,t,s={}){(s=Object.assign({},s)).id||(s.id="sub-"+this._counter++),s.destination=e,this._subscriptions[s.id]=t,this._transmit({command:"SUBSCRIBE",headers:s});const n=this;return{id:s.id,unsubscribe:e=>n.unsubscribe(s.id,e)}}unsubscribe(e,t={}){t=Object.assign({},t),delete this._subscriptions[e],t.id=e,this._transmit({command:"UNSUBSCRIBE",headers:t})}begin(e){const t=e||"tx-"+this._counter++;this._transmit({command:"BEGIN",headers:{transaction:t}});const s=this;return{id:t,commit(){s.commit(t)},abort(){s.abort(t)}}}commit(e){this._transmit({command:"COMMIT",headers:{transaction:e}})}abort(e){this._transmit({command:"ABORT",headers:{transaction:e}})}ack(e,t,s={}){s=Object.assign({},s),this._connectedVersion===r.V1_2?s.id=e:s["message-id"]=e,s.subscription=t,this._transmit({command:"ACK",headers:s})}nack(e,t,s={}){return s=Object.assign({},s),this._connectedVersion===r.V1_2?s.id=e:s["message-id"]=e,s.subscription=t,this._transmit({command:"NACK",headers:s})}}class h{constructor(t={}){this.stompVersions=r.default,this.connectionTimeout=0,this.reconnectDelay=5e3,this.heartbeatIncoming=1e4,this.heartbeatOutgoing=1e4,this.splitLargeFrames=!1,this.maxWebSocketChunkSize=8192,this.forceBinaryWSFrames=!1,this.appendMissingNULLonIncoming=!1,this.discardWebsocketOnCommFailure=!1,this.state=e.ActivationState.INACTIVE;const s=()=>{};this.debug=s,this.beforeConnect=s,this.onConnect=s,this.onDisconnect=s,this.onUnhandledMessage=s,this.onUnhandledReceipt=s,this.onUnhandledFrame=s,this.onStompError=s,this.onWebSocketClose=s,this.onWebSocketError=s,this.logRawCommunication=!1,this.onChangeState=s,this.connectHeaders={},this._disconnectHeaders={},this.configure(t)}get webSocket(){return this._stompHandler?._webSocket}get disconnectHeaders(){return this._disconnectHeaders}set disconnectHeaders(e){this._disconnectHeaders=e,this._stompHandler&&(this._stompHandler.disconnectHeaders=this._disconnectHeaders)}get connected(){return!!this._stompHandler&&this._stompHandler.connected}get connectedVersion(){return this._stompHandler?this._stompHandler.connectedVersion:void 0}get active(){return this.state===e.ActivationState.ACTIVE}_changeState(e){this.state=e,this.onChangeState(e)}configure(e){Object.assign(this,e)}activate(){if(this.state===e.ActivationState.DEACTIVATING)throw this.debug("Still DEACTIVATING, please await call to deactivate before trying to re-activate"),new Error("Still DEACTIVATING, can not activate now");this.active?this.debug("Already ACTIVE, ignoring request to activate"):(this._changeState(e.ActivationState.ACTIVE),this._connect())}async _connect(){if(this.connected)return void this.debug("STOMP: already connected, nothing to do");if(await this.beforeConnect(),!this.active)return void this.debug("Client has been marked inactive, will not attempt to connect");this.connectionTimeout>0&&(this._connectionWatcher&&clearTimeout(this._connectionWatcher),this._connectionWatcher=setTimeout((()=>{this.connected||(this.debug(`Connection not established in ${this.connectionTimeout}ms, closing socket`),this.forceDisconnect())}),this.connectionTimeout)),this.debug("Opening Web Socket...");const t=this._createWebSocket();this._stompHandler=new a(this,t,{debug:this.debug,stompVersions:this.stompVersions,connectHeaders:this.connectHeaders,disconnectHeaders:this._disconnectHeaders,heartbeatIncoming:this.heartbeatIncoming,heartbeatOutgoing:this.heartbeatOutgoing,splitLargeFrames:this.splitLargeFrames,maxWebSocketChunkSize:this.maxWebSocketChunkSize,forceBinaryWSFrames:this.forceBinaryWSFrames,logRawCommunication:this.logRawCommunication,appendMissingNULLonIncoming:this.appendMissingNULLonIncoming,discardWebsocketOnCommFailure:this.discardWebsocketOnCommFailure,onConnect:e=>{if(this._connectionWatcher&&(clearTimeout(this._connectionWatcher),this._connectionWatcher=void 0),!this.active)return this.debug("STOMP got connected while deactivate was issued, will disconnect now"),void this._disposeStompHandler();this.onConnect(e)},onDisconnect:e=>{this.onDisconnect(e)},onStompError:e=>{this.onStompError(e)},onWebSocketClose:t=>{this._stompHandler=void 0,this.state===e.ActivationState.DEACTIVATING&&this._changeState(e.ActivationState.INACTIVE),this.onWebSocketClose(t),this.active&&this._schedule_reconnect()},onWebSocketError:e=>{this.onWebSocketError(e)},onUnhandledMessage:e=>{this.onUnhandledMessage(e)},onUnhandledReceipt:e=>{this.onUnhandledReceipt(e)},onUnhandledFrame:e=>{this.onUnhandledFrame(e)}}),this._stompHandler.start()}_createWebSocket(){let e;if(this.webSocketFactory)e=this.webSocketFactory();else{if(!this.brokerURL)throw new Error("Either brokerURL or webSocketFactory must be provided");e=new WebSocket(this.brokerURL,this.stompVersions.protocolVersions())}return e.binaryType="arraybuffer",e}_schedule_reconnect(){this.reconnectDelay>0&&(this.debug(`STOMP: scheduling reconnection in ${this.reconnectDelay}ms`),this._reconnector=setTimeout((()=>{this._connect()}),this.reconnectDelay))}async deactivate(t={}){const s=t.force||!1,n=this.active;let i;if(this.state===e.ActivationState.INACTIVE)return this.debug("Already INACTIVE, nothing more to do"),Promise.resolve();if(this._changeState(e.ActivationState.DEACTIVATING),this._reconnector&&(clearTimeout(this._reconnector),this._reconnector=void 0),!this._stompHandler||this.webSocket.readyState===e.StompSocketState.CLOSED)return this._changeState(e.ActivationState.INACTIVE),Promise.resolve();{const e=this._stompHandler.onWebSocketClose;i=new Promise(((t,s)=>{this._stompHandler.onWebSocketClose=s=>{e(s),t()}}))}return s?this._stompHandler?.discardWebsocket():n&&this._disposeStompHandler(),i}forceDisconnect(){this._stompHandler&&this._stompHandler.forceDisconnect()}_disposeStompHandler(){this._stompHandler&&this._stompHandler.dispose()}publish(e){this._checkConnection(),this._stompHandler.publish(e)}_checkConnection(){if(!this.connected)throw new TypeError("There is no underlying STOMP connection")}watchForReceipt(e,t){this._checkConnection(),this._stompHandler.watchForReceipt(e,t)}subscribe(e,t,s={}){return this._checkConnection(),this._stompHandler.subscribe(e,t,s)}unsubscribe(e,t={}){this._checkConnection(),this._stompHandler.unsubscribe(e,t)}begin(e){return this._checkConnection(),this._stompHandler.begin(e)}commit(e){this._checkConnection(),this._stompHandler.commit(e)}abort(e){this._checkConnection(),this._stompHandler.abort(e)}ack(e,t,s={}){this._checkConnection(),this._stompHandler.ack(e,t,s)}nack(e,t,s={}){this._checkConnection(),this._stompHandler.nack(e,t,s)}}class d{constructor(e){this.client=e}get outgoing(){return this.client.heartbeatOutgoing}set outgoing(e){this.client.heartbeatOutgoing=e}get incoming(){return this.client.heartbeatIncoming}set incoming(e){this.client.heartbeatIncoming=e}}class l extends h{constructor(e){super(),this.maxWebSocketFrameSize=16384,this._heartbeatInfo=new d(this),this.reconnect_delay=0,this.webSocketFactory=e,this.debug=(...e)=>{console.log(...e)}}_parseConnect(...e){let t,s,n,i={};if(e.length<2)throw new Error("Connect requires at least 2 arguments");if("function"==typeof e[1])[i,s,n,t]=e;else if(6===e.length)[i.login,i.passcode,s,n,t,i.host]=e;else[i.login,i.passcode,s,n,t]=e;return[i,s,n,t]}connect(...e){const t=this._parseConnect(...e);t[0]&&(this.connectHeaders=t[0]),t[1]&&(this.onConnect=t[1]),t[2]&&(this.onStompError=t[2]),t[3]&&(this.onWebSocketClose=t[3]),super.activate()}disconnect(e,t={}){e&&(this.onDisconnect=e),this.disconnectHeaders=t,super.deactivate()}send(e,t={},s=""){const n=!1===(t=Object.assign({},t))["content-length"];n&&delete t["content-length"],this.publish({destination:e,headers:t,body:s,skipContentLengthHeader:n})}set reconnect_delay(e){this.reconnectDelay=e}get ws(){return this.webSocket}get version(){return this.connectedVersion}get onreceive(){return this.onUnhandledMessage}set onreceive(e){this.onUnhandledMessage=e}get onreceipt(){return this.onUnhandledReceipt}set onreceipt(e){this.onUnhandledReceipt=e}get heartbeat(){return this._heartbeatInfo}set heartbeat(e){this.heartbeatIncoming=e.incoming,this.heartbeatOutgoing=e.outgoing}}class m{static client(e,t){null==t&&(t=r.default.protocolVersions());return new l((()=>new(m.WebSocketClass||WebSocket)(e,t)))}static over(e){let t;return"function"==typeof e?t=e:(console.warn("Stomp.over did not receive a factory, auto reconnect will not work. Please see https://stomp-js.github.io/api-docs/latest/classes/Stomp.html#over"),t=()=>e),new l(t)}}m.WebSocketClass=null,e.Client=h,e.CompatClient=l,e.FrameImpl=n,e.Parser=i,e.Stomp=m,e.StompConfig=class{},e.StompHeaders=class{},e.Versions=r}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).StompJs={})}(this,(function(e){"use strict";const t="\n",s="\0";class n{constructor(e){const{command:t,headers:s,body:n,binaryBody:i,escapeHeaderValues:o,skipContentLengthHeader:c}=e;this.command=t,this.headers=Object.assign({},s||{}),i?(this._binaryBody=i,this.isBinaryBody=!0):(this._body=n||"",this.isBinaryBody=!1),this.escapeHeaderValues=o||!1,this.skipContentLengthHeader=c||!1}get body(){return!this._body&&this.isBinaryBody&&(this._body=(new TextDecoder).decode(this._binaryBody)),this._body||""}get binaryBody(){return this._binaryBody||this.isBinaryBody||(this._binaryBody=(new TextEncoder).encode(this._body)),this._binaryBody}static fromRawFrame(e,t){const s={},i=e=>e.replace(/^\s+|\s+$/g,"");for(const o of e.headers.reverse()){o.indexOf(":");const c=i(o[0]);let r=i(o[1]);t&&"CONNECT"!==e.command&&"CONNECTED"!==e.command&&(r=n.hdrValueUnEscape(r)),s[c]=r}return new n({command:e.command,headers:s,binaryBody:e.binaryBody,escapeHeaderValues:t})}toString(){return this.serializeCmdAndHeaders()}serialize(){const e=this.serializeCmdAndHeaders();return this.isBinaryBody?n.toUnit8Array(e,this._binaryBody).buffer:e+this._body+s}serializeCmdAndHeaders(){const e=[this.command];this.skipContentLengthHeader&&delete this.headers["content-length"];for(const t of Object.keys(this.headers||{})){const s=this.headers[t];this.escapeHeaderValues&&"CONNECT"!==this.command&&"CONNECTED"!==this.command?e.push(`${t}:${n.hdrValueEscape(`${s}`)}`):e.push(`${t}:${s}`)}return(this.isBinaryBody||!this.isBodyEmpty()&&!this.skipContentLengthHeader)&&e.push(`content-length:${this.bodyLength()}`),e.join(t)+t+t}isBodyEmpty(){return 0===this.bodyLength()}bodyLength(){const e=this.binaryBody;return e?e.length:0}static sizeOfUTF8(e){return e?(new TextEncoder).encode(e).length:0}static toUnit8Array(e,t){const s=(new TextEncoder).encode(e),n=new Uint8Array([0]),i=new Uint8Array(s.length+t.length+n.length);return i.set(s),i.set(t,s.length),i.set(n,s.length+t.length),i}static marshall(e){return new n(e).serialize()}static hdrValueEscape(e){return e.replace(/\\/g,"\\\\").replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/:/g,"\\c")}static hdrValueUnEscape(e){return e.replace(/\\r/g,"\r").replace(/\\n/g,"\n").replace(/\\c/g,":").replace(/\\\\/g,"\\")}}class i{constructor(e,t){this.onFrame=e,this.onIncomingPing=t,this._encoder=new TextEncoder,this._decoder=new TextDecoder,this._token=[],this._initState()}parseChunk(e,t=!1){let s;if(s="string"==typeof e?this._encoder.encode(e):new Uint8Array(e),t&&0!==s[s.length-1]){const e=new Uint8Array(s.length+1);e.set(s,0),e[s.length]=0,s=e}for(let e=0;e<s.length;e++){const t=s[e];this._onByte(t)}}_collectFrame(e){0!==e&&13!==e&&(10!==e?(this._onByte=this._collectCommand,this._reinjectByte(e)):this.onIncomingPing())}_collectCommand(e){if(13!==e)return 10===e?(this._results.command=this._consumeTokenAsUTF8(),void(this._onByte=this._collectHeaders)):void this._consumeByte(e)}_collectHeaders(e){13!==e&&(10!==e?(this._onByte=this._collectHeaderKey,this._reinjectByte(e)):this._setupCollectBody())}_reinjectByte(e){this._onByte(e)}_collectHeaderKey(e){if(58===e)return this._headerKey=this._consumeTokenAsUTF8(),void(this._onByte=this._collectHeaderValue);this._consumeByte(e)}_collectHeaderValue(e){if(13!==e)return 10===e?(this._results.headers.push([this._headerKey,this._consumeTokenAsUTF8()]),this._headerKey=void 0,void(this._onByte=this._collectHeaders)):void this._consumeByte(e)}_setupCollectBody(){const e=this._results.headers.filter((e=>"content-length"===e[0]))[0];e?(this._bodyBytesRemaining=parseInt(e[1],10),this._onByte=this._collectBodyFixedSize):this._onByte=this._collectBodyNullTerminated}_collectBodyNullTerminated(e){0!==e?this._consumeByte(e):this._retrievedBody()}_collectBodyFixedSize(e){0!=this._bodyBytesRemaining--?this._consumeByte(e):this._retrievedBody()}_retrievedBody(){this._results.binaryBody=this._consumeTokenAsRaw();try{this.onFrame(this._results)}catch(e){console.log("Ignoring an exception thrown by a frame handler. Original exception: ",e)}this._initState()}_consumeByte(e){this._token.push(e)}_consumeTokenAsUTF8(){return this._decoder.decode(this._consumeTokenAsRaw())}_consumeTokenAsRaw(){const e=new Uint8Array(this._token);return this._token=[],e}_initState(){this._results={command:void 0,headers:[],binaryBody:void 0},this._token=[],this._headerKey=void 0,this._onByte=this._collectFrame}}var o,c;e.StompSocketState=void 0,(o=e.StompSocketState=e.StompSocketState||(e.StompSocketState={}))[o.CONNECTING=0]="CONNECTING",o[o.OPEN=1]="OPEN",o[o.CLOSING=2]="CLOSING",o[o.CLOSED=3]="CLOSED",e.ActivationState=void 0,(c=e.ActivationState=e.ActivationState||(e.ActivationState={}))[c.ACTIVE=0]="ACTIVE",c[c.DEACTIVATING=1]="DEACTIVATING",c[c.INACTIVE=2]="INACTIVE";class r{constructor(e){this.versions=e}supportedVersions(){return this.versions.join(",")}protocolVersions(){return this.versions.map((e=>`v${e.replace(".","")}.stomp`))}}r.V1_0="1.0",r.V1_1="1.1",r.V1_2="1.2",r.default=new r([r.V1_2,r.V1_1,r.V1_0]);class a{constructor(e,t,s){this._client=e,this._webSocket=t,this._connected=!1,this._serverFrameHandlers={CONNECTED:e=>{this.debug(`connected to server ${e.headers.server}`),this._connected=!0,this._connectedVersion=e.headers.version,this._connectedVersion===r.V1_2&&(this._escapeHeaderValues=!0),this._setupHeartbeat(e.headers),this.onConnect(e)},MESSAGE:e=>{const t=e.headers.subscription,s=this._subscriptions[t]||this.onUnhandledMessage,n=e,i=this,o=this._connectedVersion===r.V1_2?n.headers.ack:n.headers["message-id"];n.ack=(e={})=>i.ack(o,t,e),n.nack=(e={})=>i.nack(o,t,e),s(n)},RECEIPT:e=>{const t=this._receiptWatchers[e.headers["receipt-id"]];t?(t(e),delete this._receiptWatchers[e.headers["receipt-id"]]):this.onUnhandledReceipt(e)},ERROR:e=>{this.onStompError(e)}},this._counter=0,this._subscriptions={},this._receiptWatchers={},this._partialData="",this._escapeHeaderValues=!1,this._lastServerActivityTS=Date.now(),this.debug=s.debug,this.stompVersions=s.stompVersions,this.connectHeaders=s.connectHeaders,this.disconnectHeaders=s.disconnectHeaders,this.heartbeatIncoming=s.heartbeatIncoming,this.heartbeatOutgoing=s.heartbeatOutgoing,this.splitLargeFrames=s.splitLargeFrames,this.maxWebSocketChunkSize=s.maxWebSocketChunkSize,this.forceBinaryWSFrames=s.forceBinaryWSFrames,this.logRawCommunication=s.logRawCommunication,this.appendMissingNULLonIncoming=s.appendMissingNULLonIncoming,this.discardWebsocketOnCommFailure=s.discardWebsocketOnCommFailure,this.onConnect=s.onConnect,this.onDisconnect=s.onDisconnect,this.onStompError=s.onStompError,this.onWebSocketClose=s.onWebSocketClose,this.onWebSocketError=s.onWebSocketError,this.onUnhandledMessage=s.onUnhandledMessage,this.onUnhandledReceipt=s.onUnhandledReceipt,this.onUnhandledFrame=s.onUnhandledFrame}get connectedVersion(){return this._connectedVersion}get connected(){return this._connected}start(){const e=new i((e=>{const t=n.fromRawFrame(e,this._escapeHeaderValues);this.logRawCommunication||this.debug(`<<< ${t}`);(this._serverFrameHandlers[t.command]||this.onUnhandledFrame)(t)}),(()=>{this.debug("<<< PONG")}));this._webSocket.onmessage=t=>{if(this.debug("Received data"),this._lastServerActivityTS=Date.now(),this.logRawCommunication){const e=t.data instanceof ArrayBuffer?(new TextDecoder).decode(t.data):t.data;this.debug(`<<< ${e}`)}e.parseChunk(t.data,this.appendMissingNULLonIncoming)},this._webSocket.onclose=e=>{this.debug(`Connection closed to ${this._webSocket.url}`),this._cleanUp(),this.onWebSocketClose(e)},this._webSocket.onerror=e=>{this.onWebSocketError(e)},this._webSocket.onopen=()=>{const e=Object.assign({},this.connectHeaders);this.debug("Web Socket Opened..."),e["accept-version"]=this.stompVersions.supportedVersions(),e["heart-beat"]=[this.heartbeatOutgoing,this.heartbeatIncoming].join(","),this._transmit({command:"CONNECT",headers:e})}}_setupHeartbeat(s){if(s.version!==r.V1_1&&s.version!==r.V1_2)return;if(!s["heart-beat"])return;const[n,i]=s["heart-beat"].split(",").map((e=>parseInt(e,10)));if(0!==this.heartbeatOutgoing&&0!==i){const s=Math.max(this.heartbeatOutgoing,i);this.debug(`send PING every ${s}ms`),this._pinger=setInterval((()=>{this._webSocket.readyState===e.StompSocketState.OPEN&&(this._webSocket.send(t),this.debug(">>> PING"))}),s)}if(0!==this.heartbeatIncoming&&0!==n){const e=Math.max(this.heartbeatIncoming,n);this.debug(`check PONG every ${e}ms`),this._ponger=setInterval((()=>{const t=Date.now()-this._lastServerActivityTS;t>2*e&&(this.debug(`did not receive server activity for the last ${t}ms`),this._closeOrDiscardWebsocket())}),e)}}_closeOrDiscardWebsocket(){this.discardWebsocketOnCommFailure?(this.debug("Discarding websocket, the underlying socket may linger for a while"),this.discardWebsocket()):(this.debug("Issuing close on the websocket"),this._closeWebsocket())}forceDisconnect(){this._webSocket&&(this._webSocket.readyState!==e.StompSocketState.CONNECTING&&this._webSocket.readyState!==e.StompSocketState.OPEN||this._closeOrDiscardWebsocket())}_closeWebsocket(){this._webSocket.onmessage=()=>{},this._webSocket.close()}discardWebsocket(){var e,t;"function"!=typeof this._webSocket.terminate&&(e=this._webSocket,t=e=>this.debug(e),e.terminate=function(){const s=()=>{};this.onerror=s,this.onmessage=s,this.onopen=s;const n=new Date,i=Math.random().toString().substring(2,8),o=this.onclose;this.onclose=e=>{const s=(new Date).getTime()-n.getTime();t(`Discarded socket (#${i}) closed after ${s}ms, with code/reason: ${e.code}/${e.reason}`)},this.close(),o?.call(e,{code:4001,reason:`Quick discarding socket (#${i}) without waiting for the shutdown sequence.`,wasClean:!1})}),this._webSocket.terminate()}_transmit(e){const{command:t,headers:s,body:i,binaryBody:o,skipContentLengthHeader:c}=e,r=new n({command:t,headers:s,body:i,binaryBody:o,escapeHeaderValues:this._escapeHeaderValues,skipContentLengthHeader:c});let a=r.serialize();if(this.logRawCommunication?this.debug(`>>> ${a}`):this.debug(`>>> ${r}`),this.forceBinaryWSFrames&&"string"==typeof a&&(a=(new TextEncoder).encode(a)),"string"==typeof a&&this.splitLargeFrames){let e=a;for(;e.length>0;){const t=e.substring(0,this.maxWebSocketChunkSize);e=e.substring(this.maxWebSocketChunkSize),this._webSocket.send(t),this.debug(`chunk sent = ${t.length}, remaining = ${e.length}`)}}else this._webSocket.send(a)}dispose(){if(this.connected)try{const e=Object.assign({},this.disconnectHeaders);e.receipt||(e.receipt="close-"+this._counter++),this.watchForReceipt(e.receipt,(e=>{this._closeWebsocket(),this._cleanUp(),this.onDisconnect(e)})),this._transmit({command:"DISCONNECT",headers:e})}catch(e){this.debug(`Ignoring error during disconnect ${e}`)}else this._webSocket.readyState!==e.StompSocketState.CONNECTING&&this._webSocket.readyState!==e.StompSocketState.OPEN||this._closeWebsocket()}_cleanUp(){this._connected=!1,this._pinger&&(clearInterval(this._pinger),this._pinger=void 0),this._ponger&&(clearInterval(this._ponger),this._ponger=void 0)}publish(e){const{destination:t,headers:s,body:n,binaryBody:i,skipContentLengthHeader:o}=e,c=Object.assign({destination:t},s);this._transmit({command:"SEND",headers:c,body:n,binaryBody:i,skipContentLengthHeader:o})}watchForReceipt(e,t){this._receiptWatchers[e]=t}subscribe(e,t,s={}){(s=Object.assign({},s)).id||(s.id="sub-"+this._counter++),s.destination=e,this._subscriptions[s.id]=t,this._transmit({command:"SUBSCRIBE",headers:s});const n=this;return{id:s.id,unsubscribe:e=>n.unsubscribe(s.id,e)}}unsubscribe(e,t={}){t=Object.assign({},t),delete this._subscriptions[e],t.id=e,this._transmit({command:"UNSUBSCRIBE",headers:t})}begin(e){const t=e||"tx-"+this._counter++;this._transmit({command:"BEGIN",headers:{transaction:t}});const s=this;return{id:t,commit(){s.commit(t)},abort(){s.abort(t)}}}commit(e){this._transmit({command:"COMMIT",headers:{transaction:e}})}abort(e){this._transmit({command:"ABORT",headers:{transaction:e}})}ack(e,t,s={}){s=Object.assign({},s),this._connectedVersion===r.V1_2?s.id=e:s["message-id"]=e,s.subscription=t,this._transmit({command:"ACK",headers:s})}nack(e,t,s={}){return s=Object.assign({},s),this._connectedVersion===r.V1_2?s.id=e:s["message-id"]=e,s.subscription=t,this._transmit({command:"NACK",headers:s})}}class h{constructor(t={}){this.stompVersions=r.default,this.connectionTimeout=0,this.reconnectDelay=5e3,this.heartbeatIncoming=1e4,this.heartbeatOutgoing=1e4,this.splitLargeFrames=!1,this.maxWebSocketChunkSize=8192,this.forceBinaryWSFrames=!1,this.appendMissingNULLonIncoming=!1,this.discardWebsocketOnCommFailure=!1,this.state=e.ActivationState.INACTIVE;const s=()=>{};this.debug=s,this.beforeConnect=s,this.onConnect=s,this.onDisconnect=s,this.onUnhandledMessage=s,this.onUnhandledReceipt=s,this.onUnhandledFrame=s,this.onStompError=s,this.onWebSocketClose=s,this.onWebSocketError=s,this.logRawCommunication=!1,this.onChangeState=s,this.connectHeaders={},this._disconnectHeaders={},this.configure(t)}get webSocket(){return this._stompHandler?._webSocket}get disconnectHeaders(){return this._disconnectHeaders}set disconnectHeaders(e){this._disconnectHeaders=e,this._stompHandler&&(this._stompHandler.disconnectHeaders=this._disconnectHeaders)}get connected(){return!!this._stompHandler&&this._stompHandler.connected}get connectedVersion(){return this._stompHandler?this._stompHandler.connectedVersion:void 0}get active(){return this.state===e.ActivationState.ACTIVE}_changeState(e){this.state=e,this.onChangeState(e)}configure(e){Object.assign(this,e)}activate(){if(this.state===e.ActivationState.DEACTIVATING)throw this.debug("Still DEACTIVATING, please await call to deactivate before trying to re-activate"),new Error("Still DEACTIVATING, can not activate now");this.active?this.debug("Already ACTIVE, ignoring request to activate"):(this._changeState(e.ActivationState.ACTIVE),this._connect())}async _connect(){if(this.connected)return void this.debug("STOMP: already connected, nothing to do");if(await this.beforeConnect(),!this.active)return void this.debug("Client has been marked inactive, will not attempt to connect");this.connectionTimeout>0&&(this._connectionWatcher&&clearTimeout(this._connectionWatcher),this._connectionWatcher=setTimeout((()=>{this.connected||(this.debug(`Connection not established in ${this.connectionTimeout}ms, closing socket`),this.forceDisconnect())}),this.connectionTimeout)),this.debug("Opening Web Socket...");const t=this._createWebSocket();this._stompHandler=new a(this,t,{debug:this.debug,stompVersions:this.stompVersions,connectHeaders:this.connectHeaders,disconnectHeaders:this._disconnectHeaders,heartbeatIncoming:this.heartbeatIncoming,heartbeatOutgoing:this.heartbeatOutgoing,splitLargeFrames:this.splitLargeFrames,maxWebSocketChunkSize:this.maxWebSocketChunkSize,forceBinaryWSFrames:this.forceBinaryWSFrames,logRawCommunication:this.logRawCommunication,appendMissingNULLonIncoming:this.appendMissingNULLonIncoming,discardWebsocketOnCommFailure:this.discardWebsocketOnCommFailure,onConnect:e=>{if(this._connectionWatcher&&(clearTimeout(this._connectionWatcher),this._connectionWatcher=void 0),!this.active)return this.debug("STOMP got connected while deactivate was issued, will disconnect now"),void this._disposeStompHandler();this.onConnect(e)},onDisconnect:e=>{this.onDisconnect(e)},onStompError:e=>{this.onStompError(e)},onWebSocketClose:t=>{this._stompHandler=void 0,this.state===e.ActivationState.DEACTIVATING&&this._changeState(e.ActivationState.INACTIVE),this.onWebSocketClose(t),this.active&&this._schedule_reconnect()},onWebSocketError:e=>{this.onWebSocketError(e)},onUnhandledMessage:e=>{this.onUnhandledMessage(e)},onUnhandledReceipt:e=>{this.onUnhandledReceipt(e)},onUnhandledFrame:e=>{this.onUnhandledFrame(e)}}),this._stompHandler.start()}_createWebSocket(){let e;if(this.webSocketFactory)e=this.webSocketFactory();else{if(!this.brokerURL)throw new Error("Either brokerURL or webSocketFactory must be provided");e=new WebSocket(this.brokerURL,this.stompVersions.protocolVersions())}return e.binaryType="arraybuffer",e}_schedule_reconnect(){this.reconnectDelay>0&&(this.debug(`STOMP: scheduling reconnection in ${this.reconnectDelay}ms`),this._reconnector=setTimeout((()=>{this._connect()}),this.reconnectDelay))}async deactivate(t={}){const s=t.force||!1,n=this.active;let i;if(this.state===e.ActivationState.INACTIVE)return this.debug("Already INACTIVE, nothing more to do"),Promise.resolve();if(this._changeState(e.ActivationState.DEACTIVATING),this._reconnector&&(clearTimeout(this._reconnector),this._reconnector=void 0),!this._stompHandler||this.webSocket.readyState===e.StompSocketState.CLOSED)return this._changeState(e.ActivationState.INACTIVE),Promise.resolve();{const e=this._stompHandler.onWebSocketClose;i=new Promise(((t,s)=>{this._stompHandler.onWebSocketClose=s=>{e(s),t()}}))}return s?this._stompHandler?.discardWebsocket():n&&this._disposeStompHandler(),i}forceDisconnect(){this._stompHandler&&this._stompHandler.forceDisconnect()}_disposeStompHandler(){this._stompHandler&&this._stompHandler.dispose()}publish(e){this._checkConnection(),this._stompHandler.publish(e)}_checkConnection(){if(!this.connected)throw new TypeError("There is no underlying STOMP connection")}watchForReceipt(e,t){this._checkConnection(),this._stompHandler.watchForReceipt(e,t)}subscribe(e,t,s={}){return this._checkConnection(),this._stompHandler.subscribe(e,t,s)}unsubscribe(e,t={}){this._checkConnection(),this._stompHandler.unsubscribe(e,t)}begin(e){return this._checkConnection(),this._stompHandler.begin(e)}commit(e){this._checkConnection(),this._stompHandler.commit(e)}abort(e){this._checkConnection(),this._stompHandler.abort(e)}ack(e,t,s={}){this._checkConnection(),this._stompHandler.ack(e,t,s)}nack(e,t,s={}){this._checkConnection(),this._stompHandler.nack(e,t,s)}}class d{constructor(e){this.client=e}get outgoing(){return this.client.heartbeatOutgoing}set outgoing(e){this.client.heartbeatOutgoing=e}get incoming(){return this.client.heartbeatIncoming}set incoming(e){this.client.heartbeatIncoming=e}}class l extends h{constructor(e){super(),this.maxWebSocketFrameSize=16384,this._heartbeatInfo=new d(this),this.reconnect_delay=0,this.webSocketFactory=e,this.debug=(...e)=>{console.log(...e)}}_parseConnect(...e){let t,s,n,i={};if(e.length<2)throw new Error("Connect requires at least 2 arguments");if("function"==typeof e[1])[i,s,n,t]=e;else if(6===e.length)[i.login,i.passcode,s,n,t,i.host]=e;else[i.login,i.passcode,s,n,t]=e;return[i,s,n,t]}connect(...e){const t=this._parseConnect(...e);t[0]&&(this.connectHeaders=t[0]),t[1]&&(this.onConnect=t[1]),t[2]&&(this.onStompError=t[2]),t[3]&&(this.onWebSocketClose=t[3]),super.activate()}disconnect(e,t={}){e&&(this.onDisconnect=e),this.disconnectHeaders=t,super.deactivate()}send(e,t={},s=""){const n=!1===(t=Object.assign({},t))["content-length"];n&&delete t["content-length"],this.publish({destination:e,headers:t,body:s,skipContentLengthHeader:n})}set reconnect_delay(e){this.reconnectDelay=e}get ws(){return this.webSocket}get version(){return this.connectedVersion}get onreceive(){return this.onUnhandledMessage}set onreceive(e){this.onUnhandledMessage=e}get onreceipt(){return this.onUnhandledReceipt}set onreceipt(e){this.onUnhandledReceipt=e}get heartbeat(){return this._heartbeatInfo}set heartbeat(e){this.heartbeatIncoming=e.incoming,this.heartbeatOutgoing=e.outgoing}}class m{static client(e,t){null==t&&(t=r.default.protocolVersions());return new l((()=>new(m.WebSocketClass||WebSocket)(e,t)))}static over(e){let t;return"function"==typeof e?t=e:(console.warn("Stomp.over did not receive a factory, auto reconnect will not work. Please see https://stomp-js.github.io/api-docs/latest/classes/Stomp.html#over"),t=()=>e),new l(t)}}m.WebSocketClass=null,e.Client=h,e.CompatClient=l,e.FrameImpl=n,e.Parser=i,e.Stomp=m,e.StompConfig=class{},e.StompHeaders=class{},e.Versions=r}));
@@ -0,0 +1,84 @@
1
+ 'use strict';
2
+
3
+ var net = require('net');
4
+
5
+ /**
6
+ * Possible states for the IStompSocket
7
+ */
8
+ var StompSocketState;
9
+ (function (StompSocketState) {
10
+ StompSocketState[StompSocketState["CONNECTING"] = 0] = "CONNECTING";
11
+ StompSocketState[StompSocketState["OPEN"] = 1] = "OPEN";
12
+ StompSocketState[StompSocketState["CLOSING"] = 2] = "CLOSING";
13
+ StompSocketState[StompSocketState["CLOSED"] = 3] = "CLOSED";
14
+ })(StompSocketState = StompSocketState || (StompSocketState = {}));
15
+ /**
16
+ * Possible activation state
17
+ */
18
+ var ActivationState;
19
+ (function (ActivationState) {
20
+ ActivationState[ActivationState["ACTIVE"] = 0] = "ACTIVE";
21
+ ActivationState[ActivationState["DEACTIVATING"] = 1] = "DEACTIVATING";
22
+ ActivationState[ActivationState["INACTIVE"] = 2] = "INACTIVE";
23
+ })(ActivationState = ActivationState || (ActivationState = {}));
24
+
25
+ /**
26
+ * Wrapper for a TCP socket to make it behave similar to the WebSocket interface
27
+ */
28
+ class TCPWrapper {
29
+ constructor(host, port) {
30
+ this.url = `tcp://${host}/${port}/`;
31
+ this.readyState = StompSocketState.CONNECTING;
32
+ this.socket = net.createConnection(port, host, () => {
33
+ if (typeof this.onopen === 'function') {
34
+ this.readyState = StompSocketState.OPEN;
35
+ this.onopen();
36
+ }
37
+ });
38
+ this.socket.on('data', ev => {
39
+ if (typeof this.onmessage === 'function') {
40
+ this.onmessage({ data: ev });
41
+ }
42
+ });
43
+ this.socket.on('close', hadError => {
44
+ this.readyState = StompSocketState.CLOSED;
45
+ if (typeof this.onclose === 'function') {
46
+ if (this._closeEvtOnTermination) {
47
+ this.onclose(this._closeEvtOnTermination);
48
+ }
49
+ else {
50
+ this.onclose({ wasClean: !hadError, type: 'CloseEvent', code: 1000 });
51
+ }
52
+ }
53
+ });
54
+ this.socket.on('error', ev => {
55
+ if (typeof this.onerror === 'function') {
56
+ this.onerror({ type: 'Error', error: 100, message: ev });
57
+ }
58
+ });
59
+ }
60
+ send(data) {
61
+ if (typeof data === 'string') {
62
+ this.socket.write(data);
63
+ }
64
+ else {
65
+ this.socket.write(new Uint8Array(data));
66
+ }
67
+ }
68
+ close(code, reason) {
69
+ this.readyState = StompSocketState.CLOSING;
70
+ this.socket.end();
71
+ }
72
+ terminate() {
73
+ this.readyState = StompSocketState.CLOSING;
74
+ this._closeEvtOnTermination = {
75
+ wasClean: false,
76
+ type: 'CloseEvent',
77
+ code: 4001,
78
+ };
79
+ this.socket.destroy();
80
+ }
81
+ }
82
+
83
+ exports.TCPWrapper = TCPWrapper;
84
+ //# sourceMappingURL=tcp-wrapper.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tcp-wrapper.cjs","sources":["../src/types.ts","../src/tcp-wrapper.ts"],"sourcesContent":[null,null],"names":["createConnection"],"mappings":";;;;AA4IA;;AAEG;AACH,IAAY,gBAKX,CAAA;AALD,CAAA,UAAY,gBAAgB,EAAA;AAC1B,IAAA,gBAAA,CAAA,gBAAA,CAAA,YAAA,CAAA,GAAA,CAAA,CAAA,GAAA,YAAU,CAAA;AACV,IAAA,gBAAA,CAAA,gBAAA,CAAA,MAAA,CAAA,GAAA,CAAA,CAAA,GAAA,MAAI,CAAA;AACJ,IAAA,gBAAA,CAAA,gBAAA,CAAA,SAAA,CAAA,GAAA,CAAA,CAAA,GAAA,SAAO,CAAA;AACP,IAAA,gBAAA,CAAA,gBAAA,CAAA,QAAA,CAAA,GAAA,CAAA,CAAA,GAAA,QAAM,CAAA;AACR,CAAC,EALW,gBAAgB,GAAhB,gBAAgB,KAAhB,gBAAgB,GAK3B,EAAA,CAAA,CAAA,CAAA;AAED;;AAEG;AACH,IAAY,eAIX,CAAA;AAJD,CAAA,UAAY,eAAe,EAAA;AACzB,IAAA,eAAA,CAAA,eAAA,CAAA,QAAA,CAAA,GAAA,CAAA,CAAA,GAAA,QAAM,CAAA;AACN,IAAA,eAAA,CAAA,eAAA,CAAA,cAAA,CAAA,GAAA,CAAA,CAAA,GAAA,cAAY,CAAA;AACZ,IAAA,eAAA,CAAA,eAAA,CAAA,UAAA,CAAA,GAAA,CAAA,CAAA,GAAA,UAAQ,CAAA;AACV,CAAC,EAJW,eAAe,GAAf,eAAe,KAAf,eAAe,GAI1B,EAAA,CAAA,CAAA;;ACtJD;;AAEG;MACU,UAAU,CAAA;IAarB,WAAY,CAAA,IAAY,EAAE,IAAY,EAAA;QAGpC,IAAI,CAAC,GAAG,GAAG,CAAA,MAAA,EAAS,IAAI,CAAI,CAAA,EAAA,IAAI,GAAG,CAAC;AACpC,QAAA,IAAI,CAAC,UAAU,GAAG,gBAAgB,CAAC,UAAU,CAAC;QAE9C,IAAI,CAAC,MAAM,GAAGA,oBAAgB,CAAC,IAAI,EAAE,IAAI,EAAE,MAAK;AAC9C,YAAA,IAAI,OAAO,IAAI,CAAC,MAAM,KAAK,UAAU,EAAE;AACrC,gBAAA,IAAI,CAAC,UAAU,GAAG,gBAAgB,CAAC,IAAI,CAAC;gBACxC,IAAI,CAAC,MAAM,EAAE,CAAC;AACf,aAAA;AACH,SAAC,CAAC,CAAC;QAEH,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,EAAE,IAAG;AAC1B,YAAA,IAAI,OAAO,IAAI,CAAC,SAAS,KAAK,UAAU,EAAE;gBACxC,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,CAAC;AAC9B,aAAA;AACH,SAAC,CAAC,CAAC;QAEH,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,QAAQ,IAAG;AACjC,YAAA,IAAI,CAAC,UAAU,GAAG,gBAAgB,CAAC,MAAM,CAAC;AAC1C,YAAA,IAAI,OAAO,IAAI,CAAC,OAAO,KAAK,UAAU,EAAE;gBACtC,IAAI,IAAI,CAAC,sBAAsB,EAAE;AAC/B,oBAAA,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC;AAC3C,iBAAA;AAAM,qBAAA;AACL,oBAAA,IAAI,CAAC,OAAO,CAAC,EAAE,QAAQ,EAAE,CAAC,QAAQ,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;AACvE,iBAAA;AACF,aAAA;AACH,SAAC,CAAC,CAAC;QAEH,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,EAAE,IAAG;AAC3B,YAAA,IAAI,OAAO,IAAI,CAAC,OAAO,KAAK,UAAU,EAAE;AACtC,gBAAA,IAAI,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,CAAC;AAC1D,aAAA;AACH,SAAC,CAAC,CAAC;KACJ;AAEM,IAAA,IAAI,CAAC,IAA0B,EAAA;AACpC,QAAA,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;AAC5B,YAAA,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AACzB,SAAA;AAAM,aAAA;YACL,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC;AACzC,SAAA;KACF;IAEM,KAAK,CAAC,IAAa,EAAE,MAAe,EAAA;AACzC,QAAA,IAAI,CAAC,UAAU,GAAG,gBAAgB,CAAC,OAAO,CAAC;AAC3C,QAAA,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC;KACnB;IAEM,SAAS,GAAA;AACd,QAAA,IAAI,CAAC,UAAU,GAAG,gBAAgB,CAAC,OAAO,CAAC;QAC3C,IAAI,CAAC,sBAAsB,GAAG;AAC5B,YAAA,QAAQ,EAAE,KAAK;AACf,YAAA,IAAI,EAAE,YAAY;AAClB,YAAA,IAAI,EAAE,IAAI;SACX,CAAC;AACF,QAAA,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;KACvB;AACF;;;;"}
package/esm6/client.d.ts CHANGED
@@ -22,12 +22,12 @@ export declare class Client {
22
22
  */
23
23
  brokerURL: string | undefined;
24
24
  /**
25
- * STOMP versions to attempt during STOMP handshake. By default versions `1.0`, `1.1`, and `1.2` are attempted.
25
+ * STOMP versions to attempt during STOMP handshake. By default, versions `1.2`, `1.1`, and `1.0` are attempted.
26
26
  *
27
27
  * Example:
28
28
  * ```javascript
29
- * // Try only versions 1.0 and 1.1
30
- * client.stompVersions = new Versions(['1.0', '1.1'])
29
+ * // Try only versions 1.1 and 1.0
30
+ * client.stompVersions = new Versions(['1.1', '1.0'])
31
31
  * ```
32
32
  */
33
33
  stompVersions: Versions;
@@ -55,7 +55,7 @@ export declare class Client {
55
55
  webSocketFactory: (() => IStompSocket) | undefined;
56
56
  /**
57
57
  * Will retry if Stomp connection is not established in specified milliseconds.
58
- * Default 0, which implies wait for ever.
58
+ * Default 0, which switches off automatic reconnection.
59
59
  */
60
60
  connectionTimeout: number;
61
61
  private _connectionWatcher;
@@ -72,13 +72,13 @@ export declare class Client {
72
72
  */
73
73
  heartbeatOutgoing: number;
74
74
  /**
75
- * This switches on a non standard behavior while sending WebSocket packets.
75
+ * This switches on a non-standard behavior while sending WebSocket packets.
76
76
  * It splits larger (text) packets into chunks of [maxWebSocketChunkSize]{@link Client#maxWebSocketChunkSize}.
77
- * Only Java Spring brokers seems to use this mode.
77
+ * Only Java Spring brokers seem to support this mode.
78
78
  *
79
79
  * WebSockets, by itself, split large (text) packets,
80
80
  * so it is not needed with a truly compliant STOMP/WebSocket broker.
81
- * Actually setting it for such broker will cause large messages to fail.
81
+ * Setting it for such a broker will cause large messages to fail.
82
82
  *
83
83
  * `false` by default.
84
84
  *
@@ -142,30 +142,30 @@ export declare class Client {
142
142
  * Prefer using [Client#watchForReceipt]{@link Client#watchForReceipt}. See
143
143
  * [Client#watchForReceipt]{@link Client#watchForReceipt} for examples.
144
144
  *
145
- * The actual {@link FrameImpl} will be passed as parameter to the callback.
145
+ * The actual {@link IFrame} will be passed as parameter to the callback.
146
146
  */
147
147
  onUnhandledReceipt: frameCallbackType;
148
148
  /**
149
- * Will be invoked if {@link FrameImpl} of unknown type is received from the STOMP broker.
149
+ * Will be invoked if {@link IFrame} of an unknown type is received from the STOMP broker.
150
150
  *
151
151
  * The actual {@link IFrame} will be passed as parameter to the callback.
152
152
  */
153
153
  onUnhandledFrame: frameCallbackType;
154
154
  /**
155
- * `true` if there is a active connection with STOMP Broker
155
+ * `true` if there is an active connection to STOMP Broker
156
156
  */
157
157
  get connected(): boolean;
158
158
  /**
159
- * Callback, invoked on before a connection connection to the STOMP broker.
159
+ * Callback, invoked on before a connection to the STOMP broker.
160
160
  *
161
- * You can change options on the client, which will impact the immediate connect.
161
+ * You can change options on the client, which will impact the immediate connecting.
162
162
  * It is valid to call [Client#decativate]{@link Client#deactivate} in this callback.
163
163
  *
164
164
  * As of version 5.1, this callback can be
165
165
  * [async](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)
166
166
  * (i.e., it can return a
167
167
  * [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)).
168
- * In that case connect will be called only after the Promise is resolved.
168
+ * In that case, connect will be called only after the Promise is resolved.
169
169
  * This can be used to reliably fetch credentials, access token etc. from some other service
170
170
  * in an asynchronous way.
171
171
  */
@@ -173,7 +173,7 @@ export declare class Client {
173
173
  /**
174
174
  * Callback, invoked on every successful connection to the STOMP broker.
175
175
  *
176
- * The actual {@link FrameImpl} will be passed as parameter to the callback.
176
+ * The actual {@link IFrame} will be passed as parameter to the callback.
177
177
  * Sometimes clients will like to use headers from this frame.
178
178
  */
179
179
  onConnect: frameCallbackType;
@@ -181,10 +181,10 @@ export declare class Client {
181
181
  * Callback, invoked on every successful disconnection from the STOMP broker. It will not be invoked if
182
182
  * the STOMP broker disconnected due to an error.
183
183
  *
184
- * The actual Receipt {@link FrameImpl} acknowledging the DISCONNECT will be passed as parameter to the callback.
184
+ * The actual Receipt {@link IFrame} acknowledging the DISCONNECT will be passed as parameter to the callback.
185
185
  *
186
186
  * The way STOMP protocol is designed, the connection may close/terminate without the client
187
- * receiving the Receipt {@link FrameImpl} acknowledging the DISCONNECT.
187
+ * receiving the Receipt {@link IFrame} acknowledging the DISCONNECT.
188
188
  * You might find [Client#onWebSocketClose]{@link Client#onWebSocketClose} more appropriate to watch
189
189
  * STOMP broker disconnects.
190
190
  */
@@ -215,7 +215,7 @@ export declare class Client {
215
215
  * Set it to log the actual raw communication with the broker.
216
216
  * When unset, it logs headers of the parsed frames.
217
217
  *
218
- * Change in this effects from next broker reconnect.
218
+ * Changes effect from the next broker reconnect.
219
219
  *
220
220
  * **Caution: this assumes that frames only have valid UTF8 strings.**
221
221
  */
@@ -229,15 +229,18 @@ export declare class Client {
229
229
  * };
230
230
  * ```
231
231
  *
232
- * Currently this method does not support levels of log. Be aware that the output can be quite verbose
232
+ * Currently this method does not support levels of log. Be aware that the
233
+ * output can be quite verbose
233
234
  * and may contain sensitive information (like passwords, tokens etc.).
234
235
  */
235
236
  debug: debugFnType;
236
237
  /**
237
238
  * Browsers do not immediately close WebSockets when `.close` is issued.
238
- * This may cause reconnection to take a longer on certain type of failures.
239
- * In case of incoming heartbeat failure, this experimental flag instructs the library
240
- * to discard the socket immediately (even before it is actually closed).
239
+ * This may cause reconnection to take a significantly long time in case
240
+ * of some types of failures.
241
+ * In case of incoming heartbeat failure, this experimental flag instructs
242
+ * the library to discard the socket immediately
243
+ * (even before it is actually closed).
241
244
  */
242
245
  discardWebsocketOnCommFailure: boolean;
243
246
  /**
@@ -252,7 +255,7 @@ export declare class Client {
252
255
  /**
253
256
  * It will be called on state change.
254
257
  *
255
- * When deactivating it may go from ACTIVE to INACTIVE without entering DEACTIVATING.
258
+ * When deactivating, it may go from ACTIVE to INACTIVE without entering DEACTIVATING.
256
259
  */
257
260
  onChangeState: (state: ActivationState) => void;
258
261
  private _changeState;
@@ -260,7 +263,7 @@ export declare class Client {
260
263
  * Activation state.
261
264
  *
262
265
  * It will usually be ACTIVE or INACTIVE.
263
- * When deactivating it may go from ACTIVE to INACTIVE without entering DEACTIVATING.
266
+ * When deactivating, it may go from ACTIVE to INACTIVE without entering DEACTIVATING.
264
267
  */
265
268
  state: ActivationState;
266
269
  private _reconnector;
@@ -297,7 +300,8 @@ export declare class Client {
297
300
  *
298
301
  * Experimental: pass `force: true` to immediately discard the underlying connection.
299
302
  * This mode will skip both the STOMP and the Websocket shutdown sequences.
300
- * In some cases, browsers take a long time in the Websocket shutdown if the underlying connection had gone stale.
303
+ * In some cases, browsers take a long time in the Websocket shutdown
304
+ * if the underlying connection had gone stale.
301
305
  * Using this mode can speed up.
302
306
  * When this mode is used, the actual Websocket may linger for a while
303
307
  * and the broker may not realize that the connection is no longer in use.
@@ -310,7 +314,7 @@ export declare class Client {
310
314
  }): Promise<void>;
311
315
  /**
312
316
  * Force disconnect if there is an active connection by directly closing the underlying WebSocket.
313
- * This is different than a normal disconnect where a DISCONNECT sequence is carried out with the broker.
317
+ * This is different from a normal disconnect where a DISCONNECT sequence is carried out with the broker.
314
318
  * After forcing disconnect, automatic reconnect will be attempted.
315
319
  * To stop further reconnects call [Client#deactivate]{@link Client#deactivate} as well.
316
320
  */
@@ -320,22 +324,22 @@ export declare class Client {
320
324
  * Send a message to a named destination. Refer to your STOMP broker documentation for types
321
325
  * and naming of destinations.
322
326
  *
323
- * STOMP protocol specifies and suggests some headers and also allows broker specific headers.
327
+ * STOMP protocol specifies and suggests some headers and also allows broker-specific headers.
324
328
  *
325
329
  * `body` must be String.
326
330
  * You will need to covert the payload to string in case it is not string (e.g. JSON).
327
331
  *
328
- * To send a binary message body use binaryBody parameter. It should be a
332
+ * To send a binary message body, use `binaryBody` parameter. It should be a
329
333
  * [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array).
330
334
  * Sometimes brokers may not support binary frames out of the box.
331
335
  * Please check your broker documentation.
332
336
  *
333
337
  * `content-length` header is automatically added to the STOMP Frame sent to the broker.
334
338
  * Set `skipContentLengthHeader` to indicate that `content-length` header should not be added.
335
- * For binary messages `content-length` header is always added.
339
+ * For binary messages, `content-length` header is always added.
336
340
  *
337
- * Caution: The broker will, most likely, report an error and disconnect if message body has NULL octet(s)
338
- * and `content-length` header is missing.
341
+ * Caution: The broker will, most likely, report an error and disconnect
342
+ * if the message body has NULL octet(s) and `content-length` header is missing.
339
343
  *
340
344
  * ```javascript
341
345
  * client.publish({destination: "/queue/test", headers: {priority: 9}, body: "Hello, STOMP"});
@@ -357,16 +361,16 @@ export declare class Client {
357
361
  /**
358
362
  * STOMP brokers may carry out operation asynchronously and allow requesting for acknowledgement.
359
363
  * To request an acknowledgement, a `receipt` header needs to be sent with the actual request.
360
- * The value (say receipt-id) for this header needs to be unique for each use. Typically a sequence, a UUID, a
361
- * random number or a combination may be used.
364
+ * The value (say receipt-id) for this header needs to be unique for each use.
365
+ * Typically, a sequence, a UUID, a random number or a combination may be used.
362
366
  *
363
367
  * A complaint broker will send a RECEIPT frame when an operation has actually been completed.
364
- * The operation needs to be matched based in the value of the receipt-id.
368
+ * The operation needs to be matched based on the value of the receipt-id.
365
369
  *
366
- * This method allow watching for a receipt and invoke the callback
367
- * when corresponding receipt has been received.
370
+ * This method allows watching for a receipt and invoking the callback
371
+ * when the corresponding receipt has been received.
368
372
  *
369
- * The actual {@link FrameImpl} will be passed as parameter to the callback.
373
+ * The actual {@link IFrame} will be passed as parameter to the callback.
370
374
  *
371
375
  * Example:
372
376
  * ```javascript
@@ -391,11 +395,11 @@ export declare class Client {
391
395
  */
392
396
  watchForReceipt(receiptId: string, callback: frameCallbackType): void;
393
397
  /**
394
- * Subscribe to a STOMP Broker location. The callback will be invoked for each received message with
395
- * the {@link IMessage} as argument.
398
+ * Subscribe to a STOMP Broker location. The callback will be invoked for each
399
+ * received message with the {@link IMessage} as argument.
396
400
  *
397
- * Note: The library will generate an unique ID if there is none provided in the headers.
398
- * To use your own ID, pass it using the headers argument.
401
+ * Note: The library will generate a unique ID if there is none provided in the headers.
402
+ * To use your own ID, pass it using the `headers` argument.
399
403
  *
400
404
  * ```javascript
401
405
  * callback = function(message) {
@@ -425,7 +429,7 @@ export declare class Client {
425
429
  * subscription.unsubscribe();
426
430
  * ```
427
431
  *
428
- * See: http://stomp.github.com/stomp-specification-1.2.html#UNSUBSCRIBE UNSUBSCRIBE Frame
432
+ * See: https://stomp.github.com/stomp-specification-1.2.html#UNSUBSCRIBE UNSUBSCRIBE Frame
429
433
  */
430
434
  unsubscribe(id: string, headers?: StompHeaders): void;
431
435
  /**
package/esm6/client.js CHANGED
@@ -12,18 +12,18 @@ export class Client {
12
12
  */
13
13
  constructor(conf = {}) {
14
14
  /**
15
- * STOMP versions to attempt during STOMP handshake. By default versions `1.0`, `1.1`, and `1.2` are attempted.
15
+ * STOMP versions to attempt during STOMP handshake. By default, versions `1.2`, `1.1`, and `1.0` are attempted.
16
16
  *
17
17
  * Example:
18
18
  * ```javascript
19
- * // Try only versions 1.0 and 1.1
20
- * client.stompVersions = new Versions(['1.0', '1.1'])
19
+ * // Try only versions 1.1 and 1.0
20
+ * client.stompVersions = new Versions(['1.1', '1.0'])
21
21
  * ```
22
22
  */
23
23
  this.stompVersions = Versions.default;
24
24
  /**
25
25
  * Will retry if Stomp connection is not established in specified milliseconds.
26
- * Default 0, which implies wait for ever.
26
+ * Default 0, which switches off automatic reconnection.
27
27
  */
28
28
  this.connectionTimeout = 0;
29
29
  /**
@@ -39,13 +39,13 @@ export class Client {
39
39
  */
40
40
  this.heartbeatOutgoing = 10000;
41
41
  /**
42
- * This switches on a non standard behavior while sending WebSocket packets.
42
+ * This switches on a non-standard behavior while sending WebSocket packets.
43
43
  * It splits larger (text) packets into chunks of [maxWebSocketChunkSize]{@link Client#maxWebSocketChunkSize}.
44
- * Only Java Spring brokers seems to use this mode.
44
+ * Only Java Spring brokers seem to support this mode.
45
45
  *
46
46
  * WebSockets, by itself, split large (text) packets,
47
47
  * so it is not needed with a truly compliant STOMP/WebSocket broker.
48
- * Actually setting it for such broker will cause large messages to fail.
48
+ * Setting it for such a broker will cause large messages to fail.
49
49
  *
50
50
  * `false` by default.
51
51
  *
@@ -79,19 +79,21 @@ export class Client {
79
79
  this.appendMissingNULLonIncoming = false;
80
80
  /**
81
81
  * Browsers do not immediately close WebSockets when `.close` is issued.
82
- * This may cause reconnection to take a longer on certain type of failures.
83
- * In case of incoming heartbeat failure, this experimental flag instructs the library
84
- * to discard the socket immediately (even before it is actually closed).
82
+ * This may cause reconnection to take a significantly long time in case
83
+ * of some types of failures.
84
+ * In case of incoming heartbeat failure, this experimental flag instructs
85
+ * the library to discard the socket immediately
86
+ * (even before it is actually closed).
85
87
  */
86
88
  this.discardWebsocketOnCommFailure = false;
87
89
  /**
88
90
  * Activation state.
89
91
  *
90
92
  * It will usually be ACTIVE or INACTIVE.
91
- * When deactivating it may go from ACTIVE to INACTIVE without entering DEACTIVATING.
93
+ * When deactivating, it may go from ACTIVE to INACTIVE without entering DEACTIVATING.
92
94
  */
93
95
  this.state = ActivationState.INACTIVE;
94
- // Dummy callbacks
96
+ // No op callbacks
95
97
  const noOp = () => { };
96
98
  this.debug = noOp;
97
99
  this.beforeConnect = noOp;
@@ -130,7 +132,7 @@ export class Client {
130
132
  }
131
133
  }
132
134
  /**
133
- * `true` if there is a active connection with STOMP Broker
135
+ * `true` if there is an active connection to STOMP Broker
134
136
  */
135
137
  get connected() {
136
138
  return !!this._stompHandler && this._stompHandler.connected;
@@ -302,7 +304,8 @@ export class Client {
302
304
  *
303
305
  * Experimental: pass `force: true` to immediately discard the underlying connection.
304
306
  * This mode will skip both the STOMP and the Websocket shutdown sequences.
305
- * In some cases, browsers take a long time in the Websocket shutdown if the underlying connection had gone stale.
307
+ * In some cases, browsers take a long time in the Websocket shutdown
308
+ * if the underlying connection had gone stale.
306
309
  * Using this mode can speed up.
307
310
  * When this mode is used, the actual Websocket may linger for a while
308
311
  * and the broker may not realize that the connection is no longer in use.
@@ -352,7 +355,7 @@ export class Client {
352
355
  }
353
356
  /**
354
357
  * Force disconnect if there is an active connection by directly closing the underlying WebSocket.
355
- * This is different than a normal disconnect where a DISCONNECT sequence is carried out with the broker.
358
+ * This is different from a normal disconnect where a DISCONNECT sequence is carried out with the broker.
356
359
  * After forcing disconnect, automatic reconnect will be attempted.
357
360
  * To stop further reconnects call [Client#deactivate]{@link Client#deactivate} as well.
358
361
  */
@@ -371,22 +374,22 @@ export class Client {
371
374
  * Send a message to a named destination. Refer to your STOMP broker documentation for types
372
375
  * and naming of destinations.
373
376
  *
374
- * STOMP protocol specifies and suggests some headers and also allows broker specific headers.
377
+ * STOMP protocol specifies and suggests some headers and also allows broker-specific headers.
375
378
  *
376
379
  * `body` must be String.
377
380
  * You will need to covert the payload to string in case it is not string (e.g. JSON).
378
381
  *
379
- * To send a binary message body use binaryBody parameter. It should be a
382
+ * To send a binary message body, use `binaryBody` parameter. It should be a
380
383
  * [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array).
381
384
  * Sometimes brokers may not support binary frames out of the box.
382
385
  * Please check your broker documentation.
383
386
  *
384
387
  * `content-length` header is automatically added to the STOMP Frame sent to the broker.
385
388
  * Set `skipContentLengthHeader` to indicate that `content-length` header should not be added.
386
- * For binary messages `content-length` header is always added.
389
+ * For binary messages, `content-length` header is always added.
387
390
  *
388
- * Caution: The broker will, most likely, report an error and disconnect if message body has NULL octet(s)
389
- * and `content-length` header is missing.
391
+ * Caution: The broker will, most likely, report an error and disconnect
392
+ * if the message body has NULL octet(s) and `content-length` header is missing.
390
393
  *
391
394
  * ```javascript
392
395
  * client.publish({destination: "/queue/test", headers: {priority: 9}, body: "Hello, STOMP"});
@@ -416,16 +419,16 @@ export class Client {
416
419
  /**
417
420
  * STOMP brokers may carry out operation asynchronously and allow requesting for acknowledgement.
418
421
  * To request an acknowledgement, a `receipt` header needs to be sent with the actual request.
419
- * The value (say receipt-id) for this header needs to be unique for each use. Typically a sequence, a UUID, a
420
- * random number or a combination may be used.
422
+ * The value (say receipt-id) for this header needs to be unique for each use.
423
+ * Typically, a sequence, a UUID, a random number or a combination may be used.
421
424
  *
422
425
  * A complaint broker will send a RECEIPT frame when an operation has actually been completed.
423
- * The operation needs to be matched based in the value of the receipt-id.
426
+ * The operation needs to be matched based on the value of the receipt-id.
424
427
  *
425
- * This method allow watching for a receipt and invoke the callback
426
- * when corresponding receipt has been received.
428
+ * This method allows watching for a receipt and invoking the callback
429
+ * when the corresponding receipt has been received.
427
430
  *
428
- * The actual {@link FrameImpl} will be passed as parameter to the callback.
431
+ * The actual {@link IFrame} will be passed as parameter to the callback.
429
432
  *
430
433
  * Example:
431
434
  * ```javascript
@@ -454,11 +457,11 @@ export class Client {
454
457
  this._stompHandler.watchForReceipt(receiptId, callback);
455
458
  }
456
459
  /**
457
- * Subscribe to a STOMP Broker location. The callback will be invoked for each received message with
458
- * the {@link IMessage} as argument.
460
+ * Subscribe to a STOMP Broker location. The callback will be invoked for each
461
+ * received message with the {@link IMessage} as argument.
459
462
  *
460
- * Note: The library will generate an unique ID if there is none provided in the headers.
461
- * To use your own ID, pass it using the headers argument.
463
+ * Note: The library will generate a unique ID if there is none provided in the headers.
464
+ * To use your own ID, pass it using the `headers` argument.
462
465
  *
463
466
  * ```javascript
464
467
  * callback = function(message) {
@@ -492,7 +495,7 @@ export class Client {
492
495
  * subscription.unsubscribe();
493
496
  * ```
494
497
  *
495
- * See: http://stomp.github.com/stomp-specification-1.2.html#UNSUBSCRIBE UNSUBSCRIBE Frame
498
+ * See: https://stomp.github.com/stomp-specification-1.2.html#UNSUBSCRIBE UNSUBSCRIBE Frame
496
499
  */
497
500
  unsubscribe(id, headers = {}) {
498
501
  this._checkConnection();