@ndustrial/contxt-sdk 5.4.0 → 5.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,10 +1,18 @@
1
- ## [v5.3.1](http://github.com/ndustrialio/contxt-sdk-js/tree/v4.3.1) (2022-03-17)
1
+ ## [v5.5.0](http://github.com/ndustrialio/contxt-sdk-js/tree/v5.5.0) (2023-06-14)
2
+
3
+ **Changed**
4
+
5
+ - adds onClose and onError callbacks to Message Bus connect
6
+ - custom message bus error callbacks are no longer overwritten
7
+ - adds app and contxt lib version as API requests User-Agent header
8
+
9
+ ## [v5.4.0](http://github.com/ndustrialio/contxt-sdk-js/tree/v5.4.0) (2022-03-17)
2
10
 
3
11
  **Changed**
4
12
 
5
13
  - exposed `peek` operation on message bus channel for a given subscription
6
14
 
7
- ## [v5.3.0](http://github.com/ndustrialio/contxt-sdk-js/tree/v4.3.1) (2022-03-17)
15
+ ## [v5.3.0](http://github.com/ndustrialio/contxt-sdk-js/tree/v5.3.0) (2022-03-17)
8
16
 
9
17
  **Changed**
10
18
 
package/esm/bus/index.js CHANGED
@@ -88,13 +88,19 @@ var Bus = function () {
88
88
  * If a connection already exists for that organization id, the connection is returned, otherwise a new connection is created and returned.
89
89
  *
90
90
  * @param {string} organizationId UUID corresponding with an organization
91
+ * @param {function} onClose optional callback to be executed when the connection is closed
92
+ * @param {function} onError optional callback to be executed when the connection encounters an error
91
93
  *
92
94
  * @returns {Promise}
93
95
  * @fulfill {WebSocketConnection}
94
96
  * @reject {errorEvent} The error event
95
97
  *
96
98
  * @example
97
- * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')
99
+ * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d', (orgId, evt) => {
100
+ * console.log(`connection closed: ${evt}`);
101
+ * }, (orgId, evt) => {
102
+ * console.log(`connection error: ${evt}`);
103
+ * })
98
104
  * .then((webSocket) => {
99
105
  * console.log(webSocket);
100
106
  * })
@@ -106,7 +112,7 @@ var Bus = function () {
106
112
 
107
113
  _createClass(Bus, [{
108
114
  key: 'connect',
109
- value: function connect(organizationId) {
115
+ value: function connect(organizationId, onClose, onError) {
110
116
  var _this = this;
111
117
 
112
118
  return new Promise(function (resolve, reject) {
@@ -127,13 +133,31 @@ var Bus = function () {
127
133
  resolve(_this._webSockets[organizationId]);
128
134
  };
129
135
 
130
- ws.onclose = function (event) {
136
+ ws.addEventListener("close", function (event) {
131
137
  _this._webSockets[organizationId] = null;
132
- };
138
+ if (onClose) {
139
+ try {
140
+ onClose(organizationId, event);
141
+ } catch (ex) {
142
+ console.log('Message Bus Error calling onClose callback: ', ex);
143
+ }
144
+ }
145
+ });
133
146
 
134
- ws.onerror = function (errorEvent) {
135
- reject(errorEvent);
136
- };
147
+ ws.addEventListener("error", function (errorEvent) {
148
+ var connected = _this._webSockets[organizationId] != null;
149
+ _this._webSockets[organizationId] = null;
150
+ if (!connected) {
151
+ reject(errorEvent);
152
+ }
153
+ if (onError) {
154
+ try {
155
+ onError(organizationId, errorEvent);
156
+ } catch (ex) {
157
+ console.log('Message Bus Error calling onError callback: ', ex);
158
+ }
159
+ }
160
+ });
137
161
  }).catch(function (err) {
138
162
  reject(err);
139
163
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["bus/index.js"],"names":["WebSocket","Channels","WebSocketConnection","defaultBusConfig","autoAcknowledge","Bus","sdk","request","config","baseUrl","audiences","bus","host","baseWebSocketUrl","webSocket","_baseWebSocketUrl","_baseUrl","_request","_sdk","_webSockets","_config","Object","assign","channels","organizationId","Promise","resolve","reject","auth","getCurrentApiToken","then","apiToken","ws","headers","Authorization","onopen","event","onclose","onerror","errorEvent","catch","err"],"mappings":";;;;AAAA,OAAOA,SAAP,MAAsB,IAAtB;;AAEA,OAAOC,QAAP,MAAqB,YAArB;AACA,OAAOC,mBAAP,MAAgC,uBAAhC;;AAEA;;;;;;;;;;;;;;;;;;;;;;;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ACrB,kBAAKjB,WAAL,CAAiBK,cAAjB,IAAmC,IAAItB,mBAAJ,CACjC8B,EADiC,EAEjCR,cAFiC,EAGjC,MAAKJ,OAAL,CAAahB,eAHoB,CAAnC;;AAMAsB,oBAAQ,MAAKP,WAAL,CAAiBK,cAAjB,CAAR;AACD,WARD;;AAUAQ,aAAGK,OAAH,GAAa,UAACD,KAAD,EAAW;AACtB,kBAAKjB,WAAL,CAAiBK,cAAjB,IAAmC,IAAnC;AACD,WAFD;;AAIAQ,aAAGM,OAAH,GAAa,UAACC,UAAD,EAAgB;AAC3BZ,mBAAOY,UAAP;AACD,WAFD;AAGD,SA9BI,EA+BJC,KA/BI,CA+BE,UAACC,GAAD,EAAS;AACdd,iBAAOc,GAAP;AACD,SAjCI,CAAP;AAkCD,OAvCM,CAAP;AAwCD;;AAED;;;;;;;;;;;;;;2CAWuBjB,c,EAAgB;AACrC,aAAO,KAAKL,WAAL,CAAiBK,cAAjB,CAAP;AACD;;;;;;AAGH,eAAenB,GAAf","file":"index.js","sourcesContent":["import WebSocket from 'ws';\n\nimport Channels from './channels';\nimport WebSocketConnection from './webSocketConnection';\n\n/**\n * The raw WebSocket created by ws\n *\n * @typedef {Object} WebSocket\n * @property {function} addEventListener Register an event listener emulating the EventTarget interface\n * @property {string} binaryType A string indicating the type of binary data being transmitted by the connection. This should be one of \"nodebuffer\", \"arraybuffer\" or \"fragments\". Defaults to \"nodebuffer\".\n * @property {number} bufferedAmount The number of bytes of data that have been queued using calls to send() but not yet transmitted to the network.\n * @property {function} close Initiate a closing handshake\n * @property {Object} extensions An object containing the negotiated extensions\n * @property {function} onclose An event listener to be called when connection is closed\n * @property {function} onerror An event listener to be called when an error occurs\n * @property {function} onmessage An event listener to be called when a message is received from the server\n * @property {function} onopen An event listener to be called when the connection is established\n * @property {function} ping Send a ping to the WebSocket server\n * @property {function} pong Send a pong to the WebSocket server\n * @property {string} protocol The subprotocol selected by the server\n * @property {number} readyState The current state of the connection\n * @property {function} removeEventListener Removes an event listener emulating the EventTarget interface\n * @property {function} send Send data through the open WebSocket connection\n * @property {function} terminate Forcibly close the connection\n * @property {string} url The URL of the WebSocket server\n */\n\n/**\n * A wrapper around the raw WebSocket to provide a finite set of operations\n *\n * @typedef {Object} WebSocketConnection\n * @property {function} close Closes the WebSocket connection to the message bus server\n * @property {string} _organizationId The organization id for the open WebSocket connection\n * @property {WebSocket} _webSocket The raw WebSocket connection to the message bus\n */\n\n/**\n * Configuration object for the Bus\n *\n * @typedef {Object} BusConfig\n * @property {boolean} autoAcknowledge\n */\n\n/**\n * @type {BusConfig}\n */\nconst defaultBusConfig = {\n autoAcknowledge: true\n};\n\n/**\n * Module that provides access to the message bus. This is for Node\n * environments. Documentation for browser environments is found under\n * `BrowserBus`.\n *\n * @typicalname contxtSdk.bus\n */\nclass Bus {\n /**\n * @param {Object} sdk An instance of the SDK so the module can communicate with other modules\n * @param {Object} request An instance of the request module tied to this module's audience.\n * @param {BusConfig} config A config object for the Bus instance\n */\n constructor(sdk, request, config) {\n const baseUrl = `${sdk.config.audiences.bus.host}`;\n const baseWebSocketUrl = `${sdk.config.audiences.bus.webSocket}`;\n\n this._baseWebSocketUrl = baseWebSocketUrl;\n this._baseUrl = baseUrl;\n this._request = request;\n this._sdk = sdk;\n this._webSockets = {};\n this._config = Object.assign({}, defaultBusConfig, config);\n\n this.channels = new Channels(sdk, request, baseUrl);\n }\n\n /**\n * Connects to the message bus via websocket.\n * If a connection already exists for that organization id, the connection is returned, otherwise a new connection is created and returned.\n *\n * @param {string} organizationId UUID corresponding with an organization\n *\n * @returns {Promise}\n * @fulfill {WebSocketConnection}\n * @reject {errorEvent} The error event\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * console.log(webSocket);\n * })\n * .catch((errorEvent) => {\n * console.log(errorEvent);\n * });\n */\n connect(organizationId) {\n return new Promise((resolve, reject) => {\n if (this._webSockets[organizationId]) {\n return resolve(this._webSockets[organizationId]);\n }\n\n return this._sdk.auth\n .getCurrentApiToken('contxtAuth')\n .then((apiToken) => {\n const ws = new WebSocket(\n `${this._baseWebSocketUrl}/organizations/${organizationId}/stream`,\n [],\n {\n headers: {\n Authorization: `Bearer ${apiToken}`\n }\n }\n );\n\n ws.onopen = (event) => {\n this._webSockets[organizationId] = new WebSocketConnection(\n ws,\n organizationId,\n this._config.autoAcknowledge\n );\n\n resolve(this._webSockets[organizationId]);\n };\n\n ws.onclose = (event) => {\n this._webSockets[organizationId] = null;\n };\n\n ws.onerror = (errorEvent) => {\n reject(errorEvent);\n };\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n /**\n * Gets the WebSocketConnection for an organization id\n * If a connection already exists for that organization id, the connection is returned, otherwise returns undefined.\n *\n * @param {string} organizationId UUID corresponding with an organization\n *\n * @returns {WebSocketConnection}\n *\n * @example\n * const messageBusWebSocket = contxtSdk.bus.getWebSocketConnection('4f0e51c6-728b-4892-9863-6d002e61204d');\n */\n getWebSocketConnection(organizationId) {\n return this._webSockets[organizationId];\n }\n}\n\nexport default Bus;\n"]}
1
+ {"version":3,"sources":["bus/index.js"],"names":["WebSocket","Channels","WebSocketConnection","defaultBusConfig","autoAcknowledge","Bus","sdk","request","config","baseUrl","audiences","bus","host","baseWebSocketUrl","webSocket","_baseWebSocketUrl","_baseUrl","_request","_sdk","_webSockets","_config","Object","assign","channels","organizationId","onClose","onError","Promise","resolve","reject","auth","getCurrentApiToken","then","apiToken","ws","headers","Authorization","onopen","event","addEventListener","ex","console","log","errorEvent","connected","catch","err"],"mappings":";;;;AAAA,OAAOA,SAAP,MAAsB,IAAtB;;AAEA,OAAOC,QAAP,MAAqB,YAArB;AACA,OAAOC,mBAAP,MAAgC,uBAAhC;;AAEA;;;;;;;;;;;;;;;;;;;;;;;AAuBA;;;;;;;;;AASA;;;;;;;AAOA;;;AAGA,IAAMC,mBAAmB;AACvBC,mBAAiB;AADM,CAAzB;;AAIA;;;;;;;;IAOMC,G;AACJ;;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jC,MAAKJ,OAAL,CAAahB,eAHoB,CAAnC;;AAMAwB,oBAAQ,MAAKT,WAAL,CAAiBK,cAAjB,CAAR;AACD,WARD;;AAUAU,aAAGK,gBAAH,CAAoB,OAApB,EAA6B,UAACD,KAAD,EAAW;AACtC,kBAAKnB,WAAL,CAAiBK,cAAjB,IAAmC,IAAnC;AACA,gBAAIC,OAAJ,EAAa;AACX,kBAAI;AACFA,wBAAQD,cAAR,EAAwBc,KAAxB;AACD,eAFD,CAEE,OAAOE,EAAP,EAAW;AACXC,wBAAQC,GAAR,CAAY,8CAAZ,EAA4DF,EAA5D;AACD;AACF;AACF,WATD;;AAWAN,aAAGK,gBAAH,CAAoB,OAApB,EAA6B,UAACI,UAAD,EAAgB;AAC3C,gBAAMC,YAAY,MAAKzB,WAAL,CAAiBK,cAAjB,KAAoC,IAAtD;AACA,kBAAKL,WAAL,CAAiBK,cAAjB,IAAmC,IAAnC;AACA,gBAAI,CAACoB,SAAL,EAAgB;AACdf,qBAAOc,UAAP;AACD;AACD,gBAAIjB,OAAJ,EAAa;AACX,kBAAI;AACFA,wBAAQF,cAAR,EAAwBmB,UAAxB;AACD,eAFD,CAEE,OAAOH,EAAP,EAAW;AACXC,wBAAQC,GAAR,CAAY,8CAAZ,EAA4DF,EAA5D;AACD;AACF;AACF,WAbD;AAcD,SAhDI,EAiDJK,KAjDI,CAiDE,UAACC,GAAD,EAAS;AACdjB,iBAAOiB,GAAP;AACD,SAnDI,CAAP;AAoDD,OAzDM,CAAP;AA0DD;;AAED;;;;;;;;;;;;;;2CAWuBtB,c,EAAgB;AACrC,aAAO,KAAKL,WAAL,CAAiBK,cAAjB,CAAP;AACD;;;;;;AAGH,eAAenB,GAAf","file":"index.js","sourcesContent":["import WebSocket from 'ws';\n\nimport Channels from './channels';\nimport WebSocketConnection from './webSocketConnection';\n\n/**\n * The raw WebSocket created by ws\n *\n * @typedef {Object} WebSocket\n * @property {function} addEventListener Register an event listener emulating the EventTarget interface\n * @property {string} binaryType A string indicating the type of binary data being transmitted by the connection. This should be one of \"nodebuffer\", \"arraybuffer\" or \"fragments\". Defaults to \"nodebuffer\".\n * @property {number} bufferedAmount The number of bytes of data that have been queued using calls to send() but not yet transmitted to the network.\n * @property {function} close Initiate a closing handshake\n * @property {Object} extensions An object containing the negotiated extensions\n * @property {function} onclose An event listener to be called when connection is closed\n * @property {function} onerror An event listener to be called when an error occurs\n * @property {function} onmessage An event listener to be called when a message is received from the server\n * @property {function} onopen An event listener to be called when the connection is established\n * @property {function} ping Send a ping to the WebSocket server\n * @property {function} pong Send a pong to the WebSocket server\n * @property {string} protocol The subprotocol selected by the server\n * @property {number} readyState The current state of the connection\n * @property {function} removeEventListener Removes an event listener emulating the EventTarget interface\n * @property {function} send Send data through the open WebSocket connection\n * @property {function} terminate Forcibly close the connection\n * @property {string} url The URL of the WebSocket server\n */\n\n/**\n * A wrapper around the raw WebSocket to provide a finite set of operations\n *\n * @typedef {Object} WebSocketConnection\n * @property {function} close Closes the WebSocket connection to the message bus server\n * @property {string} _organizationId The organization id for the open WebSocket connection\n * @property {WebSocket} _webSocket The raw WebSocket connection to the message bus\n */\n\n/**\n * Configuration object for the Bus\n *\n * @typedef {Object} BusConfig\n * @property {boolean} autoAcknowledge\n */\n\n/**\n * @type {BusConfig}\n */\nconst defaultBusConfig = {\n autoAcknowledge: true\n};\n\n/**\n * Module that provides access to the message bus. This is for Node\n * environments. Documentation for browser environments is found under\n * `BrowserBus`.\n *\n * @typicalname contxtSdk.bus\n */\nclass Bus {\n /**\n * @param {Object} sdk An instance of the SDK so the module can communicate with other modules\n * @param {Object} request An instance of the request module tied to this module's audience.\n * @param {BusConfig} config A config object for the Bus instance\n */\n constructor(sdk, request, config) {\n const baseUrl = `${sdk.config.audiences.bus.host}`;\n const baseWebSocketUrl = `${sdk.config.audiences.bus.webSocket}`;\n\n this._baseWebSocketUrl = baseWebSocketUrl;\n this._baseUrl = baseUrl;\n this._request = request;\n this._sdk = sdk;\n this._webSockets = {};\n this._config = Object.assign({}, defaultBusConfig, config);\n\n this.channels = new Channels(sdk, request, baseUrl);\n }\n\n /**\n * Connects to the message bus via websocket.\n * If a connection already exists for that organization id, the connection is returned, otherwise a new connection is created and returned.\n *\n * @param {string} organizationId UUID corresponding with an organization\n * @param {function} onClose optional callback to be executed when the connection is closed\n * @param {function} onError optional callback to be executed when the connection encounters an error\n *\n * @returns {Promise}\n * @fulfill {WebSocketConnection}\n * @reject {errorEvent} The error event\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d', (orgId, evt) => {\n * console.log(`connection closed: ${evt}`);\n * }, (orgId, evt) => {\n * console.log(`connection error: ${evt}`);\n * })\n * .then((webSocket) => {\n * console.log(webSocket);\n * })\n * .catch((errorEvent) => {\n * console.log(errorEvent);\n * });\n */\n connect(organizationId, onClose, onError) {\n return new Promise((resolve, reject) => {\n if (this._webSockets[organizationId]) {\n return resolve(this._webSockets[organizationId]);\n }\n\n return this._sdk.auth\n .getCurrentApiToken('contxtAuth')\n .then((apiToken) => {\n const ws = new WebSocket(\n `${this._baseWebSocketUrl}/organizations/${organizationId}/stream`,\n [],\n {\n headers: {\n Authorization: `Bearer ${apiToken}`\n }\n }\n );\n\n ws.onopen = (event) => {\n this._webSockets[organizationId] = new WebSocketConnection(\n ws,\n organizationId,\n this._config.autoAcknowledge\n );\n\n resolve(this._webSockets[organizationId]);\n };\n\n ws.addEventListener(\"close\", (event) => {\n this._webSockets[organizationId] = null;\n if (onClose) {\n try {\n onClose(organizationId, event);\n } catch (ex) {\n console.log('Message Bus Error calling onClose callback: ', ex)\n }\n }\n });\n\n ws.addEventListener(\"error\", (errorEvent) => {\n const connected = this._webSockets[organizationId] != null;\n this._webSockets[organizationId] = null;\n if (!connected) {\n reject(errorEvent)\n }\n if (onError) {\n try {\n onError(organizationId, errorEvent);\n } catch (ex) {\n console.log('Message Bus Error calling onError callback: ', ex)\n }\n }\n });\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n /**\n * Gets the WebSocketConnection for an organization id\n * If a connection already exists for that organization id, the connection is returned, otherwise returns undefined.\n *\n * @param {string} organizationId UUID corresponding with an organization\n *\n * @returns {WebSocketConnection}\n *\n * @example\n * const messageBusWebSocket = contxtSdk.bus.getWebSocketConnection('4f0e51c6-728b-4892-9863-6d002e61204d');\n */\n getWebSocketConnection(organizationId) {\n return this._webSockets[organizationId];\n }\n}\n\nexport default Bus;\n"]}
@@ -69,7 +69,7 @@ var WebSocketConnection = function () {
69
69
  this._autoAck = autoAcknowledge;
70
70
 
71
71
  if (this._webSocket) {
72
- this._webSocket.onerror = this._onError;
72
+ this._webSocket.addEventListener("error", this._onError);
73
73
  this._webSocket.onmessage = this._onMessage;
74
74
  }
75
75
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["bus/webSocketConnection.js"],"names":["v4","uuid","once","WebSocketConnection","webSocket","organizationId","autoAcknowledge","_onError","error","_messageHandlers","console","log","_onMessage","message","messageData","JSON","parse","data","err","Error","id","_organizationId","_webSocket","_autoAck","onerror","onmessage","token","Promise","reject","_isConnected","_registerSingleMessageHandler","close","serviceClientId","channel","service_id","group","handler","errorHandler","params","then","result","subscription","subscriptionMessage","resolve","ack","_acknowledge","body","res","throwable","acknowledgedMessageId","message_id","method","messageId","send","stringify","jsonrpc","readyState","OPEN"],"mappings":";;;;AAAA,SAASA,MAAMC,IAAf,QAA2B,MAA3B;AACA,OAAOC,IAAP,MAAiB,aAAjB;;AAEA;;;;;;;AAOA;;;;;;;;;;;AAWA;;;;;;;IAMMC,mB;AACJ;;;;;AAKA,+BAAYC,SAAZ,EAAuBC,cAAvB,EAA+D;AAAA;;AAAA,QAAxBC,eAAwB,uEAAN,IAAM;;AAAA;;AAAA,SAsE/DC,QAtE+D,GAsEpD,UAACC,KAAD,EAAW;AACpB,YAAKC,gBAAL,GAAwB,EAAxB;;AAEAC,cAAQC,GAAR,CAAY,+BAAZ,EAA6CH,KAA7C;AACD,KA1E8D;;AAAA,SAmF/DI,UAn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C,UAAI,CAAC,KAAKpB,YAAL,EAAL,EAA0B;AACxB,eAAOF,QAAQC,MAAR,CAAe,IAAIT,KAAJ,CAAU,+BAAV,CAAf,CAAP;AACD;;AAED,aAAO,KAAKW,6BAAL,CAAmC,aAAnC,EAAkD;AACvDoB,oBAAYD;AAD2C,OAAlD,CAAP;AAGD;;AAED;;;;;;;;;;;;kDAS8BE,M,EAAQb,M,EAAQ;AAAA;;AAC5C,aAAO,IAAIX,OAAJ,CAAY,UAACgB,OAAD,EAAUf,MAAV,EAAqB;AACtC,YAAMwB,YAAYnD,MAAlB;;AAEA,eAAKQ,gBAAL,CAAsB2C,SAAtB,IAAmC,UAACvC,OAAD,EAAa;AAC9C,cAAML,QAAQK,QAAQL,KAAtB;AACA,iBAAO,OAAKC,gBAAL,CAAsB2C,SAAtB,CAAP;;AAEA,cAAI5C,KAAJ,EAAW;AACT,mBAAOoB,OAAOpB,KAAP,CAAP;AACD;;AAED,iBAAOmC,QAAQ9B,QAAQ2B,MAAhB,CAAP;AACD,SATD;;AAWA,eAAKlB,UAAL,CAAgB+B,IAAhB,CACEtC,KAAKuC,SAAL,CAAe;AACbC,mBAAS,KADI;AAEbJ,kCAAsBA,MAFT;AAGbb,wBAHa;AAIblB,cAAIgC;AAJS,SAAf,CADF;AAQD,OAtBM,CAAP;AAuBD;;AAED;;;;;;;;;;mCAOe;AACb,aACE,KAAK9B,UAAL,IAAmB,KAAKA,UAAL,CAAgBkC,UAAhB,KAA+B,KAAKlC,UAAL,CAAgBmC,IADpE;AAGD;;;;;;AAGH,eAAetD,mBAAf","file":"webSocketConnection.js","sourcesContent":["import { v4 as uuid } from 'uuid';\nimport once from 'lodash.once';\n\n/**\n * The WebSocket Error Event\n *\n * @typedef {Object} WebSocketError\n * @property {string} type The event type\n */\n\n/**\n * The WebSocket Message Event\n *\n * @typedef {Object} WebSocketMessage\n * @property {Object} data The data sent by the message emitter\n * @property {string} origin A USVString representing the origin of the message emitter\n * @property {string} lastEventId A DOMString representing a unique ID for the event\n * @property {Object} source A MessageEventSource (which can be a WindowProxy, MessagePort, or ServiceWorker object) representing the message emitter\n * @property {Array} ports MessagePort objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker)\n */\n\n/**\n * Module that wraps the websocket connection to the message bus to provide the\n * developer with a specific set of functionality. This is for Node\n * environments. Documentation for browser environments is found under\n * `BrowserWebSocketConnection`.\n */\nclass WebSocketConnection {\n /**\n * @param {WebSocket} webSocket A WebSocket connection to the message bus\n * @param {string} organizationId UUID corresponding with an organization\n * @param {boolean} autoAcknowledge Whether the messages should be ACK'd explicitly or not\n */\n constructor(webSocket, organizationId, autoAcknowledge = true) {\n this._messageHandlers = {};\n this._organizationId = organizationId;\n this._webSocket = webSocket;\n this._autoAck = autoAcknowledge;\n\n if (this._webSocket) {\n this._webSocket.onerror = this._onError;\n this._webSocket.onmessage = this._onMessage;\n }\n }\n\n /**\n * Sends a message to the message bus to authorize a channel\n *\n * @param {string} token JSON Web Signature containing the channel and actions needed for authorization\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.authorize(token).then(() => {\n * console.log(\"authorization successful\")\n * })\n * .catch((authError) => {\n * console.log(authError)\n * });\n * })\n * });\n */\n authorize(token) {\n if (!token) {\n return Promise.reject(new Error('A token is required for authorization'));\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Authorize', { token });\n }\n\n /**\n * Closes the websocket connection\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.close()\n * })\n * .catch((errorEvent) => {\n * console.log(errorEvent);\n * });\n */\n close() {\n this._webSocket.close();\n }\n\n /**\n * Handles WebSocket errors.\n * The `ws` library also closes the socket when an error occurs.\n * Since the socket connection closes, the jsonRpcId and message handlers are cleared\n *\n * @param {WebSocketError} error The error event thrown\n *\n * @private\n */\n _onError = (error) => {\n this._messageHandlers = {};\n\n console.log('Message Bus WebSocket Error: ', error);\n };\n\n /**\n * Handles messages sent from the Message Bus WebSocket connection.\n *\n * @param {WebSocketMessage} message The message event recieved over the WebSocket connection\n *\n * @private\n */\n _onMessage = (message) => {\n let messageData;\n\n try {\n messageData = JSON.parse(message.data);\n } catch (err) {\n throw new Error('Invalid JSON in message');\n }\n\n if (this._messageHandlers[messageData.id]) {\n this._messageHandlers[messageData.id](messageData);\n }\n };\n\n /**\n * Publishes a message to a specific channel on the message bus\n *\n * @param {string} serviceClientId Client ID of the message bus service\n * @param {string} channel Message bus channel the message is being sent to\n * @param {Any} message Message being sent to the message bus. Must be valid JSON.\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.publish('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', {\"example\": 1}).then(() => {\n * console.log(\"publish successful\")\n * })\n * .catch((error) => {\n * console.log(error)\n * });\n * });\n */\n publish(serviceClientId, channel, message) {\n if (!serviceClientId) {\n return Promise.reject(\n new Error('A service client id is required for publishing')\n );\n }\n\n if (!channel) {\n return Promise.reject(new Error('A channel is required for publishing'));\n }\n\n if (!message) {\n return Promise.reject(new Error('A message is required for publishing'));\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Publish', {\n service_id: serviceClientId,\n channel,\n message\n });\n }\n\n /**\n * Subscribes to a specific channel on the message bus and handles messages as they are received. When the handler is\n * called, the message is automatically acknowledged after the message completes except whenever an Error is thrown.\n * The user can also programmatically control when the message is acknowledged by calling `ack` at any time.\n *\n * @param {string} serviceClientId Client ID of the message bus service\n * @param {string} channel Message bus channel the message is being sent to\n * @param {string} [group] A unique identifier for the subscriber that can be shared between connections\n * @param {function} handler A function that gets invoked with every received message\n * @param {function} errorHandler A function that gets invoked with every error\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', 'test-sub', (message) => {\n * console.log('Message received: ', message);\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', 'test-sub', (message, ack) => {\n * console.log('Message received: ', message);\n *\n * ack();\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', (message) => {\n * return db.save(message);\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', (message, ack) => {\n * return db.save(message)\n * .then(ack)\n * .then(() => {\n * // additional processing\n * });\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n */\n subscribe(serviceClientId, channel, group, handler, errorHandler) {\n if (typeof group === 'function') {\n errorHandler = handler;\n handler = group;\n group = null;\n }\n\n if (!serviceClientId) {\n return Promise.reject(\n new Error('A service client id is required for subscribing')\n );\n }\n\n if (!channel) {\n return Promise.reject(new Error('A channel is required for subscribing'));\n }\n\n if (!handler) {\n return Promise.reject(\n new Error('A message handler is required for subscribing')\n );\n }\n\n if (!errorHandler) {\n return Promise.reject(\n new Error('An error handler is required for subscribing')\n );\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n const params = {\n service_id: serviceClientId,\n channel\n };\n\n if (group) {\n params.group = group;\n }\n\n return this._registerSingleMessageHandler('Subscribe', params).then(\n (result) => {\n this._messageHandlers[result.subscription] = (subscriptionMessage) => {\n return new Promise((resolve, reject) => {\n const error = subscriptionMessage.error;\n const result = subscriptionMessage.result;\n\n if (error) {\n return resolve(errorHandler(error));\n }\n\n try {\n const ack = once(() => {\n return this._acknowledge(result.id);\n });\n\n return resolve(\n Promise.resolve(handler(result.body, ack)).then((res) => {\n if (this._autoAck) {\n return ack().then(() => res);\n }\n\n return res;\n })\n );\n } catch (throwable) {\n return reject(throwable);\n }\n });\n };\n\n return result;\n }\n );\n }\n\n /**\n * Acknowledges a Message ID has been received and processed\n *\n * @returns {Promise}\n * @param acknowledgedMessageId {string} The Message ID that has been received\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @private\n */\n _acknowledge(acknowledgedMessageId) {\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Acknowledge', {\n message_id: acknowledgedMessageId\n });\n }\n\n /**\n * Registers a JSON RPC message handler that expects only one response.\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @private\n */\n _registerSingleMessageHandler(method, params) {\n return new Promise((resolve, reject) => {\n const messageId = uuid();\n\n this._messageHandlers[messageId] = (message) => {\n const error = message.error;\n delete this._messageHandlers[messageId];\n\n if (error) {\n return reject(error);\n }\n\n return resolve(message.result);\n };\n\n this._webSocket.send(\n JSON.stringify({\n jsonrpc: '2.0',\n method: `MessageBus.${method}`,\n params,\n id: messageId\n })\n );\n });\n }\n\n /**\n * Checks whether the current WebSocket is connected to the Message Bus service.\n *\n * @returns {boolean} Whether the WebSocket is connected to the Message Bus service\n *\n * @private\n */\n _isConnected() {\n return (\n this._webSocket && this._webSocket.readyState === this._webSocket.OPEN\n );\n }\n}\n\nexport default WebSocketConnection;\n"]}
1
+ {"version":3,"sources":["bus/webSocketConnection.js"],"names":["v4","uuid","once","WebSocketConnection","webSocket","organizationId","autoAcknowledge","_onError","error","_messageHandlers","console","log","_onMessage","message","messageData","JSON","parse","data","err","Error","id","_organizationId","_webSocket","_autoAck","addEventListener","onmessage","token","Promise","reject","_isConnected","_registerSingleMessageHandler","close","serviceClientId","channel","service_id","group","handler","errorHandler","params","then","result","subscription","subscriptionMessage","resolve","ack","_acknowledge","body","res","throwable","acknowledgedMessageId","message_id","method","messageId","send","stringify","jsonrpc","readyState","OPEN"],"mappings":";;;;AAAA,SAASA,MAAMC,IAAf,QAA2B,MAA3B;AACA,OAAOC,IAAP,MAAiB,aAAjB;;AAEA;;;;;;;AAOA;;;;;;;;;;;AAWA;;;;;;;IAMMC,mB;AACJ;;;;;AAKA,+BAAYC,SAAZ,EAAuBC,cAAvB,EAA+D;AAAA;;AAAA,QAAxBC,eAAwB,uEAAN,IAAM;;AAAA;;AAAA,SAsE/DC,QAtE+D,GAsEpD,UAACC,KAAD,EAAW;AACpB,YAAKC,gBAAL,GAAwB,EAAxB;;AAEAC,cAAQC,GAAR,CAAY,+BAAZ,EAA6CH,KAA7C;AACD,KA1E8D;;AAAA,SAmF/DI,UAnF+D,GAmFlD,UAACC,OAAD,EAAa;AACxB,UAAIC,oBAAJ;;AAEA,UAAI;AACFA,sBAAcC,KAAKC,KAAL,CAAWH,QAAQI,IAAnB,CAAd;AACD,OAFD,CAEE,OAAOC,GAAP,EAAY;AACZ,cAAM,IAAIC,KAAJ,CAAU,yBAAV,CAAN;AACD;;AAED,UAAI,MAAKV,gBAAL,CAAsBK,YAAYM,EAAlC,CAAJ,EAA2C;AACzC,cAAKX,gBAAL,CAAsBK,YAAYM,EAAlC,EAAsCN,WAAtC;AACD;AACF,KA/F8D;;AAC7D,SAAKL,gBAAL,GAAwB,EAA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EA,eAAKQ,gBAAL,CAAsB2C,SAAtB,IAAmC,UAACvC,OAAD,EAAa;AAC9C,cAAML,QAAQK,QAAQL,KAAtB;AACA,iBAAO,OAAKC,gBAAL,CAAsB2C,SAAtB,CAAP;;AAEA,cAAI5C,KAAJ,EAAW;AACT,mBAAOoB,OAAOpB,KAAP,CAAP;AACD;;AAED,iBAAOmC,QAAQ9B,QAAQ2B,MAAhB,CAAP;AACD,SATD;;AAWA,eAAKlB,UAAL,CAAgB+B,IAAhB,CACEtC,KAAKuC,SAAL,CAAe;AACbC,mBAAS,KADI;AAEbJ,kCAAsBA,MAFT;AAGbb,wBAHa;AAIblB,cAAIgC;AAJS,SAAf,CADF;AAQD,OAtBM,CAAP;AAuBD;;AAED;;;;;;;;;;mCAOe;AACb,aACE,KAAK9B,UAAL,IAAmB,KAAKA,UAAL,CAAgBkC,UAAhB,KAA+B,KAAKlC,UAAL,CAAgBmC,IADpE;AAGD;;;;;;AAGH,eAAetD,mBAAf","file":"webSocketConnection.js","sourcesContent":["import { v4 as uuid } from 'uuid';\nimport once from 'lodash.once';\n\n/**\n * The WebSocket Error Event\n *\n * @typedef {Object} WebSocketError\n * @property {string} type The event type\n */\n\n/**\n * The WebSocket Message Event\n *\n * @typedef {Object} WebSocketMessage\n * @property {Object} data The data sent by the message emitter\n * @property {string} origin A USVString representing the origin of the message emitter\n * @property {string} lastEventId A DOMString representing a unique ID for the event\n * @property {Object} source A MessageEventSource (which can be a WindowProxy, MessagePort, or ServiceWorker object) representing the message emitter\n * @property {Array} ports MessagePort objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker)\n */\n\n/**\n * Module that wraps the websocket connection to the message bus to provide the\n * developer with a specific set of functionality. This is for Node\n * environments. Documentation for browser environments is found under\n * `BrowserWebSocketConnection`.\n */\nclass WebSocketConnection {\n /**\n * @param {WebSocket} webSocket A WebSocket connection to the message bus\n * @param {string} organizationId UUID corresponding with an organization\n * @param {boolean} autoAcknowledge Whether the messages should be ACK'd explicitly or not\n */\n constructor(webSocket, organizationId, autoAcknowledge = true) {\n this._messageHandlers = {};\n this._organizationId = organizationId;\n this._webSocket = webSocket;\n this._autoAck = autoAcknowledge;\n\n if (this._webSocket) {\n this._webSocket.addEventListener(\"error\", this._onError);\n this._webSocket.onmessage = this._onMessage;\n }\n }\n\n /**\n * Sends a message to the message bus to authorize a channel\n *\n * @param {string} token JSON Web Signature containing the channel and actions needed for authorization\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.authorize(token).then(() => {\n * console.log(\"authorization successful\")\n * })\n * .catch((authError) => {\n * console.log(authError)\n * });\n * })\n * });\n */\n authorize(token) {\n if (!token) {\n return Promise.reject(new Error('A token is required for authorization'));\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Authorize', { token });\n }\n\n /**\n * Closes the websocket connection\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.close()\n * })\n * .catch((errorEvent) => {\n * console.log(errorEvent);\n * });\n */\n close() {\n this._webSocket.close();\n }\n\n /**\n * Handles WebSocket errors.\n * The `ws` library also closes the socket when an error occurs.\n * Since the socket connection closes, the jsonRpcId and message handlers are cleared\n *\n * @param {WebSocketError} error The error event thrown\n *\n * @private\n */\n _onError = (error) => {\n this._messageHandlers = {};\n\n console.log('Message Bus WebSocket Error: ', error);\n };\n\n /**\n * Handles messages sent from the Message Bus WebSocket connection.\n *\n * @param {WebSocketMessage} message The message event recieved over the WebSocket connection\n *\n * @private\n */\n _onMessage = (message) => {\n let messageData;\n\n try {\n messageData = JSON.parse(message.data);\n } catch (err) {\n throw new Error('Invalid JSON in message');\n }\n\n if (this._messageHandlers[messageData.id]) {\n this._messageHandlers[messageData.id](messageData);\n }\n };\n\n /**\n * Publishes a message to a specific channel on the message bus\n *\n * @param {string} serviceClientId Client ID of the message bus service\n * @param {string} channel Message bus channel the message is being sent to\n * @param {Any} message Message being sent to the message bus. Must be valid JSON.\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.publish('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', {\"example\": 1}).then(() => {\n * console.log(\"publish successful\")\n * })\n * .catch((error) => {\n * console.log(error)\n * });\n * });\n */\n publish(serviceClientId, channel, message) {\n if (!serviceClientId) {\n return Promise.reject(\n new Error('A service client id is required for publishing')\n );\n }\n\n if (!channel) {\n return Promise.reject(new Error('A channel is required for publishing'));\n }\n\n if (!message) {\n return Promise.reject(new Error('A message is required for publishing'));\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Publish', {\n service_id: serviceClientId,\n channel,\n message\n });\n }\n\n /**\n * Subscribes to a specific channel on the message bus and handles messages as they are received. When the handler is\n * called, the message is automatically acknowledged after the message completes except whenever an Error is thrown.\n * The user can also programmatically control when the message is acknowledged by calling `ack` at any time.\n *\n * @param {string} serviceClientId Client ID of the message bus service\n * @param {string} channel Message bus channel the message is being sent to\n * @param {string} [group] A unique identifier for the subscriber that can be shared between connections\n * @param {function} handler A function that gets invoked with every received message\n * @param {function} errorHandler A function that gets invoked with every error\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', 'test-sub', (message) => {\n * console.log('Message received: ', message);\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', 'test-sub', (message, ack) => {\n * console.log('Message received: ', message);\n *\n * ack();\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', (message) => {\n * return db.save(message);\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', (message, ack) => {\n * return db.save(message)\n * .then(ack)\n * .then(() => {\n * // additional processing\n * });\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n */\n subscribe(serviceClientId, channel, group, handler, errorHandler) {\n if (typeof group === 'function') {\n errorHandler = handler;\n handler = group;\n group = null;\n }\n\n if (!serviceClientId) {\n return Promise.reject(\n new Error('A service client id is required for subscribing')\n );\n }\n\n if (!channel) {\n return Promise.reject(new Error('A channel is required for subscribing'));\n }\n\n if (!handler) {\n return Promise.reject(\n new Error('A message handler is required for subscribing')\n );\n }\n\n if (!errorHandler) {\n return Promise.reject(\n new Error('An error handler is required for subscribing')\n );\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n const params = {\n service_id: serviceClientId,\n channel\n };\n\n if (group) {\n params.group = group;\n }\n\n return this._registerSingleMessageHandler('Subscribe', params).then(\n (result) => {\n this._messageHandlers[result.subscription] = (subscriptionMessage) => {\n return new Promise((resolve, reject) => {\n const error = subscriptionMessage.error;\n const result = subscriptionMessage.result;\n\n if (error) {\n return resolve(errorHandler(error));\n }\n\n try {\n const ack = once(() => {\n return this._acknowledge(result.id);\n });\n\n return resolve(\n Promise.resolve(handler(result.body, ack)).then((res) => {\n if (this._autoAck) {\n return ack().then(() => res);\n }\n\n return res;\n })\n );\n } catch (throwable) {\n return reject(throwable);\n }\n });\n };\n\n return result;\n }\n );\n }\n\n /**\n * Acknowledges a Message ID has been received and processed\n *\n * @returns {Promise}\n * @param acknowledgedMessageId {string} The Message ID that has been received\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @private\n */\n _acknowledge(acknowledgedMessageId) {\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Acknowledge', {\n message_id: acknowledgedMessageId\n });\n }\n\n /**\n * Registers a JSON RPC message handler that expects only one response.\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @private\n */\n _registerSingleMessageHandler(method, params) {\n return new Promise((resolve, reject) => {\n const messageId = uuid();\n\n this._messageHandlers[messageId] = (message) => {\n const error = message.error;\n delete this._messageHandlers[messageId];\n\n if (error) {\n return reject(error);\n }\n\n return resolve(message.result);\n };\n\n this._webSocket.send(\n JSON.stringify({\n jsonrpc: '2.0',\n method: `MessageBus.${method}`,\n params,\n id: messageId\n })\n );\n });\n }\n\n /**\n * Checks whether the current WebSocket is connected to the Message Bus service.\n *\n * @returns {boolean} Whether the WebSocket is connected to the Message Bus service\n *\n * @private\n */\n _isConnected() {\n return (\n this._webSocket && this._webSocket.readyState === this._webSocket.OPEN\n );\n }\n}\n\nexport default WebSocketConnection;\n"]}
package/esm/request.js CHANGED
@@ -6,6 +6,22 @@ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Cons
6
6
 
7
7
  import axios from 'axios';
8
8
 
9
+ function loadSdkInfo() {
10
+ try {
11
+ var _require = require('../package.json'),
12
+ _sdkName = _require.name,
13
+ _sdkVersion = _require.version;
14
+
15
+ return { sdkName: _sdkName, sdkVersion: _sdkVersion };
16
+ } catch (e) {
17
+ return { sdkName: "@ndustrial/contxt-sdk", sdkVersion: "5.5.0+" };
18
+ }
19
+ }
20
+
21
+ var _loadSdkInfo = loadSdkInfo(),
22
+ sdkName = _loadSdkInfo.sdkName,
23
+ sdkVersion = _loadSdkInfo.sdkVersion;
24
+
9
25
  var Request = function () {
10
26
  /**
11
27
  * @param {Object} sdk An instance of the SDK so the module can communicate with other modules
@@ -223,6 +239,7 @@ var Request = function () {
223
239
  value: function _insertHeaders(config) {
224
240
  return this._sdk.auth.getCurrentApiToken(this._audienceName).then(function (apiToken) {
225
241
  config.headers.common.Authorization = 'Bearer ' + apiToken;
242
+ config.headers.common['User-Agent'] = process.env.npm_package_name + '/' + process.env.npm_package_version + ' (' + sdkName + '/' + sdkVersion + ')';
226
243
 
227
244
  return config;
228
245
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["request.js"],"names":["axios","Request","sdk","audienceName","_audienceName","_axios","create","_insertHeaders","bind","_sdk","_attachInterceptors","delete","then","data","get","head","options","patch","post","put","request","requestInterceptors","fulfilled","config","interceptors","responseInterceptors","response","forEach","rejected","use","auth","getCurrentApiToken","apiToken","headers","common","Authorization"],"mappings":";;;;;;AAAA,OAAOA,KAAP,MAAkB,OAAlB;;IAEMC,O;AACJ;;;;;AAKA,mBAAYC,GAAZ,EAAiBC,YAAjB,EAA+B;AAAA;;AAC7B,SAAKC,aAAL,GAAqBD,YAArB;AACA,SAAKE,MAAL,GAAcL,MAAMM,MAAN,EAAd;AACA,SAAKC,cAAL,GAAsB,KAAKA,cAAL,CAAoBC,IAApB,CAAyB,IAAzB,CAAtB;AACA,SAAKC,IAAL,GAAYP,GAAZ;;AAEA,SAAKQ,mBAAL;AACD;;AAED;;;;;;;;;;;8BAOgB;AAAA;;AACd,aAAO,eAAKL,MAAL,EAAYM,MAAZ,0BAA4BC,IAA5B,CAAiC;AAAA,YAAGC,IAAH,QAAGA,IAAH;AAAA,eAAcA,IAAd;AAAA,OAAjC,CAAP;AACD;;AAED;;;;;;;;;;0BAOa;AAAA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,WAAW,KAAKf,cAAlB,EADI,4BAED,KAAKE,IAAL,CAAUc,MAAV,CAAiBC,YAAjB,CAA8BJ,OAF7B,EAAN;AAIA,UAAMK,oDAA2B,KAAKhB,IAAL,CAAUc,MAAV,CAAiBC,YAAjB,CAA8BE,QAAzD,EAAN;;AAEAL,0BAAoBM,OAApB,CAA4B,iBAA6B;AAAA,YAA1BL,SAA0B,SAA1BA,SAA0B;AAAA,YAAfM,QAAe,SAAfA,QAAe;;AACvD,cAAKvB,MAAL,CAAYmB,YAAZ,CAAyBJ,OAAzB,CAAiCS,GAAjC,CAAqCP,SAArC,EAAgDM,QAAhD;AACD,OAFD;AAGAH,2BAAqBE,OAArB,CAA6B,kBAA6B;AAAA,YAA1BL,SAA0B,UAA1BA,SAA0B;AAAA,YAAfM,QAAe,UAAfA,QAAe;;AACxD,cAAKvB,MAAL,CAAYmB,YAAZ,CAAyBE,QAAzB,CAAkCG,GAAlC,CAAsCP,SAAtC,EAAiDM,QAAjD;AACD,OAFD;AAGD;;AAED;;;;;;;;;;;;;;;mCAYeL,M,EAAQ;AACrB,aAAO,KAAKd,IAAL,CAAUqB,IAAV,CACJC,kBADI,CACe,KAAK3B,aADpB,EAEJQ,IAFI,CAEC,UAACoB,QAAD,EAAc;AAClBT,eAAOU,OAAP,CAAeC,MAAf,CAAsBC,aAAtB,eAAgDH,QAAhD;;AAEA,eAAOT,MAAP;AACD,OANI,CAAP;AAOD;;;;;;AAGH,eAAetB,OAAf","file":"request.js","sourcesContent":["import axios from 'axios';\n\nclass Request {\n /**\n * @param {Object} sdk An instance of the SDK so the module can communicate with other modules\n * @param {string} audienceName The audience name for this instance. Used when grabbing a\n * Bearer token\n */\n constructor(sdk, audienceName) {\n this._audienceName = audienceName;\n this._axios = axios.create();\n this._insertHeaders = this._insertHeaders.bind(this);\n this._sdk = sdk;\n\n this._attachInterceptors();\n }\n\n /**\n * Makes a DELETE request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n delete(...args) {\n return this._axios.delete(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a GET request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n get(...args) {\n return this._axios.get(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a HEAD request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n head(...args) {\n return this._axios.head(...args).then(({ data }) => data);\n }\n\n /**\n * Makes an OPTIONS request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n options(...args) {\n return this._axios.options(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a PATCH request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n patch(...args) {\n return this._axios.patch(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a POST request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n post(...args) {\n return this._axios.post(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a PUT request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n put(...args) {\n return this._axios.put(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n request(...args) {\n return this._axios.request(...args).then(({ data }) => data);\n }\n\n /**\n * Sets up axios interceptors for the request instance\n * More information at {@link https://github.com/axios/axios#interceptors axios Interceptors}\n *\n * @private\n */\n _attachInterceptors() {\n const requestInterceptors = [\n { fulfilled: this._insertHeaders },\n ...this._sdk.config.interceptors.request\n ];\n const responseInterceptors = [...this._sdk.config.interceptors.response];\n\n requestInterceptors.forEach(({ fulfilled, rejected }) => {\n this._axios.interceptors.request.use(fulfilled, rejected);\n });\n responseInterceptors.forEach(({ fulfilled, rejected }) => {\n this._axios.interceptors.response.use(fulfilled, rejected);\n });\n }\n\n /**\n * Decorates custom modules onto the SDK instance so they behave as first-class citizens.\n *\n * @param {Object} config\n * @param {Object} config.headers\n * @param {Object} config.headers.common\n *\n * @returns {Promise}\n * @fulfill {Object} axios.js config\n *\n * @private\n */\n _insertHeaders(config) {\n return this._sdk.auth\n .getCurrentApiToken(this._audienceName)\n .then((apiToken) => {\n config.headers.common.Authorization = `Bearer ${apiToken}`;\n\n return config;\n });\n }\n}\n\nexport default Request;\n"]}
1
+ {"version":3,"sources":["request.js"],"names":["axios","loadSdkInfo","require","sdkName","name","sdkVersion","version","e","Request","sdk","audienceName","_audienceName","_axios","create","_insertHeaders","bind","_sdk","_attachInterceptors","delete","then","data","get","head","options","patch","post","put","request","requestInterceptors","fulfilled","config","interceptors","responseInterceptors","response","forEach","rejected","use","auth","getCurrentApiToken","apiToken","headers","common","Authorization","process","env","npm_package_name","npm_package_version"],"mappings":";;;;;;AAAA,OAAOA,KAAP,MAAkB,OAAlB;;AAEA,SAASC,WAAT,GAAuB;AACrB,MAAI;AAAA,mBAC6CC,QAAQ,iBAAR,CAD7C;AAAA,QACYC,QADZ,YACMC,IADN;AAAA,QAC8BC,WAD9B,YACqBC,OADrB;;AAEF,WAAO,EAAEH,iBAAF,EAAWE,uBAAX,EAAP;AACD,GAHD,CAGE,OAAOE,CAAP,EAAU;AACV,WAAO,EAAEJ,SAAS,uBAAX,EAAoCE,YAAY,QAAhD,EAAP;AACD;AACF;;mBAE+BJ,a;IAAxBE,O,gBAAAA,O;IAASE,U,gBAAAA,U;;IACXG,O;AACJ;;;;;AAKA,mBAAYC,GAAZ,EAAiBC,YAAjB,EAA+B;AAAA;;AAC7B,SAAKC,aAAL,GAAqBD,YAArB;AACA,SAAKE,MAAL,GAAcZ,MAAMa,MAAN,EAAd;AACA,SAAKC,cAAL,GAAsB,KAAKA,cAAL,CAAoBC,IAApB,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,CAAYE,mBAArF,UAA6G3C,OAA7G,SAAwHE,UAAxH;;AAEA,eAAOyB,MAAP;AACD,OAPI,CAAP;AAQD;;;;;;AAGH,eAAetB,OAAf","file":"request.js","sourcesContent":["import axios from 'axios';\n\nfunction loadSdkInfo() {\n try {\n const { name: sdkName, version: sdkVersion } = require('../package.json');\n return { sdkName, sdkVersion };\n } catch (e) {\n return { sdkName: \"@ndustrial/contxt-sdk\", sdkVersion: \"5.5.0+\" };\n }\n}\n\nconst { sdkName, sdkVersion } = loadSdkInfo();\nclass Request {\n /**\n * @param {Object} sdk An instance of the SDK so the module can communicate with other modules\n * @param {string} audienceName The audience name for this instance. Used when grabbing a\n * Bearer token\n */\n constructor(sdk, audienceName) {\n this._audienceName = audienceName;\n this._axios = axios.create();\n this._insertHeaders = this._insertHeaders.bind(this);\n this._sdk = sdk;\n\n this._attachInterceptors();\n }\n\n /**\n * Makes a DELETE request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n delete(...args) {\n return this._axios.delete(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a GET request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n get(...args) {\n return this._axios.get(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a HEAD request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n head(...args) {\n return this._axios.head(...args).then(({ data }) => data);\n }\n\n /**\n * Makes an OPTIONS request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n options(...args) {\n return this._axios.options(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a PATCH request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n patch(...args) {\n return this._axios.patch(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a POST request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n post(...args) {\n return this._axios.post(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a PUT request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n put(...args) {\n return this._axios.put(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n request(...args) {\n return this._axios.request(...args).then(({ data }) => data);\n }\n\n /**\n * Sets up axios interceptors for the request instance\n * More information at {@link https://github.com/axios/axios#interceptors axios Interceptors}\n *\n * @private\n */\n _attachInterceptors() {\n const requestInterceptors = [\n { fulfilled: this._insertHeaders },\n ...this._sdk.config.interceptors.request\n ];\n const responseInterceptors = [...this._sdk.config.interceptors.response];\n\n requestInterceptors.forEach(({ fulfilled, rejected }) => {\n this._axios.interceptors.request.use(fulfilled, rejected);\n });\n responseInterceptors.forEach(({ fulfilled, rejected }) => {\n this._axios.interceptors.response.use(fulfilled, rejected);\n });\n }\n\n /**\n * Decorates custom modules onto the SDK instance so they behave as first-class citizens.\n *\n * @param {Object} config\n * @param {Object} config.headers\n * @param {Object} config.headers.common\n *\n * @returns {Promise}\n * @fulfill {Object} axios.js config\n *\n * @private\n */\n _insertHeaders(config) {\n return this._sdk.auth\n .getCurrentApiToken(this._audienceName)\n .then((apiToken) => {\n config.headers.common.Authorization = `Bearer ${apiToken}`;\n config.headers.common['User-Agent'] = `${process.env.npm_package_name}/${process.env.npm_package_version} (${sdkName}/${sdkVersion})`;\n\n return config;\n });\n }\n}\n\nexport default Request;\n"]}
package/lib/bus/index.js CHANGED
@@ -103,13 +103,19 @@ var Bus = function () {
103
103
  * If a connection already exists for that organization id, the connection is returned, otherwise a new connection is created and returned.
104
104
  *
105
105
  * @param {string} organizationId UUID corresponding with an organization
106
+ * @param {function} onClose optional callback to be executed when the connection is closed
107
+ * @param {function} onError optional callback to be executed when the connection encounters an error
106
108
  *
107
109
  * @returns {Promise}
108
110
  * @fulfill {WebSocketConnection}
109
111
  * @reject {errorEvent} The error event
110
112
  *
111
113
  * @example
112
- * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')
114
+ * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d', (orgId, evt) => {
115
+ * console.log(`connection closed: ${evt}`);
116
+ * }, (orgId, evt) => {
117
+ * console.log(`connection error: ${evt}`);
118
+ * })
113
119
  * .then((webSocket) => {
114
120
  * console.log(webSocket);
115
121
  * })
@@ -121,7 +127,7 @@ var Bus = function () {
121
127
 
122
128
  _createClass(Bus, [{
123
129
  key: 'connect',
124
- value: function connect(organizationId) {
130
+ value: function connect(organizationId, onClose, onError) {
125
131
  var _this = this;
126
132
 
127
133
  return new Promise(function (resolve, reject) {
@@ -142,13 +148,31 @@ var Bus = function () {
142
148
  resolve(_this._webSockets[organizationId]);
143
149
  };
144
150
 
145
- ws.onclose = function (event) {
151
+ ws.addEventListener("close", function (event) {
146
152
  _this._webSockets[organizationId] = null;
147
- };
153
+ if (onClose) {
154
+ try {
155
+ onClose(organizationId, event);
156
+ } catch (ex) {
157
+ console.log('Message Bus Error calling onClose callback: ', ex);
158
+ }
159
+ }
160
+ });
148
161
 
149
- ws.onerror = function (errorEvent) {
150
- reject(errorEvent);
151
- };
162
+ ws.addEventListener("error", function (errorEvent) {
163
+ var connected = _this._webSockets[organizationId] != null;
164
+ _this._webSockets[organizationId] = null;
165
+ if (!connected) {
166
+ reject(errorEvent);
167
+ }
168
+ if (onError) {
169
+ try {
170
+ onError(organizationId, errorEvent);
171
+ } catch (ex) {
172
+ console.log('Message Bus Error calling onError callback: ', ex);
173
+ }
174
+ }
175
+ });
152
176
  }).catch(function (err) {
153
177
  reject(err);
154
178
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["bus/index.js"],"names":["defaultBusConfig","autoAcknowledge","Bus","sdk","request","config","baseUrl","audiences","bus","host","baseWebSocketUrl","webSocket","_baseWebSocketUrl","_baseUrl","_request","_sdk","_webSockets","_config","Object","assign","channels","Channels","organizationId","Promise","resolve","reject","auth","getCurrentApiToken","then","apiToken","ws","WebSocket","headers","Authorization","onopen","event","WebSocketConnection","onclose","onerror","errorEvent","catch","err"],"mappings":";;;;;;;;AAAA;;;;AAEA;;;;AACA;;;;;;;;AAEA;;;;;;;;;;;;;;;;;;;;;;;AAuBA;;;;;;;;;AASA;;;;;;;AAOA;;;AAGA,IAAMA,mBAAmB;AACvBC,mBAAiB;AADM,CAAzB;;AAIA;;;;;;;;IAOMC,G;AACJ;;;;;AAKA,eAAYC,GAAZ,EAAiBC,OAAjB,EAA0BC,MAA1B,EAAkC;AAAA;;AAChC,QAAMC,eAAaH,IAAIE,MAAJ,CAAWE,SAAX,CAAqBC,GAArB,CAAyBC,IAA5C;AACA,QAAMC,wBAAsBP,IAAIE,MAAJ,CAAWE,SAAX,CAAqBC,GAArB,CAAyBG,SAArD;;AAEA,SAAKC,iBAAL,GAAyBF,gBAAzB;AACA,SAAKG,QAAL,GAAgBP,OAAhB;AACA,SAAKQ,QAAL,GAAgBV,OAAhB;AACA,SAAKW,IAAL,GAAYZ,GAAZ;AACA,SAAKa,WAAL,GAAmB,EAAnB;AACA,SAAKC,OAAL,GAAeC,OAAOC,MAAP,CAAc,EAAd,EAAkBnB,gBAAlB,EAAoCK,MAApC,CAAf;;AAEA,SAAKe,QAAL,GAAgB,IAAIC,kBAAJ,CAAalB,GAAb,EAAkBC,OAAlB,EAA2BE,OAA3B,CAAhB;AACD;;AAED;;;;;;;;;;;;;;;;;;;;;;;4BAmBQgB,c,EAAgB;AAAA;;AACtB,aAAO,IAAIC,OAAJ,CAAY,UAACC,OAAD,EAAUC,MAAV,EAAqB;AACtC,YAAI,MAAKT,WAAL,CAAiBM,cAAjB,CAAJ,EAAsC;AACpC,iBAAOE,QAAQ,MAAKR,WAAL,CAAiBM,cAAjB,CAAR,CAAP;AACD;;AAED,eAAO,MAAKP,IAAL,CAAUW,IAAV,CACJC,kBADI,CACe,YADf,EAEJC,IAFI,CAEC,UAACC,QAAD,EAAc;AAClB,cAAMC,KAAK,IAAIC,YAAJ,CACN,MAAKnB,iBADC,uBACkCU,cADlC,cAET,EAFS,EAGT;AACEU,qBAAS;AACPC,yCAAyBJ;AADlB;AADX,WAHS,CAAX;;AAUAC,aAAGI,MAAH,GAAY,UAACC,KAAD,EAAW;AACrB,kBAAKnB,WAAL,CAAiBM,cAAjB,IAAmC,IAAIc,6BAAJ,CACjCN,EADiC,EAEjCR,cAFiC,EAGjC,MAAKL,OAAL,CAAahB,eAHoB,CAAnC;;AAMAuB,oBAAQ,MAAKR,WAAL,CAAiBM,cAAjB,CAAR;AACD,WARD;;AAUAQ,aAAGO,OAAH,GAAa,UAACF,KAAD,EAAW;AACtB,kBAAKnB,WAAL,CAAiBM,cAAjB,IAAmC,IAAnC;AACD,WAFD;;AAIAQ,aAAGQ,OAAH,GAAa,UAACC,UAAD,EAAgB;AAC3Bd,mBAAOc,UAAP;AACD,WAFD;AAGD,SA9BI,EA+BJC,KA/BI,CA+BE,UAACC,GAAD,EAAS;AACdhB,iBAAOgB,GAAP;AACD,SAjCI,CAAP;AAkCD,OAvCM,CAAP;AAwCD;;AAED;;;;;;;;;;;;;;2CAWuBnB,c,EAAgB;AACrC,aAAO,KAAKN,WAAL,CAAiBM,cAAjB,CAAP;AACD;;;;;;kBAGYpB,G","file":"index.js","sourcesContent":["import WebSocket from 'ws';\n\nimport Channels from './channels';\nimport WebSocketConnection from './webSocketConnection';\n\n/**\n * The raw WebSocket created by ws\n *\n * @typedef {Object} WebSocket\n * @property {function} addEventListener Register an event listener emulating the EventTarget interface\n * @property {string} binaryType A string indicating the type of binary data being transmitted by the connection. This should be one of \"nodebuffer\", \"arraybuffer\" or \"fragments\". Defaults to \"nodebuffer\".\n * @property {number} bufferedAmount The number of bytes of data that have been queued using calls to send() but not yet transmitted to the network.\n * @property {function} close Initiate a closing handshake\n * @property {Object} extensions An object containing the negotiated extensions\n * @property {function} onclose An event listener to be called when connection is closed\n * @property {function} onerror An event listener to be called when an error occurs\n * @property {function} onmessage An event listener to be called when a message is received from the server\n * @property {function} onopen An event listener to be called when the connection is established\n * @property {function} ping Send a ping to the WebSocket server\n * @property {function} pong Send a pong to the WebSocket server\n * @property {string} protocol The subprotocol selected by the server\n * @property {number} readyState The current state of the connection\n * @property {function} removeEventListener Removes an event listener emulating the EventTarget interface\n * @property {function} send Send data through the open WebSocket connection\n * @property {function} terminate Forcibly close the connection\n * @property {string} url The URL of the WebSocket server\n */\n\n/**\n * A wrapper around the raw WebSocket to provide a finite set of operations\n *\n * @typedef {Object} WebSocketConnection\n * @property {function} close Closes the WebSocket connection to the message bus server\n * @property {string} _organizationId The organization id for the open WebSocket connection\n * @property {WebSocket} _webSocket The raw WebSocket connection to the message bus\n */\n\n/**\n * Configuration object for the Bus\n *\n * @typedef {Object} BusConfig\n * @property {boolean} autoAcknowledge\n */\n\n/**\n * @type {BusConfig}\n */\nconst defaultBusConfig = {\n autoAcknowledge: true\n};\n\n/**\n * Module that provides access to the message bus. This is for Node\n * environments. Documentation for browser environments is found under\n * `BrowserBus`.\n *\n * @typicalname contxtSdk.bus\n */\nclass Bus {\n /**\n * @param {Object} sdk An instance of the SDK so the module can communicate with other modules\n * @param {Object} request An instance of the request module tied to this module's audience.\n * @param {BusConfig} config A config object for the Bus instance\n */\n constructor(sdk, request, config) {\n const baseUrl = `${sdk.config.audiences.bus.host}`;\n const baseWebSocketUrl = `${sdk.config.audiences.bus.webSocket}`;\n\n this._baseWebSocketUrl = baseWebSocketUrl;\n this._baseUrl = baseUrl;\n this._request = request;\n this._sdk = sdk;\n this._webSockets = {};\n this._config = Object.assign({}, defaultBusConfig, config);\n\n this.channels = new Channels(sdk, request, baseUrl);\n }\n\n /**\n * Connects to the message bus via websocket.\n * If a connection already exists for that organization id, the connection is returned, otherwise a new connection is created and returned.\n *\n * @param {string} organizationId UUID corresponding with an organization\n *\n * @returns {Promise}\n * @fulfill {WebSocketConnection}\n * @reject {errorEvent} The error event\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * console.log(webSocket);\n * })\n * .catch((errorEvent) => {\n * console.log(errorEvent);\n * });\n */\n connect(organizationId) {\n return new Promise((resolve, reject) => {\n if (this._webSockets[organizationId]) {\n return resolve(this._webSockets[organizationId]);\n }\n\n return this._sdk.auth\n .getCurrentApiToken('contxtAuth')\n .then((apiToken) => {\n const ws = new WebSocket(\n `${this._baseWebSocketUrl}/organizations/${organizationId}/stream`,\n [],\n {\n headers: {\n Authorization: `Bearer ${apiToken}`\n }\n }\n );\n\n ws.onopen = (event) => {\n this._webSockets[organizationId] = new WebSocketConnection(\n ws,\n organizationId,\n this._config.autoAcknowledge\n );\n\n resolve(this._webSockets[organizationId]);\n };\n\n ws.onclose = (event) => {\n this._webSockets[organizationId] = null;\n };\n\n ws.onerror = (errorEvent) => {\n reject(errorEvent);\n };\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n /**\n * Gets the WebSocketConnection for an organization id\n * If a connection already exists for that organization id, the connection is returned, otherwise returns undefined.\n *\n * @param {string} organizationId UUID corresponding with an organization\n *\n * @returns {WebSocketConnection}\n *\n * @example\n * const messageBusWebSocket = contxtSdk.bus.getWebSocketConnection('4f0e51c6-728b-4892-9863-6d002e61204d');\n */\n getWebSocketConnection(organizationId) {\n return this._webSockets[organizationId];\n }\n}\n\nexport default Bus;\n"]}
1
+ {"version":3,"sources":["bus/index.js"],"names":["defaultBusConfig","autoAcknowledge","Bus","sdk","request","config","baseUrl","audiences","bus","host","baseWebSocketUrl","webSocket","_baseWebSocketUrl","_baseUrl","_request","_sdk","_webSockets","_config","Object","assign","channels","Channels","organizationId","onClose","onError","Promise","resolve","reject","auth","getCurrentApiToken","then","apiToken","ws","WebSocket","headers","Authorization","onopen","event","WebSocketConnection","addEventListener","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L,CAAiBM,cAAjB,CAAP;AACD;;;;;;kBAGYpB,G","file":"index.js","sourcesContent":["import WebSocket from 'ws';\n\nimport Channels from './channels';\nimport WebSocketConnection from './webSocketConnection';\n\n/**\n * The raw WebSocket created by ws\n *\n * @typedef {Object} WebSocket\n * @property {function} addEventListener Register an event listener emulating the EventTarget interface\n * @property {string} binaryType A string indicating the type of binary data being transmitted by the connection. This should be one of \"nodebuffer\", \"arraybuffer\" or \"fragments\". Defaults to \"nodebuffer\".\n * @property {number} bufferedAmount The number of bytes of data that have been queued using calls to send() but not yet transmitted to the network.\n * @property {function} close Initiate a closing handshake\n * @property {Object} extensions An object containing the negotiated extensions\n * @property {function} onclose An event listener to be called when connection is closed\n * @property {function} onerror An event listener to be called when an error occurs\n * @property {function} onmessage An event listener to be called when a message is received from the server\n * @property {function} onopen An event listener to be called when the connection is established\n * @property {function} ping Send a ping to the WebSocket server\n * @property {function} pong Send a pong to the WebSocket server\n * @property {string} protocol The subprotocol selected by the server\n * @property {number} readyState The current state of the connection\n * @property {function} removeEventListener Removes an event listener emulating the EventTarget interface\n * @property {function} send Send data through the open WebSocket connection\n * @property {function} terminate Forcibly close the connection\n * @property {string} url The URL of the WebSocket server\n */\n\n/**\n * A wrapper around the raw WebSocket to provide a finite set of operations\n *\n * @typedef {Object} WebSocketConnection\n * @property {function} close Closes the WebSocket connection to the message bus server\n * @property {string} _organizationId The organization id for the open WebSocket connection\n * @property {WebSocket} _webSocket The raw WebSocket connection to the message bus\n */\n\n/**\n * Configuration object for the Bus\n *\n * @typedef {Object} BusConfig\n * @property {boolean} autoAcknowledge\n */\n\n/**\n * @type {BusConfig}\n */\nconst defaultBusConfig = {\n autoAcknowledge: true\n};\n\n/**\n * Module that provides access to the message bus. This is for Node\n * environments. Documentation for browser environments is found under\n * `BrowserBus`.\n *\n * @typicalname contxtSdk.bus\n */\nclass Bus {\n /**\n * @param {Object} sdk An instance of the SDK so the module can communicate with other modules\n * @param {Object} request An instance of the request module tied to this module's audience.\n * @param {BusConfig} config A config object for the Bus instance\n */\n constructor(sdk, request, config) {\n const baseUrl = `${sdk.config.audiences.bus.host}`;\n const baseWebSocketUrl = `${sdk.config.audiences.bus.webSocket}`;\n\n this._baseWebSocketUrl = baseWebSocketUrl;\n this._baseUrl = baseUrl;\n this._request = request;\n this._sdk = sdk;\n this._webSockets = {};\n this._config = Object.assign({}, defaultBusConfig, config);\n\n this.channels = new Channels(sdk, request, baseUrl);\n }\n\n /**\n * Connects to the message bus via websocket.\n * If a connection already exists for that organization id, the connection is returned, otherwise a new connection is created and returned.\n *\n * @param {string} organizationId UUID corresponding with an organization\n * @param {function} onClose optional callback to be executed when the connection is closed\n * @param {function} onError optional callback to be executed when the connection encounters an error\n *\n * @returns {Promise}\n * @fulfill {WebSocketConnection}\n * @reject {errorEvent} The error event\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d', (orgId, evt) => {\n * console.log(`connection closed: ${evt}`);\n * }, (orgId, evt) => {\n * console.log(`connection error: ${evt}`);\n * })\n * .then((webSocket) => {\n * console.log(webSocket);\n * })\n * .catch((errorEvent) => {\n * console.log(errorEvent);\n * });\n */\n connect(organizationId, onClose, onError) {\n return new Promise((resolve, reject) => {\n if (this._webSockets[organizationId]) {\n return resolve(this._webSockets[organizationId]);\n }\n\n return this._sdk.auth\n .getCurrentApiToken('contxtAuth')\n .then((apiToken) => {\n const ws = new WebSocket(\n `${this._baseWebSocketUrl}/organizations/${organizationId}/stream`,\n [],\n {\n headers: {\n Authorization: `Bearer ${apiToken}`\n }\n }\n );\n\n ws.onopen = (event) => {\n this._webSockets[organizationId] = new WebSocketConnection(\n ws,\n organizationId,\n this._config.autoAcknowledge\n );\n\n resolve(this._webSockets[organizationId]);\n };\n\n ws.addEventListener(\"close\", (event) => {\n this._webSockets[organizationId] = null;\n if (onClose) {\n try {\n onClose(organizationId, event);\n } catch (ex) {\n console.log('Message Bus Error calling onClose callback: ', ex)\n }\n }\n });\n\n ws.addEventListener(\"error\", (errorEvent) => {\n const connected = this._webSockets[organizationId] != null;\n this._webSockets[organizationId] = null;\n if (!connected) {\n reject(errorEvent)\n }\n if (onError) {\n try {\n onError(organizationId, errorEvent);\n } catch (ex) {\n console.log('Message Bus Error calling onError callback: ', ex)\n }\n }\n });\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n /**\n * Gets the WebSocketConnection for an organization id\n * If a connection already exists for that organization id, the connection is returned, otherwise returns undefined.\n *\n * @param {string} organizationId UUID corresponding with an organization\n *\n * @returns {WebSocketConnection}\n *\n * @example\n * const messageBusWebSocket = contxtSdk.bus.getWebSocketConnection('4f0e51c6-728b-4892-9863-6d002e61204d');\n */\n getWebSocketConnection(organizationId) {\n return this._webSockets[organizationId];\n }\n}\n\nexport default Bus;\n"]}
@@ -79,7 +79,7 @@ var WebSocketConnection = function () {
79
79
  this._autoAck = autoAcknowledge;
80
80
 
81
81
  if (this._webSocket) {
82
- this._webSocket.onerror = this._onError;
82
+ this._webSocket.addEventListener("error", this._onError);
83
83
  this._webSocket.onmessage = this._onMessage;
84
84
  }
85
85
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["bus/webSocketConnection.js"],"names":["WebSocketConnection","webSocket","organizationId","autoAcknowledge","_onError","error","_messageHandlers","console","log","_onMessage","message","messageData","JSON","parse","data","err","Error","id","_organizationId","_webSocket","_autoAck","onerror","onmessage","token","Promise","reject","_isConnected","_registerSingleMessageHandler","close","serviceClientId","channel","service_id","group","handler","errorHandler","params","then","result","subscription","subscriptionMessage","resolve","ack","_acknowledge","body","res","throwable","acknowledgedMessageId","message_id","method","messageId","send","stringify","jsonrpc","readyState","OPEN"],"mappings":";;;;;;;;AAAA;;AACA;;;;;;;;AAEA;;;;;;;AAOA;;;;;;;;;;;AAWA;;;;;;IAMMA,mB;AACJ;;;;;AAKA,+BAAYC,SAAZ,EAAuBC,cAAvB,EAA+D;AAAA;;AAAA,QAAxBC,eAAwB,uEAAN,IAAM;;AAAA;;AAAA,SAs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,qBAAOpB,OAAOoB,SAAP,CAAP;AACD;AACF,WAzBM,CAAP;AA0BD,SA3BD;;AA6BA,eAAOR,MAAP;AACD,OAhCI,CAAP;AAkCD;;AAED;;;;;;;;;;;;;iCAUaS,qB,EAAuB;AAClC,UAAI,CAAC,KAAKpB,YAAL,EAAL,EAA0B;AACxB,eAAOF,QAAQC,MAAR,CAAe,IAAIT,KAAJ,CAAU,+BAAV,CAAf,CAAP;AACD;;AAED,aAAO,KAAKW,6BAAL,CAAmC,aAAnC,EAAkD;AACvDoB,oBAAYD;AAD2C,OAAlD,CAAP;AAGD;;AAED;;;;;;;;;;;;kDAS8BE,M,EAAQb,M,EAAQ;AAAA;;AAC5C,aAAO,IAAIX,OAAJ,CAAY,UAACgB,OAAD,EAAUf,MAAV,EAAqB;AACtC,YAAMwB,YAAY,eAAlB;;AAEA,eAAK3C,gBAAL,CAAsB2C,SAAtB,IAAmC,UAACvC,OAAD,EAAa;AAC9C,cAAML,QAAQK,QAAQL,KAAtB;AACA,iBAAO,OAAKC,gBAAL,CAAsB2C,SAAtB,CAAP;;AAEA,cAAI5C,KAAJ,EAAW;AACT,mBAAOoB,OAAOpB,KAAP,CAAP;AACD;;AAED,iBAAOmC,QAAQ9B,QAAQ2B,MAAhB,CAAP;AACD,SATD;;AAWA,eAAKlB,UAAL,CAAgB+B,IAAhB,CACEtC,KAAKuC,SAAL,CAAe;AACbC,mBAAS,KADI;AAEbJ,kCAAsBA,MAFT;AAGbb,wBAHa;AAIblB,cAAIgC;AAJS,SAAf,CADF;AAQD,OAtBM,CAAP;AAuBD;;AAED;;;;;;;;;;mCAOe;AACb,aACE,KAAK9B,UAAL,IAAmB,KAAKA,UAAL,CAAgBkC,UAAhB,KAA+B,KAAKlC,UAAL,CAAgBmC,IADpE;AAGD;;;;;;kBAGYtD,mB","file":"webSocketConnection.js","sourcesContent":["import { v4 as uuid } from 'uuid';\nimport once from 'lodash.once';\n\n/**\n * The WebSocket Error Event\n *\n * @typedef {Object} WebSocketError\n * @property {string} type The event type\n */\n\n/**\n * The WebSocket Message Event\n *\n * @typedef {Object} WebSocketMessage\n * @property {Object} data The data sent by the message emitter\n * @property {string} origin A USVString representing the origin of the message emitter\n * @property {string} lastEventId A DOMString representing a unique ID for the event\n * @property {Object} source A MessageEventSource (which can be a WindowProxy, MessagePort, or ServiceWorker object) representing the message emitter\n * @property {Array} ports MessagePort objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker)\n */\n\n/**\n * Module that wraps the websocket connection to the message bus to provide the\n * developer with a specific set of functionality. This is for Node\n * environments. Documentation for browser environments is found under\n * `BrowserWebSocketConnection`.\n */\nclass WebSocketConnection {\n /**\n * @param {WebSocket} webSocket A WebSocket connection to the message bus\n * @param {string} organizationId UUID corresponding with an organization\n * @param {boolean} autoAcknowledge Whether the messages should be ACK'd explicitly or not\n */\n constructor(webSocket, organizationId, autoAcknowledge = true) {\n this._messageHandlers = {};\n this._organizationId = organizationId;\n this._webSocket = webSocket;\n this._autoAck = autoAcknowledge;\n\n if (this._webSocket) {\n this._webSocket.onerror = this._onError;\n this._webSocket.onmessage = this._onMessage;\n }\n }\n\n /**\n * Sends a message to the message bus to authorize a channel\n *\n * @param {string} token JSON Web Signature containing the channel and actions needed for authorization\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.authorize(token).then(() => {\n * console.log(\"authorization successful\")\n * })\n * .catch((authError) => {\n * console.log(authError)\n * });\n * })\n * });\n */\n authorize(token) {\n if (!token) {\n return Promise.reject(new Error('A token is required for authorization'));\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Authorize', { token });\n }\n\n /**\n * Closes the websocket connection\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.close()\n * })\n * .catch((errorEvent) => {\n * console.log(errorEvent);\n * });\n */\n close() {\n this._webSocket.close();\n }\n\n /**\n * Handles WebSocket errors.\n * The `ws` library also closes the socket when an error occurs.\n * Since the socket connection closes, the jsonRpcId and message handlers are cleared\n *\n * @param {WebSocketError} error The error event thrown\n *\n * @private\n */\n _onError = (error) => {\n this._messageHandlers = {};\n\n console.log('Message Bus WebSocket Error: ', error);\n };\n\n /**\n * Handles messages sent from the Message Bus WebSocket connection.\n *\n * @param {WebSocketMessage} message The message event recieved over the WebSocket connection\n *\n * @private\n */\n _onMessage = (message) => {\n let messageData;\n\n try {\n messageData = JSON.parse(message.data);\n } catch (err) {\n throw new Error('Invalid JSON in message');\n }\n\n if (this._messageHandlers[messageData.id]) {\n this._messageHandlers[messageData.id](messageData);\n }\n };\n\n /**\n * Publishes a message to a specific channel on the message bus\n *\n * @param {string} serviceClientId Client ID of the message bus service\n * @param {string} channel Message bus channel the message is being sent to\n * @param {Any} message Message being sent to the message bus. Must be valid JSON.\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.publish('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', {\"example\": 1}).then(() => {\n * console.log(\"publish successful\")\n * })\n * .catch((error) => {\n * console.log(error)\n * });\n * });\n */\n publish(serviceClientId, channel, message) {\n if (!serviceClientId) {\n return Promise.reject(\n new Error('A service client id is required for publishing')\n );\n }\n\n if (!channel) {\n return Promise.reject(new Error('A channel is required for publishing'));\n }\n\n if (!message) {\n return Promise.reject(new Error('A message is required for publishing'));\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Publish', {\n service_id: serviceClientId,\n channel,\n message\n });\n }\n\n /**\n * Subscribes to a specific channel on the message bus and handles messages as they are received. When the handler is\n * called, the message is automatically acknowledged after the message completes except whenever an Error is thrown.\n * The user can also programmatically control when the message is acknowledged by calling `ack` at any time.\n *\n * @param {string} serviceClientId Client ID of the message bus service\n * @param {string} channel Message bus channel the message is being sent to\n * @param {string} [group] A unique identifier for the subscriber that can be shared between connections\n * @param {function} handler A function that gets invoked with every received message\n * @param {function} errorHandler A function that gets invoked with every error\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', 'test-sub', (message) => {\n * console.log('Message received: ', message);\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', 'test-sub', (message, ack) => {\n * console.log('Message received: ', message);\n *\n * ack();\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', (message) => {\n * return db.save(message);\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', (message, ack) => {\n * return db.save(message)\n * .then(ack)\n * .then(() => {\n * // additional processing\n * });\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n */\n subscribe(serviceClientId, channel, group, handler, errorHandler) {\n if (typeof group === 'function') {\n errorHandler = handler;\n handler = group;\n group = null;\n }\n\n if (!serviceClientId) {\n return Promise.reject(\n new Error('A service client id is required for subscribing')\n );\n }\n\n if (!channel) {\n return Promise.reject(new Error('A channel is required for subscribing'));\n }\n\n if (!handler) {\n return Promise.reject(\n new Error('A message handler is required for subscribing')\n );\n }\n\n if (!errorHandler) {\n return Promise.reject(\n new Error('An error handler is required for subscribing')\n );\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n const params = {\n service_id: serviceClientId,\n channel\n };\n\n if (group) {\n params.group = group;\n }\n\n return this._registerSingleMessageHandler('Subscribe', params).then(\n (result) => {\n this._messageHandlers[result.subscription] = (subscriptionMessage) => {\n return new Promise((resolve, reject) => {\n const error = subscriptionMessage.error;\n const result = subscriptionMessage.result;\n\n if (error) {\n return resolve(errorHandler(error));\n }\n\n try {\n const ack = once(() => {\n return this._acknowledge(result.id);\n });\n\n return resolve(\n Promise.resolve(handler(result.body, ack)).then((res) => {\n if (this._autoAck) {\n return ack().then(() => res);\n }\n\n return res;\n })\n );\n } catch (throwable) {\n return reject(throwable);\n }\n });\n };\n\n return result;\n }\n );\n }\n\n /**\n * Acknowledges a Message ID has been received and processed\n *\n * @returns {Promise}\n * @param acknowledgedMessageId {string} The Message ID that has been received\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @private\n */\n _acknowledge(acknowledgedMessageId) {\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Acknowledge', {\n message_id: acknowledgedMessageId\n });\n }\n\n /**\n * Registers a JSON RPC message handler that expects only one response.\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @private\n */\n _registerSingleMessageHandler(method, params) {\n return new Promise((resolve, reject) => {\n const messageId = uuid();\n\n this._messageHandlers[messageId] = (message) => {\n const error = message.error;\n delete this._messageHandlers[messageId];\n\n if (error) {\n return reject(error);\n }\n\n return resolve(message.result);\n };\n\n this._webSocket.send(\n JSON.stringify({\n jsonrpc: '2.0',\n method: `MessageBus.${method}`,\n params,\n id: messageId\n })\n );\n });\n }\n\n /**\n * Checks whether the current WebSocket is connected to the Message Bus service.\n *\n * @returns {boolean} Whether the WebSocket is connected to the Message Bus service\n *\n * @private\n */\n _isConnected() {\n return (\n this._webSocket && this._webSocket.readyState === this._webSocket.OPEN\n );\n }\n}\n\nexport default WebSocketConnection;\n"]}
1
+ {"version":3,"sources":["bus/webSocketConnection.js"],"names":["WebSocketConnection","webSocket","organizationId","autoAcknowledge","_onError","error","_messageHandlers","console","log","_onMessage","message","messageData","JSON","parse","data","err","Error","id","_organizationId","_webSocket","_autoAck","addEventListener","onmessage","token","Promise","reject","_isConnected","_registerSingleMessageHandler","close","serviceClientId","channel","service_id","group","handler","errorHandler","params","then","result","subscription","subscriptionMessage","resolve","ack","_acknowledge","body","res","throwable","acknowledgedMessageId","message_id","method","messageId","send","stringify","jsonrpc","readyState","OPEN"],"mappings":";;;;;;;;AAAA;;AACA;;;;;;;;AAEA;;;;;;;AAOA;;;;;;;;;;;AAWA;;;;;;IAMMA,mB;AACJ;;;;;AAKA,+BAAYC,SAAZ,EAAuBC,cAAvB,EAA+D;AAAA;;AAAA,QAAxBC,eAAwB,uEAAN,IAAM;;AAAA;;AAAA,SAsE/DC,QAtE+D,GAsEpD,UAACC,KAAD,EAAW;AACpB,YAAKC,gBAAL,GAAwB,EAAxB;;AAEAC,cAAQC,GAAR,CAAY,+BAAZ,EAA6CH,KAA7C;AACD,KA1E8D;;AAAA,SAmF/DI,UAnF+D,GAmFlD,UAACC,OAAD,EAAa;AACxB,UAAIC,oBAAJ;;AAEA,UAAI;AACFA,sBAAcC,KAAKC,KAAL,CAAWH,QAAQI,IAAnB,CAAd;AACD,OAFD,CAEE,OAAOC,GAAP,EAAY;AACZ,cAAM,IAAIC,KAAJ,CAAU,yBAAV,CAAN;AACD;;AAED,UAAI,MAAKV,gBAAL,CAAsBK,YAAYM,EAAlC,CAAJ,EAA2C;AACzC,cAAKX,gBAAL,C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AAIX,OAAJ,CAAY,UAACgB,OAAD,EAAUf,MAAV,EAAqB;AACtC,YAAMwB,YAAY,eAAlB;;AAEA,eAAK3C,gBAAL,CAAsB2C,SAAtB,IAAmC,UAACvC,OAAD,EAAa;AAC9C,cAAML,QAAQK,QAAQL,KAAtB;AACA,iBAAO,OAAKC,gBAAL,CAAsB2C,SAAtB,CAAP;;AAEA,cAAI5C,KAAJ,EAAW;AACT,mBAAOoB,OAAOpB,KAAP,CAAP;AACD;;AAED,iBAAOmC,QAAQ9B,QAAQ2B,MAAhB,CAAP;AACD,SATD;;AAWA,eAAKlB,UAAL,CAAgB+B,IAAhB,CACEtC,KAAKuC,SAAL,CAAe;AACbC,mBAAS,KADI;AAEbJ,kCAAsBA,MAFT;AAGbb,wBAHa;AAIblB,cAAIgC;AAJS,SAAf,CADF;AAQD,OAtBM,CAAP;AAuBD;;AAED;;;;;;;;;;mCAOe;AACb,aACE,KAAK9B,UAAL,IAAmB,KAAKA,UAAL,CAAgBkC,UAAhB,KAA+B,KAAKlC,UAAL,CAAgBmC,IADpE;AAGD;;;;;;kBAGYtD,mB","file":"webSocketConnection.js","sourcesContent":["import { v4 as uuid } from 'uuid';\nimport once from 'lodash.once';\n\n/**\n * The WebSocket Error Event\n *\n * @typedef {Object} WebSocketError\n * @property {string} type The event type\n */\n\n/**\n * The WebSocket Message Event\n *\n * @typedef {Object} WebSocketMessage\n * @property {Object} data The data sent by the message emitter\n * @property {string} origin A USVString representing the origin of the message emitter\n * @property {string} lastEventId A DOMString representing a unique ID for the event\n * @property {Object} source A MessageEventSource (which can be a WindowProxy, MessagePort, or ServiceWorker object) representing the message emitter\n * @property {Array} ports MessagePort objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker)\n */\n\n/**\n * Module that wraps the websocket connection to the message bus to provide the\n * developer with a specific set of functionality. This is for Node\n * environments. Documentation for browser environments is found under\n * `BrowserWebSocketConnection`.\n */\nclass WebSocketConnection {\n /**\n * @param {WebSocket} webSocket A WebSocket connection to the message bus\n * @param {string} organizationId UUID corresponding with an organization\n * @param {boolean} autoAcknowledge Whether the messages should be ACK'd explicitly or not\n */\n constructor(webSocket, organizationId, autoAcknowledge = true) {\n this._messageHandlers = {};\n this._organizationId = organizationId;\n this._webSocket = webSocket;\n this._autoAck = autoAcknowledge;\n\n if (this._webSocket) {\n this._webSocket.addEventListener(\"error\", this._onError);\n this._webSocket.onmessage = this._onMessage;\n }\n }\n\n /**\n * Sends a message to the message bus to authorize a channel\n *\n * @param {string} token JSON Web Signature containing the channel and actions needed for authorization\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.authorize(token).then(() => {\n * console.log(\"authorization successful\")\n * })\n * .catch((authError) => {\n * console.log(authError)\n * });\n * })\n * });\n */\n authorize(token) {\n if (!token) {\n return Promise.reject(new Error('A token is required for authorization'));\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Authorize', { token });\n }\n\n /**\n * Closes the websocket connection\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.close()\n * })\n * .catch((errorEvent) => {\n * console.log(errorEvent);\n * });\n */\n close() {\n this._webSocket.close();\n }\n\n /**\n * Handles WebSocket errors.\n * The `ws` library also closes the socket when an error occurs.\n * Since the socket connection closes, the jsonRpcId and message handlers are cleared\n *\n * @param {WebSocketError} error The error event thrown\n *\n * @private\n */\n _onError = (error) => {\n this._messageHandlers = {};\n\n console.log('Message Bus WebSocket Error: ', error);\n };\n\n /**\n * Handles messages sent from the Message Bus WebSocket connection.\n *\n * @param {WebSocketMessage} message The message event recieved over the WebSocket connection\n *\n * @private\n */\n _onMessage = (message) => {\n let messageData;\n\n try {\n messageData = JSON.parse(message.data);\n } catch (err) {\n throw new Error('Invalid JSON in message');\n }\n\n if (this._messageHandlers[messageData.id]) {\n this._messageHandlers[messageData.id](messageData);\n }\n };\n\n /**\n * Publishes a message to a specific channel on the message bus\n *\n * @param {string} serviceClientId Client ID of the message bus service\n * @param {string} channel Message bus channel the message is being sent to\n * @param {Any} message Message being sent to the message bus. Must be valid JSON.\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.publish('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', {\"example\": 1}).then(() => {\n * console.log(\"publish successful\")\n * })\n * .catch((error) => {\n * console.log(error)\n * });\n * });\n */\n publish(serviceClientId, channel, message) {\n if (!serviceClientId) {\n return Promise.reject(\n new Error('A service client id is required for publishing')\n );\n }\n\n if (!channel) {\n return Promise.reject(new Error('A channel is required for publishing'));\n }\n\n if (!message) {\n return Promise.reject(new Error('A message is required for publishing'));\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Publish', {\n service_id: serviceClientId,\n channel,\n message\n });\n }\n\n /**\n * Subscribes to a specific channel on the message bus and handles messages as they are received. When the handler is\n * called, the message is automatically acknowledged after the message completes except whenever an Error is thrown.\n * The user can also programmatically control when the message is acknowledged by calling `ack` at any time.\n *\n * @param {string} serviceClientId Client ID of the message bus service\n * @param {string} channel Message bus channel the message is being sent to\n * @param {string} [group] A unique identifier for the subscriber that can be shared between connections\n * @param {function} handler A function that gets invoked with every received message\n * @param {function} errorHandler A function that gets invoked with every error\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', 'test-sub', (message) => {\n * console.log('Message received: ', message);\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', 'test-sub', (message, ack) => {\n * console.log('Message received: ', message);\n *\n * ack();\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', (message) => {\n * return db.save(message);\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n *\n * @example\n * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')\n * .then((webSocket) => {\n * webSocket.subscribe('GCXd2bwE9fgvqxygrx2J7TkDJ3ef', 'feed:1', (message, ack) => {\n * return db.save(message)\n * .then(ack)\n * .then(() => {\n * // additional processing\n * });\n * }, (error) => {\n * console.log('Error received: ', error);\n * });\n * });\n */\n subscribe(serviceClientId, channel, group, handler, errorHandler) {\n if (typeof group === 'function') {\n errorHandler = handler;\n handler = group;\n group = null;\n }\n\n if (!serviceClientId) {\n return Promise.reject(\n new Error('A service client id is required for subscribing')\n );\n }\n\n if (!channel) {\n return Promise.reject(new Error('A channel is required for subscribing'));\n }\n\n if (!handler) {\n return Promise.reject(\n new Error('A message handler is required for subscribing')\n );\n }\n\n if (!errorHandler) {\n return Promise.reject(\n new Error('An error handler is required for subscribing')\n );\n }\n\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n const params = {\n service_id: serviceClientId,\n channel\n };\n\n if (group) {\n params.group = group;\n }\n\n return this._registerSingleMessageHandler('Subscribe', params).then(\n (result) => {\n this._messageHandlers[result.subscription] = (subscriptionMessage) => {\n return new Promise((resolve, reject) => {\n const error = subscriptionMessage.error;\n const result = subscriptionMessage.result;\n\n if (error) {\n return resolve(errorHandler(error));\n }\n\n try {\n const ack = once(() => {\n return this._acknowledge(result.id);\n });\n\n return resolve(\n Promise.resolve(handler(result.body, ack)).then((res) => {\n if (this._autoAck) {\n return ack().then(() => res);\n }\n\n return res;\n })\n );\n } catch (throwable) {\n return reject(throwable);\n }\n });\n };\n\n return result;\n }\n );\n }\n\n /**\n * Acknowledges a Message ID has been received and processed\n *\n * @returns {Promise}\n * @param acknowledgedMessageId {string} The Message ID that has been received\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @private\n */\n _acknowledge(acknowledgedMessageId) {\n if (!this._isConnected()) {\n return Promise.reject(new Error('WebSocket connection not open'));\n }\n\n return this._registerSingleMessageHandler('Acknowledge', {\n message_id: acknowledgedMessageId\n });\n }\n\n /**\n * Registers a JSON RPC message handler that expects only one response.\n *\n * @returns {Promise}\n * @fulfill\n * @reject {error} The error event from the WebSocket or the error message from the message bus\n *\n * @private\n */\n _registerSingleMessageHandler(method, params) {\n return new Promise((resolve, reject) => {\n const messageId = uuid();\n\n this._messageHandlers[messageId] = (message) => {\n const error = message.error;\n delete this._messageHandlers[messageId];\n\n if (error) {\n return reject(error);\n }\n\n return resolve(message.result);\n };\n\n this._webSocket.send(\n JSON.stringify({\n jsonrpc: '2.0',\n method: `MessageBus.${method}`,\n params,\n id: messageId\n })\n );\n });\n }\n\n /**\n * Checks whether the current WebSocket is connected to the Message Bus service.\n *\n * @returns {boolean} Whether the WebSocket is connected to the Message Bus service\n *\n * @private\n */\n _isConnected() {\n return (\n this._webSocket && this._webSocket.readyState === this._webSocket.OPEN\n );\n }\n}\n\nexport default WebSocketConnection;\n"]}
package/lib/request.js CHANGED
@@ -16,6 +16,22 @@ function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr
16
16
 
17
17
  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
18
18
 
19
+ function loadSdkInfo() {
20
+ try {
21
+ var _require = require('../package.json'),
22
+ _sdkName = _require.name,
23
+ _sdkVersion = _require.version;
24
+
25
+ return { sdkName: _sdkName, sdkVersion: _sdkVersion };
26
+ } catch (e) {
27
+ return { sdkName: "@ndustrial/contxt-sdk", sdkVersion: "5.5.0+" };
28
+ }
29
+ }
30
+
31
+ var _loadSdkInfo = loadSdkInfo(),
32
+ sdkName = _loadSdkInfo.sdkName,
33
+ sdkVersion = _loadSdkInfo.sdkVersion;
34
+
19
35
  var Request = function () {
20
36
  /**
21
37
  * @param {Object} sdk An instance of the SDK so the module can communicate with other modules
@@ -233,6 +249,7 @@ var Request = function () {
233
249
  value: function _insertHeaders(config) {
234
250
  return this._sdk.auth.getCurrentApiToken(this._audienceName).then(function (apiToken) {
235
251
  config.headers.common.Authorization = 'Bearer ' + apiToken;
252
+ config.headers.common['User-Agent'] = process.env.npm_package_name + '/' + process.env.npm_package_version + ' (' + sdkName + '/' + sdkVersion + ')';
236
253
 
237
254
  return config;
238
255
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["request.js"],"names":["Request","sdk","audienceName","_audienceName","_axios","axios","create","_insertHeaders","bind","_sdk","_attachInterceptors","delete","then","data","get","head","options","patch","post","put","request","requestInterceptors","fulfilled","config","interceptors","responseInterceptors","response","forEach","rejected","use","auth","getCurrentApiToken","apiToken","headers","common","Authorization"],"mappings":";;;;;;;;AAAA;;;;;;;;;;IAEMA,O;AACJ;;;;;AAKA,mBAAYC,GAAZ,EAAiBC,YAAjB,EAA+B;AAAA;;AAC7B,SAAKC,aAAL,GAAqBD,YAArB;AACA,SAAKE,MAAL,GAAcC,iBAAMC,MAAN,EAAd;AACA,SAAKC,cAAL,GAAsB,KAAKA,cAAL,CAAoBC,IAApB,CAAyB,IAAzB,CAAtB;AACA,SAAKC,IAAL,GAAYR,GAAZ;;AAEA,SAAKS,mBAAL;AACD;;AAED;;;;;;;;;;;8BAOgB;AAAA;;AACd,aAAO,eAAKN,MAAL,EAAYO,MAAZ,0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YAAGC,IAAH,SAAGA,IAAH;AAAA,eAAcA,IAAd;AAAA,OAAlC,CAAP;AACD;;AAED;;;;;;;;;0CAMsB;AAAA;;AACpB,UAAMQ,uBACJ,EAAEC,WAAW,KAAKf,cAAlB,EADI,4BAED,KAAKE,IAAL,CAAUc,MAAV,CAAiBC,YAAjB,CAA8BJ,OAF7B,EAAN;AAIA,UAAMK,oDAA2B,KAAKhB,IAAL,CAAUc,MAAV,CAAiBC,YAAjB,CAA8BE,QAAzD,EAAN;;AAEAL,0BAAoBM,OAApB,CAA4B,iBAA6B;AAAA,YAA1BL,SAA0B,SAA1BA,SAA0B;AAAA,YAAfM,QAAe,SAAfA,QAAe;;AACvD,cAAKxB,MAAL,CAAYoB,YAAZ,CAAyBJ,OAAzB,CAAiCS,GAAjC,CAAqCP,SAArC,EAAgDM,QAAhD;AACD,OAFD;AAGAH,2BAAqBE,OAArB,CAA6B,kBAA6B;AAAA,YAA1BL,SAA0B,UAA1BA,SAA0B;AAAA,YAAfM,QAAe,UAAfA,QAAe;;AACxD,cAAKxB,MAAL,CAAYoB,YAAZ,CAAyBE,QAAzB,CAAkCG,GAAlC,CAAsCP,SAAtC,EAAiDM,QAAjD;AACD,OAFD;AAGD;;AAED;;;;;;;;;;;;;;;mCAYeL,M,EAAQ;AACrB,aAAO,KAAKd,IAAL,CAAUqB,IAAV,CACJC,kBADI,CACe,KAAK5B,aADpB,EAEJS,IAFI,CAEC,UAACoB,QAAD,EAAc;AAClBT,eAAOU,OAAP,CAAeC,MAAf,CAAsBC,aAAtB,eAAgDH,QAAhD;;AAEA,eAAOT,MAAP;AACD,OANI,CAAP;AAOD;;;;;;kBAGYvB,O","file":"request.js","sourcesContent":["import axios from 'axios';\n\nclass Request {\n /**\n * @param {Object} sdk An instance of the SDK so the module can communicate with other modules\n * @param {string} audienceName The audience name for this instance. Used when grabbing a\n * Bearer token\n */\n constructor(sdk, audienceName) {\n this._audienceName = audienceName;\n this._axios = axios.create();\n this._insertHeaders = this._insertHeaders.bind(this);\n this._sdk = sdk;\n\n this._attachInterceptors();\n }\n\n /**\n * Makes a DELETE request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n delete(...args) {\n return this._axios.delete(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a GET request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n get(...args) {\n return this._axios.get(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a HEAD request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n head(...args) {\n return this._axios.head(...args).then(({ data }) => data);\n }\n\n /**\n * Makes an OPTIONS request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n options(...args) {\n return this._axios.options(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a PATCH request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n patch(...args) {\n return this._axios.patch(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a POST request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n post(...args) {\n return this._axios.post(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a PUT request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n put(...args) {\n return this._axios.put(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n request(...args) {\n return this._axios.request(...args).then(({ data }) => data);\n }\n\n /**\n * Sets up axios interceptors for the request instance\n * More information at {@link https://github.com/axios/axios#interceptors axios Interceptors}\n *\n * @private\n */\n _attachInterceptors() {\n const requestInterceptors = [\n { fulfilled: this._insertHeaders },\n ...this._sdk.config.interceptors.request\n ];\n const responseInterceptors = [...this._sdk.config.interceptors.response];\n\n requestInterceptors.forEach(({ fulfilled, rejected }) => {\n this._axios.interceptors.request.use(fulfilled, rejected);\n });\n responseInterceptors.forEach(({ fulfilled, rejected }) => {\n this._axios.interceptors.response.use(fulfilled, rejected);\n });\n }\n\n /**\n * Decorates custom modules onto the SDK instance so they behave as first-class citizens.\n *\n * @param {Object} config\n * @param {Object} config.headers\n * @param {Object} config.headers.common\n *\n * @returns {Promise}\n * @fulfill {Object} axios.js config\n *\n * @private\n */\n _insertHeaders(config) {\n return this._sdk.auth\n .getCurrentApiToken(this._audienceName)\n .then((apiToken) => {\n config.headers.common.Authorization = `Bearer ${apiToken}`;\n\n return config;\n });\n }\n}\n\nexport default Request;\n"]}
1
+ {"version":3,"sources":["request.js"],"names":["loadSdkInfo","require","sdkName","name","sdkVersion","version","e","Request","sdk","audienceName","_audienceName","_axios","axios","create","_insertHeaders","bind","_sdk","_attachInterceptors","delete","then","data","get","head","options","patch","post","put","request","requestInterceptors","fulfilled","config","interceptors","responseInterceptors","response","forEach","rejected","use","auth","getCurrentApiToken","apiToken","headers","common","Authorization","process","env","npm_package_name","npm_package_version"],"mappings":";;;;;;;;AAAA;;;;;;;;;;AAEA,SAASA,WAAT,GAAuB;AACrB,MAAI;AAAA,mBAC6CC,QAAQ,iBAAR,CAD7C;AAAA,QACYC,QADZ,YACMC,IADN;AAAA,QAC8BC,WAD9B,YACqBC,OADrB;;AAEF,WAAO,EAAEH,iBAAF,EAAWE,uBAAX,EAAP;AACD,GAHD,CAGE,OAAOE,CAAP,EAAU;AACV,WAAO,EAAEJ,SAAS,uBAAX,EAAoCE,YAAY,QAAhD,EAAP;AACD;AACF;;mBAE+BJ,a;IAAxBE,O,gBAAAA,O;IAASE,U,gBAAAA,U;;IACXG,O;AACJ;;;;;AAKA,mBAAYC,GAAZ,EAAiBC,YAAjB,EAA+B;AAAA;;AAC7B,SAAKC,aAAL,GAAqBD,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AACAT,eAAOU,OAAP,CAAeC,MAAf,CAAsB,YAAtB,IAAyCE,QAAQC,GAAR,CAAYC,gBAArD,SAAyEF,QAAQC,GAAR,CAAYE,mBAArF,UAA6G5C,OAA7G,SAAwHE,UAAxH;;AAEA,eAAO0B,MAAP;AACD,OAPI,CAAP;AAQD;;;;;;kBAGYvB,O","file":"request.js","sourcesContent":["import axios from 'axios';\n\nfunction loadSdkInfo() {\n try {\n const { name: sdkName, version: sdkVersion } = require('../package.json');\n return { sdkName, sdkVersion };\n } catch (e) {\n return { sdkName: \"@ndustrial/contxt-sdk\", sdkVersion: \"5.5.0+\" };\n }\n}\n\nconst { sdkName, sdkVersion } = loadSdkInfo();\nclass Request {\n /**\n * @param {Object} sdk An instance of the SDK so the module can communicate with other modules\n * @param {string} audienceName The audience name for this instance. Used when grabbing a\n * Bearer token\n */\n constructor(sdk, audienceName) {\n this._audienceName = audienceName;\n this._axios = axios.create();\n this._insertHeaders = this._insertHeaders.bind(this);\n this._sdk = sdk;\n\n this._attachInterceptors();\n }\n\n /**\n * Makes a DELETE request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n delete(...args) {\n return this._axios.delete(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a GET request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n get(...args) {\n return this._axios.get(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a HEAD request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n head(...args) {\n return this._axios.head(...args).then(({ data }) => data);\n }\n\n /**\n * Makes an OPTIONS request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n options(...args) {\n return this._axios.options(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a PATCH request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n patch(...args) {\n return this._axios.patch(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a POST request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n post(...args) {\n return this._axios.post(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a PUT request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n put(...args) {\n return this._axios.put(...args).then(({ data }) => data);\n }\n\n /**\n * Makes a request\n * See more at {@link https://github.com/axios/axios axios}\n *\n * @returns {Promise}\n * @fulfill {string|number|object|array} data\n */\n request(...args) {\n return this._axios.request(...args).then(({ data }) => data);\n }\n\n /**\n * Sets up axios interceptors for the request instance\n * More information at {@link https://github.com/axios/axios#interceptors axios Interceptors}\n *\n * @private\n */\n _attachInterceptors() {\n const requestInterceptors = [\n { fulfilled: this._insertHeaders },\n ...this._sdk.config.interceptors.request\n ];\n const responseInterceptors = [...this._sdk.config.interceptors.response];\n\n requestInterceptors.forEach(({ fulfilled, rejected }) => {\n this._axios.interceptors.request.use(fulfilled, rejected);\n });\n responseInterceptors.forEach(({ fulfilled, rejected }) => {\n this._axios.interceptors.response.use(fulfilled, rejected);\n });\n }\n\n /**\n * Decorates custom modules onto the SDK instance so they behave as first-class citizens.\n *\n * @param {Object} config\n * @param {Object} config.headers\n * @param {Object} config.headers.common\n *\n * @returns {Promise}\n * @fulfill {Object} axios.js config\n *\n * @private\n */\n _insertHeaders(config) {\n return this._sdk.auth\n .getCurrentApiToken(this._audienceName)\n .then((apiToken) => {\n config.headers.common.Authorization = `Bearer ${apiToken}`;\n config.headers.common['User-Agent'] = `${process.env.npm_package_name}/${process.env.npm_package_version} (${sdkName}/${sdkVersion})`;\n\n return config;\n });\n }\n}\n\nexport default Request;\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ndustrial/contxt-sdk",
3
- "version": "5.4.0",
3
+ "version": "5.5.0",
4
4
  "description": "",
5
5
  "main": "lib/index.js",
6
6
  "module": "esm/index.js",
package/src/bus/index.js CHANGED
@@ -81,13 +81,19 @@ class Bus {
81
81
  * If a connection already exists for that organization id, the connection is returned, otherwise a new connection is created and returned.
82
82
  *
83
83
  * @param {string} organizationId UUID corresponding with an organization
84
+ * @param {function} onClose optional callback to be executed when the connection is closed
85
+ * @param {function} onError optional callback to be executed when the connection encounters an error
84
86
  *
85
87
  * @returns {Promise}
86
88
  * @fulfill {WebSocketConnection}
87
89
  * @reject {errorEvent} The error event
88
90
  *
89
91
  * @example
90
- * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d')
92
+ * contxtSdk.bus.connect('4f0e51c6-728b-4892-9863-6d002e61204d', (orgId, evt) => {
93
+ * console.log(`connection closed: ${evt}`);
94
+ * }, (orgId, evt) => {
95
+ * console.log(`connection error: ${evt}`);
96
+ * })
91
97
  * .then((webSocket) => {
92
98
  * console.log(webSocket);
93
99
  * })
@@ -95,7 +101,7 @@ class Bus {
95
101
  * console.log(errorEvent);
96
102
  * });
97
103
  */
98
- connect(organizationId) {
104
+ connect(organizationId, onClose, onError) {
99
105
  return new Promise((resolve, reject) => {
100
106
  if (this._webSockets[organizationId]) {
101
107
  return resolve(this._webSockets[organizationId]);
@@ -124,13 +130,31 @@ class Bus {
124
130
  resolve(this._webSockets[organizationId]);
125
131
  };
126
132
 
127
- ws.onclose = (event) => {
133
+ ws.addEventListener("close", (event) => {
128
134
  this._webSockets[organizationId] = null;
129
- };
135
+ if (onClose) {
136
+ try {
137
+ onClose(organizationId, event);
138
+ } catch (ex) {
139
+ console.log('Message Bus Error calling onClose callback: ', ex)
140
+ }
141
+ }
142
+ });
130
143
 
131
- ws.onerror = (errorEvent) => {
132
- reject(errorEvent);
133
- };
144
+ ws.addEventListener("error", (errorEvent) => {
145
+ const connected = this._webSockets[organizationId] != null;
146
+ this._webSockets[organizationId] = null;
147
+ if (!connected) {
148
+ reject(errorEvent)
149
+ }
150
+ if (onError) {
151
+ try {
152
+ onError(organizationId, errorEvent);
153
+ } catch (ex) {
154
+ console.log('Message Bus Error calling onError callback: ', ex)
155
+ }
156
+ }
157
+ });
134
158
  })
135
159
  .catch((err) => {
136
160
  reject(err);
@@ -144,6 +144,8 @@ describe('Bus', function() {
144
144
  let promise;
145
145
  let sdk;
146
146
  let server;
147
+ let testOnClose;
148
+ let testOnClose2;
147
149
 
148
150
  beforeEach(function() {
149
151
  expectedApiToken = faker.internet.password();
@@ -160,10 +162,16 @@ describe('Bus', function() {
160
162
  `${expectedHost}/organizations/${expectedOrganization.id}/stream`
161
163
  );
162
164
 
165
+ testOnClose = sinon.stub();
166
+ testOnClose2 = sinon.stub();
167
+
163
168
  bus = new Bus(sdk, baseRequest);
164
169
  bus._baseWebSocketUrl = expectedHost;
165
170
 
166
- promise = bus.connect(expectedOrganization.id);
171
+ promise = bus.connect(
172
+ expectedOrganization.id,
173
+ testOnClose
174
+ );
167
175
  });
168
176
 
169
177
  afterEach(function() {
@@ -191,10 +199,19 @@ describe('Bus', function() {
191
199
  context('when the connection closes', function() {
192
200
  beforeEach(function() {
193
201
  return promise.then(() => {
202
+ const ws = bus._webSockets[expectedOrganization.id];
203
+ ws._webSocket.addEventListener("close", testOnClose2);
194
204
  server.close();
195
205
  });
196
206
  });
197
207
 
208
+ it('calls the onClose callback', function() {
209
+ return promise.then(() => {
210
+ expect(testOnClose).to.have.been.calledOnce;
211
+ expect(testOnClose2).to.have.been.calledOnce;
212
+ });
213
+ });
214
+
198
215
  it('clears out the stored copy of the websocket', function() {
199
216
  return promise.then(() => {
200
217
  expect(bus._webSockets[expectedOrganization.id]).to.be.null;
@@ -237,6 +254,7 @@ describe('Bus', function() {
237
254
  let promise;
238
255
  let sdk;
239
256
  let server;
257
+ let testOnError;
240
258
 
241
259
  beforeEach(function() {
242
260
  expectedApiToken = faker.internet.password();
@@ -259,10 +277,16 @@ describe('Bus', function() {
259
277
  }
260
278
  );
261
279
 
280
+ testOnError = sinon.stub();
281
+
262
282
  const bus = new Bus(sdk, baseRequest);
263
283
  bus._baseWebSocketUrl = expectedHost;
264
284
 
265
- promise = bus.connect(expectedOrganization.id);
285
+ promise = bus.connect(
286
+ expectedOrganization.id,
287
+ null,
288
+ testOnError
289
+ );
266
290
  });
267
291
 
268
292
  afterEach(function() {
@@ -281,11 +305,13 @@ describe('Bus', function() {
281
305
  return expect(promise).to.be.rejected;
282
306
  });
283
307
 
284
- it('rejects with an error event', function() {
308
+ it('rejects with an error event AND onError is called', function() {
285
309
  return promise.catch((event) => {
286
310
  expect(event.type).to.equal('error');
311
+ expect(testOnError).to.have.been.calledOnce;
287
312
  });
288
313
  });
314
+
289
315
  }
290
316
  );
291
317
  }
@@ -38,7 +38,7 @@ class WebSocketConnection {
38
38
  this._autoAck = autoAcknowledge;
39
39
 
40
40
  if (this._webSocket) {
41
- this._webSocket.onerror = this._onError;
41
+ this._webSocket.addEventListener("error", this._onError);
42
42
  this._webSocket.onmessage = this._onMessage;
43
43
  }
44
44
  }
package/src/request.js CHANGED
@@ -1,5 +1,15 @@
1
1
  import axios from 'axios';
2
2
 
3
+ function loadSdkInfo() {
4
+ try {
5
+ const { name: sdkName, version: sdkVersion } = require('../package.json');
6
+ return { sdkName, sdkVersion };
7
+ } catch (e) {
8
+ return { sdkName: "@ndustrial/contxt-sdk", sdkVersion: "5.5.0+" };
9
+ }
10
+ }
11
+
12
+ const { sdkName, sdkVersion } = loadSdkInfo();
3
13
  class Request {
4
14
  /**
5
15
  * @param {Object} sdk An instance of the SDK so the module can communicate with other modules
@@ -141,6 +151,7 @@ class Request {
141
151
  .getCurrentApiToken(this._audienceName)
142
152
  .then((apiToken) => {
143
153
  config.headers.common.Authorization = `Bearer ${apiToken}`;
154
+ config.headers.common['User-Agent'] = `${process.env.npm_package_name}/${process.env.npm_package_version} (${sdkName}/${sdkVersion})`;
144
155
 
145
156
  return config;
146
157
  });