@ndustrial/contxt-sdk 5.2.6 → 5.3.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/esm/bus/index.js +18 -2
- package/esm/bus/index.js.map +1 -1
- package/esm/bus/webSocketConnection.js +18 -10
- package/esm/bus/webSocketConnection.js.map +1 -1
- package/esm/config/defaults.js +3 -0
- package/esm/config/defaults.js.map +1 -1
- package/esm/config/index.js +2 -0
- package/esm/config/index.js.map +1 -1
- package/esm/index.js +1 -1
- package/esm/index.js.map +1 -1
- package/lib/bus/index.js +19 -2
- package/lib/bus/index.js.map +1 -1
- package/lib/bus/webSocketConnection.js +18 -10
- package/lib/bus/webSocketConnection.js.map +1 -1
- package/lib/config/defaults.js +3 -0
- package/lib/config/defaults.js.map +1 -1
- package/lib/config/index.js +2 -0
- package/lib/config/index.js.map +1 -1
- package/lib/index.js +1 -1
- package/lib/index.js.map +1 -1
- package/package.json +1 -1
- package/src/bus/index.js +19 -2
- package/src/bus/index.spec.js +42 -0
- package/src/bus/webSocketConnection.js +20 -14
- package/src/bus/webSocketConnection.spec.js +45 -0
- package/src/config/defaults.js +3 -0
- package/src/config/index.js +5 -0
- package/src/index.js +1 -1
- package/src/index.spec.js +9 -0
package/esm/bus/index.js
CHANGED
|
@@ -39,6 +39,20 @@ import WebSocketConnection from './webSocketConnection';
|
|
|
39
39
|
* @property {WebSocket} _webSocket The raw WebSocket connection to the message bus
|
|
40
40
|
*/
|
|
41
41
|
|
|
42
|
+
/**
|
|
43
|
+
* Configuration object for the Bus
|
|
44
|
+
*
|
|
45
|
+
* @typedef {Object} BusConfig
|
|
46
|
+
* @property {boolean} autoAcknowledge
|
|
47
|
+
*/
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* @type {BusConfig}
|
|
51
|
+
*/
|
|
52
|
+
var defaultBusConfig = {
|
|
53
|
+
autoAcknowledge: true
|
|
54
|
+
};
|
|
55
|
+
|
|
42
56
|
/**
|
|
43
57
|
* Module that provides access to the message bus. This is for Node
|
|
44
58
|
* environments. Documentation for browser environments is found under
|
|
@@ -51,8 +65,9 @@ var Bus = function () {
|
|
|
51
65
|
/**
|
|
52
66
|
* @param {Object} sdk An instance of the SDK so the module can communicate with other modules
|
|
53
67
|
* @param {Object} request An instance of the request module tied to this module's audience.
|
|
68
|
+
* @param {BusConfig} config A config object for the Bus instance
|
|
54
69
|
*/
|
|
55
|
-
function Bus(sdk, request) {
|
|
70
|
+
function Bus(sdk, request, config) {
|
|
56
71
|
_classCallCheck(this, Bus);
|
|
57
72
|
|
|
58
73
|
var baseUrl = '' + sdk.config.audiences.bus.host;
|
|
@@ -63,6 +78,7 @@ var Bus = function () {
|
|
|
63
78
|
this._request = request;
|
|
64
79
|
this._sdk = sdk;
|
|
65
80
|
this._webSockets = {};
|
|
81
|
+
this._config = Object.assign({}, defaultBusConfig, config);
|
|
66
82
|
|
|
67
83
|
this.channels = new Channels(sdk, request, baseUrl);
|
|
68
84
|
}
|
|
@@ -106,7 +122,7 @@ var Bus = function () {
|
|
|
106
122
|
});
|
|
107
123
|
|
|
108
124
|
ws.onopen = function (event) {
|
|
109
|
-
_this._webSockets[organizationId] = new WebSocketConnection(ws, organizationId);
|
|
125
|
+
_this._webSockets[organizationId] = new WebSocketConnection(ws, organizationId, _this._config.autoAcknowledge);
|
|
110
126
|
|
|
111
127
|
resolve(_this._webSockets[organizationId]);
|
|
112
128
|
};
|
package/esm/bus/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["bus/index.js"],"names":["WebSocket","Channels","WebSocketConnection","Bus","sdk","request","
|
|
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;;;;;;;;;;;;;;;;;;;;;;;AAuBA;;;;;;;;;AASA;;;;;;;AAOA;;;AAGA,IAAMC,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,IAAItB,QAAJ,CAAaK,GAAb,EAAkBC,OAAlB,EAA2BE,OAA3B,CAAhB;AACD;;AAED;;;;;;;;;;;;;;;;;;;;;;;4BAmBQe,c,EAAgB;AAAA;;AACtB,aAAO,IAAIC,OAAJ,CAAY,UAACC,OAAD,EAAUC,MAAV,EAAqB;AACtC,YAAI,MAAKR,WAAL,CAAiBK,cAAjB,CAAJ,EAAsC;AACpC,iBAAOE,QAAQ,MAAKP,WAAL,CAAiBK,cAAjB,CAAR,CAAP;AACD;;AAED,eAAO,MAAKN,IAAL,CAAUU,IAAV,CACJC,kBADI,CACe,YADf,EAEJC,IAFI,CAEC,UAACC,QAAD,EAAc;AAClB,cAAMC,KAAK,IAAIhC,SAAJ,CACN,MAAKe,iBADC,uBACkCS,cADlC,cAET,EAFS,EAGT;AACES,qBAAS;AACPC,yCAAyBH;AADlB;AADX,WAHS,CAAX;;AAUAC,aAAGG,MAAH,GAAY,UAACC,KAAD,EAAW;AACrB,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"]}
|
|
@@ -34,10 +34,13 @@ var WebSocketConnection = function () {
|
|
|
34
34
|
/**
|
|
35
35
|
* @param {WebSocket} webSocket A WebSocket connection to the message bus
|
|
36
36
|
* @param {string} organizationId UUID corresponding with an organization
|
|
37
|
+
* @param {boolean} autoAcknowledge Whether the messages should be ACK'd explicitly or not
|
|
37
38
|
*/
|
|
38
39
|
function WebSocketConnection(webSocket, organizationId) {
|
|
39
40
|
var _this = this;
|
|
40
41
|
|
|
42
|
+
var autoAcknowledge = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
|
|
43
|
+
|
|
41
44
|
_classCallCheck(this, WebSocketConnection);
|
|
42
45
|
|
|
43
46
|
this._onError = function (error) {
|
|
@@ -63,6 +66,7 @@ var WebSocketConnection = function () {
|
|
|
63
66
|
this._messageHandlers = {};
|
|
64
67
|
this._organizationId = organizationId;
|
|
65
68
|
this._webSocket = webSocket;
|
|
69
|
+
this._autoAck = autoAcknowledge;
|
|
66
70
|
|
|
67
71
|
if (this._webSocket) {
|
|
68
72
|
this._webSocket.onerror = this._onError;
|
|
@@ -301,20 +305,24 @@ var WebSocketConnection = function () {
|
|
|
301
305
|
|
|
302
306
|
if (error) {
|
|
303
307
|
return resolve(errorHandler(error));
|
|
304
|
-
}
|
|
305
|
-
try {
|
|
306
|
-
var ack = once(function () {
|
|
307
|
-
return _this2._acknowledge(result.id);
|
|
308
|
-
});
|
|
308
|
+
}
|
|
309
309
|
|
|
310
|
-
|
|
310
|
+
try {
|
|
311
|
+
var ack = once(function () {
|
|
312
|
+
return _this2._acknowledge(result.id);
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
return resolve(Promise.resolve(handler(result.body, ack)).then(function (res) {
|
|
316
|
+
if (_this2._autoAck) {
|
|
311
317
|
return ack().then(function () {
|
|
312
318
|
return res;
|
|
313
319
|
});
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
return
|
|
317
|
-
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
return res;
|
|
323
|
+
}));
|
|
324
|
+
} catch (throwable) {
|
|
325
|
+
return reject(throwable);
|
|
318
326
|
}
|
|
319
327
|
});
|
|
320
328
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["bus/webSocketConnection.js"],"names":["v4","uuid","once","WebSocketConnection","webSocket","organizationId","_onError","error","_messageHandlers","console","log","_onMessage","message","messageData","JSON","parse","data","err","Error","id","_organizationId","_webSocket","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;;;;AAIA,+BAAYC,SAAZ,EAAuBC,cAAvB,EAAuC;AAAA;;AAAA;;AAAA,SAqEvCC,QArEuC,GAqE5B,UAACC,KAAD,EAAW;AACpB,YAAKC,gBAAL,GAAwB,EAAxB;;AAEAC,cAAQC,GAAR,CAAY,+BAAZ,EAA6CH,KAA7C;AACD,KAzEsC;;AAAA,SAkFvCI,UAlFuC,GAkF1B,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,KA9FsC;;AACrC,SAAKL,gBAAL,GAAwB,EAAxB;AACA,SAAKY,eAAL,GAAuBf,cAAvB;AACA,SAAKgB,UAAL,GAAkBjB,SAAlB;;AAEA,QAAI,KAAKiB,UAAT,EAAqB;AACnB,WAAKA,UAAL,CAAgBC,OAAhB,GAA0B,KAAKhB,QAA/B;AACA,WAAKe,UAAL,CAAgBE,SAAhB,GAA4B,KAAKZ,UAAjC;AACD;AACF;;AAED;;;;;;;;;;;;;;;;;;;;;;;;;8BAqBUa,K,EAAO;AACf,UAAI,CAACA,KAAL,EAAY;AACV,eAAOC,QAAQC,MAAR,CAAe,IAAIR,KAAJ,CA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AED;;;;;;;;;;mCAOe;AACb,aACE,KAAK7B,UAAL,IAAmB,KAAKA,UAAL,CAAgBiC,UAAhB,KAA+B,KAAKjC,UAAL,CAAgBkC,IADpE;AAGD;;;;;;AAGH,eAAepD,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 */\n constructor(webSocket, organizationId) {\n this._messageHandlers = {};\n this._organizationId = organizationId;\n this._webSocket = webSocket;\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 } else {\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 return ack().then(() => res);\n })\n );\n } catch (throwable) {\n return reject(throwable);\n }\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","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,UAnF+D,GAmFlD,UAACC,OAAD,EAAa;AACxB,UAAIC,oBAAJ;;AAEA,UAAI;AACFA,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e,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"]}
|
package/esm/config/defaults.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["config/defaults.js"],"names":["auth","domain","authorizationPath","tokenExpiresAtBufferMs","interceptors","request","response"],"mappings":"AAAA,eAAe;AACbA,QAAM;AACJC,YAAQ,qBADJ;AAEJC,uBAAmB,WAFf;AAGJC,4BAAwB,IAAI,EAAJ,GAAS,IAH7B,CAGkC;AAHlC,GADO;AAMbC,gBAAc;AACZC,aAAS,EADG;AAEZC,cAAU;AAFE;
|
|
1
|
+
{"version":3,"sources":["config/defaults.js"],"names":["auth","domain","authorizationPath","tokenExpiresAtBufferMs","interceptors","request","response","bus","autoAcknowledge"],"mappings":"AAAA,eAAe;AACbA,QAAM;AACJC,YAAQ,qBADJ;AAEJC,uBAAmB,WAFf;AAGJC,4BAAwB,IAAI,EAAJ,GAAS,IAH7B,CAGkC;AAHlC,GADO;AAMbC,gBAAc;AACZC,aAAS,EADG;AAEZC,cAAU;AAFE,GAND;AAUbC,OAAK;AACHC,qBAAiB;AADd;AAVQ,CAAf","file":"defaults.js","sourcesContent":["export default {\n auth: {\n domain: 'ndustrial.auth0.com',\n authorizationPath: '/callback',\n tokenExpiresAtBufferMs: 5 * 60 * 1000 // 5 minutes\n },\n interceptors: {\n request: [],\n response: []\n },\n bus: {\n autoAcknowledge: true\n }\n};\n"]}
|
package/esm/config/index.js
CHANGED
|
@@ -121,6 +121,8 @@ var Config = function () {
|
|
|
121
121
|
this.auth = _extends({}, defaultConfigs.auth, userConfig.auth);
|
|
122
122
|
|
|
123
123
|
this.interceptors = _extends({}, defaultConfigs.interceptors, userConfig.interceptors);
|
|
124
|
+
|
|
125
|
+
this.bus = _extends({}, defaultConfigs.bus, userConfig.bus);
|
|
124
126
|
}
|
|
125
127
|
|
|
126
128
|
_createClass(Config, [{
|
package/esm/config/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["config/index.js"],"names":["defaultAudiences","defaultConfigs","Config","userConfig","externalModules","Object","assign","_dynamicAudienceNames","_replacedAudiences","audiences","_getAudiences","customModuleConfigs","auth","env","interceptors","audienceName","clientId","host","Error","indexOf","filter","name","config","audience","webSocket","options","_getInternalAudiences","_getExternalAudiences","keys","reduce","memo","key","hasClientId","hasHost","customModuleConfig","moduleAudiences","_getAudienceFromCustomConfig"],"mappings":";;;;;;;;AAAA,OAAOA,gBAAP,MAA6B,aAA7B;AACA,OAAOC,cAAP,MAA2B,YAA3B;;AAEA;;;;;;;;;;AAUA;;;;;;;;;;;;;AAaA;;;;;;;AAOA;;;;;;;;;;;;;;AAcA;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA;;;;;;IAKMC,M;AACJ;;;;;AAKA,kBAAYC,UAAZ,EAAwBC,eAAxB,EAAyC;AAAA;;AACvCC,WAAOC,MAAP,CAAc,IAAd,EAAoBH,UAApB;;AAEA,SAAKI,qBAAL,GAA6B,EAA7B;AACA,SAAKC,kBAAL,GAA0B,EAA1B;;AAEA,SAAKC,SAAL,GAAiB,KAAKC,aAAL,CAAmB;AAClCN,sCADkC;AAElCO,2BAAqBR,WAAWS,IAAX,CAAgBD,mBAFH;AAGlCE,WAAKV,WAAWS,IAAX,CAAgBC;AAHa,KAAnB,CAAjB;;AAMA,SAAKD,IAAL,gBACKX,eAAeW,IADpB,EAEKT,WAAWS,IAFhB;;AAKA,SAAKE,YAAL,gBACKb,eAAea,YADpB,EAEKX,WAAWW,YAFhB;AAID;;;;uCAEkBC,Y,QAAkC;AAAA,UAAlBC,QAAkB,QAAlBA,QAAkB;AAAA,UAARC,IAAQ,QAARA,IAAQ;;AACnD,UAAI,CAACD,QAAD,IAAa,CAACC,IAAlB,EAAwB;AACtB,cAAM,IAAIC,KAAJ,CACJ,kEADI,CAAN;AAGD;;AAED,UAAI,KAAKX,qBAAL,CAA2BY,OAA3B,CAAmCJ,YAAnC,IAAmD,CAAC,CAAxD,EAA2D;AACzD,cAAM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,EAAuBoB,MAAvB,CAA8B,UAACC,IAAD,EAAOC,GAAP,EAAe;AAClD,YAAMG,qBAAqBvB,oBAAoBoB,GAApB,CAA3B;AACA,YAAMI,kBAAkB1B,UAAUsB,GAAV,CAAxB;;AAEA,YAAIG,kBAAJ,EAAwB;AACtBJ,eAAKC,GAAL,IAAY,MAAKK,4BAAL,CACVF,kBADU,EAEVC,eAFU,CAAZ;AAID,SALD,MAKO;AACLL,eAAKC,GAAL,IAAYI,gBAAgBtB,GAAhB,CAAZ;AACD;;AAED,eAAOiB,IAAP;AACD,OAdM,EAcJ,EAdI,CAAP;AAeD;;;;;;AAGH,eAAe5B,MAAf","file":"index.js","sourcesContent":["import defaultAudiences from './audiences';\nimport defaultConfigs from './defaults';\n\n/**\n * A single audience used for authenticating and communicating with an individual API.\n *\n * @typedef {Object} Audience\n * @param {string} config.clientId Client Id provided by Auth0 for the environment you are\n * trying to communicate with\n * @param {string} config.host Hostname for the API that corresponds with the clientId provided\n * @param {string} [config.webSocket] WebSocket URL for the API that corresponds with the clientId provided\n */\n\n/**\n * A custom audience that will override the configuration of an individual module. Consists of\n * either a reference to an environment that already exists or a clientId and host for a\n * custom environment.\n *\n * @typedef {Object} CustomAudience\n * @param {string} [config.clientId] Client Id provided by Auth0 for the environment you are\n * trying to communicate with\n * @param {string} [config.env] The SDK provided environment name you are trying to reach\n * @param {string} [config.host] Hostname for the API that corresponds with the clientId provided\n * @param {string} [config.webSocket] WebSocket URL for the API that corresponds with the clientId provided\n */\n\n/**\n * An object of audiences that corresponds to all the different environments available for a\n * single module.\n *\n * @typedef {Object.<string, Audience>} Environments\n */\n\n/**\n * An external module to be integrated into the SDK as a first class citizen. Includes information\n * for authenticating and communicating with an individual API and the external module itself.\n *\n * @typedef {Object} ExternalModule\n * @param {string} config.clientId Client Id provided by Auth0 for the environment you are\n * trying to communicate with. Can be a `null` value if the value is not needed. Some SessionType\n * adapters (currently, just the MachineAuth adapter) require a value other than `null` if the\n * built-in `request` module is used since they acquire contxt tokens based on a single clientId.\n * @param {string} config.host Hostname for the API that corresponds with the clientId provided.\n * Can be a `null` value if the value is not needed.\n * @param {function} config.module The module that will be decorated into the SDK\n */\n\n/**\n * An object of interceptors that get called on every request or response.\n * More information at {@link https://github.com/axios/axios#interceptors axios Interceptors}\n *\n * @typedef {Object} AxiosInterceptor\n * @param {function} interceptor.fulfilled A function that is run on every successful request or\n * response\n * @param {function} interceptor.rejected A function that is run on every failed request or response\n */\n\n/**\n * User provided configuration options\n *\n * @typedef {Object} UserConfig\n * @property {Object} auth User assigned configurations specific for their authentication methods\n * @property {string} [auth.authorizationPath] Path Auth0WebAuth process should redirect to after a\n * successful sign in attempt\n * @property {string} auth.clientId Client Id provided by Auth0 for this application\n * @property {string} [auth.clientSecret] Client secret provided by Auth0 for this application. This\n * is optional for the auth0WebAuth SessionType, but required for the machineAuth SessionType\n * @property {string} [auth.domain] Auth0 domain for this application. This is an optional configuration\n * that defaults to the production Auth0 tenant\n * @property {Object.<string, CustomAudience>} [auth.customModuleConfigs] Custom environment setups\n * for individual modules. Requires clientId/host or env\n * @property {string} [auth.env = 'production'] The environment that every module should use for\n * their clientId and host\n * @property {function} [auth.onAuthenticate = (auth0WebAuthSessionInfo) => handleSuccessfulAuth(auth0WebAuthSessionInfo); ] An optional\n * hook for handling a successful authentication request or overriding returned values.\n * @property {function} [auth.onRedirect = (pathname) => { window.location = pathname; }] A redirect\n * method used for navigating through Auth0 callbacks in Web applications\n * @property {number} [auth.tokenExpiresAtBufferMs = 300000] The time (in milliseconds) before a\n * token truly expires that we consider it expired (i.e. the token's expiresAt - this = calculated\n * expiresAt). Defaults to 5 minutes.\n * @property {Object} [interceptors] Axios interceptors that can transform requests and responses.\n * More information at {@link https://github.com/axios/axios#interceptors axios Interceptors}\n * @property {AxiosInterceptor[]} [interceptors.request] Interceptors that act on every request\n * @property {AxiosInterceptor[]} [intercepotrs.response] Intereptors that act on every response\n */\n\n/**\n * Module that merges user assigned configurations with default configurations.\n *\n * @typicalname contxtSdk.config\n */\nclass Config {\n /**\n * @param {UserConfig} userConfig The user provided configuration options\n * @param {Object.<string, ExternalModule>} [externalModules] User provided external modules that should be treated as\n * first class citizens\n */\n constructor(userConfig, externalModules) {\n Object.assign(this, userConfig);\n\n this._dynamicAudienceNames = [];\n this._replacedAudiences = {};\n\n this.audiences = this._getAudiences({\n externalModules,\n customModuleConfigs: userConfig.auth.customModuleConfigs,\n env: userConfig.auth.env\n });\n\n this.auth = {\n ...defaultConfigs.auth,\n ...userConfig.auth\n };\n\n this.interceptors = {\n ...defaultConfigs.interceptors,\n ...userConfig.interceptors\n };\n }\n\n addDynamicAudience(audienceName, { clientId, host }) {\n if (!clientId || !host) {\n throw new Error(\n 'A dynamic audience must contain `clientId` and `host` properties'\n );\n }\n\n if (this._dynamicAudienceNames.indexOf(audienceName) > -1) {\n throw new Error(\n `A dynamic audience of the name \\`${audienceName}\\` already exists. This problem can be rectified by using a different name for the audience.`\n );\n }\n\n this._dynamicAudienceNames = [...this._dynamicAudienceNames, audienceName];\n\n if (this.audiences[audienceName]) {\n this._replacedAudiences[audienceName] = this.audiences[audienceName];\n }\n\n this.audiences[audienceName] = {\n clientId,\n host\n };\n }\n\n removeDynamicAudience(audienceName) {\n if (this._dynamicAudienceNames.indexOf(audienceName) === -1) {\n throw new Error('There is no dynamic audience to remove.');\n }\n\n this.audiences[audienceName] = this._replacedAudiences[audienceName];\n\n delete this._replacedAudiences[audienceName];\n this._dynamicAudienceNames = this._dynamicAudienceNames.filter(\n (name) => name !== audienceName\n );\n }\n\n /**\n * Parses a custom module configuration for a valid environment/audience. Requires either a\n * clientId and host, or an environment that matches a default audience/environment.\n *\n * @param {CustomAudience} config A custom audience configuration to parse\n * @param {Object.<string, Audience>} audiences An object with keys for environment names and values of Audience information\n *\n * @returns {Audience}\n * @throws {Error}\n *\n * @private\n */\n _getAudienceFromCustomConfig(config, audiences) {\n if (config.clientId && config.host) {\n const audience = {\n clientId: config.clientId,\n host: config.host\n };\n\n if (config.webSocket) {\n audience.webSocket = config.webSocket;\n }\n\n return audience;\n } else if (config.env) {\n return audiences[config.env];\n } else {\n throw new Error(\n 'Custom module configurations must either contain a `host` and `clientId` or specify a specific target environment via the `env` property'\n );\n }\n }\n\n /**\n * Reconciles the main environment with custom environments and external modules.\n *\n * @param {Object} options\n * @param {Object.<string, CustomAudience>} [options.customModuleConfigs = {}] Any custom\n * configurations for internal modules\n * @param {string} [options.env = 'production'] The base environment for any\n * non-overridden modules\n * @param {Object.<string, ExternalModule>} [options.externalModules = {}] An object of external\n * modules from which to build a set of audiences\n *\n * @returns {Object.<string, Audience>}\n *\n * @private\n */\n _getAudiences(options = {}) {\n const {\n customModuleConfigs = {},\n env = 'production',\n externalModules = {}\n } = options;\n\n return {\n ...this._getInternalAudiences({\n customModuleConfigs,\n env,\n audiences: defaultAudiences\n }),\n ...this._getExternalAudiences({ externalModules })\n };\n }\n\n /**\n * Builds up the audiences for external modules.\n *\n * @param {Object}\n * @param {Object.<string, ExternalModule>} externalModules An object of external modules from\n * which to build a set of audiences\n *\n * @returns {Object.<string, Audience>}\n * @throws {Error}\n *\n * @private\n */\n _getExternalAudiences({ externalModules }) {\n return Object.keys(externalModules).reduce((memo, key) => {\n const clientId = externalModules[key].clientId;\n const host = externalModules[key].host;\n const hasClientId = !!clientId || clientId === null;\n const hasHost = !!host || host === null;\n\n if (!(hasClientId && hasHost)) {\n throw new Error(\n 'External modules must contain `clientId` and `host` properties'\n );\n }\n\n memo[key] = {\n clientId,\n host\n };\n\n return memo;\n }, {});\n }\n\n /**\n * Reconciles the main environment with custom environments to build up audiences for\n * internal modules.\n *\n * @param {Object.<string, Environments>} audiences All possible audiences/environments for\n * internal modules\n * @param {Object.<string, CustomAudience>} customModuleConfigs Any custom configurations for\n * internal modules\n * @param {string} env The base environment for any non-overridden modules\n *\n * @returns {Object.<string, Audience>}\n *\n * @private\n */\n _getInternalAudiences({ audiences, customModuleConfigs, env }) {\n return Object.keys(audiences).reduce((memo, key) => {\n const customModuleConfig = customModuleConfigs[key];\n const moduleAudiences = audiences[key];\n\n if (customModuleConfig) {\n memo[key] = this._getAudienceFromCustomConfig(\n customModuleConfig,\n moduleAudiences\n );\n } else {\n memo[key] = moduleAudiences[env];\n }\n\n return memo;\n }, {});\n }\n}\n\nexport default Config;\n"]}
|
|
1
|
+
{"version":3,"sources":["config/index.js"],"names":["defaultAudiences","defaultConfigs","Config","userConfig","externalModules","Object","assign","_dynamicAudienceNames","_replacedAudiences","audiences","_getAudiences","customModuleConfigs","auth","env","interceptors","bus","audienceName","clientId","host","Error","indexOf","filter","name","config","audience","webSocket","options","_getInternalAudiences","_getExternalAudiences","keys","reduce","memo","key","hasClientId","hasHost","customModuleConfig","moduleAudiences","_getAudienceFromCustomConfig"],"mappings":";;;;;;;;AAAA,OAAOA,gBAAP,MAA6B,aAA7B;AACA,OAAOC,cAAP,MAA2B,YAA3B;;AAEA;;;;;;;;;;AAUA;;;;;;;;;;;;;AAaA;;;;;;;AAOA;;;;;;;;;;;;;;AAcA;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA;;;;;;IAKMC,M;AACJ;;;;;AAKA,kBAAYC,UAAZ,EAAwBC,eAAxB,EAAyC;AAAA;;AACvCC,WAAOC,MAAP,CAAc,IAAd,EAAoBH,UAApB;;AAEA,SAAKI,qBAAL,GAA6B,EAA7B;AACA,SAAKC,kBAAL,GAA0B,EAA1B;;AAEA,SAAKC,SAAL,GAAiB,KAAKC,aAAL,CAAmB;AAClCN,sCADkC;AAElCO,2BAAqBR,WAAWS,IAAX,CAAgBD,mBAFH;AAGlCE,WAAKV,WAAWS,IAAX,CAAgBC;AAHa,KAAnB,CAAjB;;AAMA,SAAKD,IAAL,gBACKX,eAAeW,IADpB,EAEKT,WAAWS,IAFhB;;AAKA,SAAKE,YAAL,gBACKb,eAAea,YADpB,EAEKX,WAAWW,YAFhB;;AAKA,SAAKC,GAAL,gBACKd,eAAec,GADpB,EAEKZ,WAAW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,aAAKC,GAAL,IAAY;AACVf,4BADU;AAEVC;AAFU,SAAZ;;AAKA,eAAOa,IAAP;AACD,OAlBM,EAkBJ,EAlBI,CAAP;AAmBD;;AAED;;;;;;;;;;;;;;;;;iDAc+D;AAAA;;AAAA,UAAvCtB,SAAuC,SAAvCA,SAAuC;AAAA,UAA5BE,mBAA4B,SAA5BA,mBAA4B;AAAA,UAAPE,GAAO,SAAPA,GAAO;;AAC7D,aAAOR,OAAOwB,IAAP,CAAYpB,SAAZ,EAAuBqB,MAAvB,CAA8B,UAACC,IAAD,EAAOC,GAAP,EAAe;AAClD,YAAMG,qBAAqBxB,oBAAoBqB,GAApB,CAA3B;AACA,YAAMI,kBAAkB3B,UAAUuB,GAAV,CAAxB;;AAEA,YAAIG,kBAAJ,EAAwB;AACtBJ,eAAKC,GAAL,IAAY,MAAKK,4BAAL,CACVF,kBADU,EAEVC,eAFU,CAAZ;AAID,SALD,MAKO;AACLL,eAAKC,GAAL,IAAYI,gBAAgBvB,GAAhB,CAAZ;AACD;;AAED,eAAOkB,IAAP;AACD,OAdM,EAcJ,EAdI,CAAP;AAeD;;;;;;AAGH,eAAe7B,MAAf","file":"index.js","sourcesContent":["import defaultAudiences from './audiences';\nimport defaultConfigs from './defaults';\n\n/**\n * A single audience used for authenticating and communicating with an individual API.\n *\n * @typedef {Object} Audience\n * @param {string} config.clientId Client Id provided by Auth0 for the environment you are\n * trying to communicate with\n * @param {string} config.host Hostname for the API that corresponds with the clientId provided\n * @param {string} [config.webSocket] WebSocket URL for the API that corresponds with the clientId provided\n */\n\n/**\n * A custom audience that will override the configuration of an individual module. Consists of\n * either a reference to an environment that already exists or a clientId and host for a\n * custom environment.\n *\n * @typedef {Object} CustomAudience\n * @param {string} [config.clientId] Client Id provided by Auth0 for the environment you are\n * trying to communicate with\n * @param {string} [config.env] The SDK provided environment name you are trying to reach\n * @param {string} [config.host] Hostname for the API that corresponds with the clientId provided\n * @param {string} [config.webSocket] WebSocket URL for the API that corresponds with the clientId provided\n */\n\n/**\n * An object of audiences that corresponds to all the different environments available for a\n * single module.\n *\n * @typedef {Object.<string, Audience>} Environments\n */\n\n/**\n * An external module to be integrated into the SDK as a first class citizen. Includes information\n * for authenticating and communicating with an individual API and the external module itself.\n *\n * @typedef {Object} ExternalModule\n * @param {string} config.clientId Client Id provided by Auth0 for the environment you are\n * trying to communicate with. Can be a `null` value if the value is not needed. Some SessionType\n * adapters (currently, just the MachineAuth adapter) require a value other than `null` if the\n * built-in `request` module is used since they acquire contxt tokens based on a single clientId.\n * @param {string} config.host Hostname for the API that corresponds with the clientId provided.\n * Can be a `null` value if the value is not needed.\n * @param {function} config.module The module that will be decorated into the SDK\n */\n\n/**\n * An object of interceptors that get called on every request or response.\n * More information at {@link https://github.com/axios/axios#interceptors axios Interceptors}\n *\n * @typedef {Object} AxiosInterceptor\n * @param {function} interceptor.fulfilled A function that is run on every successful request or\n * response\n * @param {function} interceptor.rejected A function that is run on every failed request or response\n */\n\n/**\n * User provided configuration options\n *\n * @typedef {Object} UserConfig\n * @property {Object} auth User assigned configurations specific for their authentication methods\n * @property {string} [auth.authorizationPath] Path Auth0WebAuth process should redirect to after a\n * successful sign in attempt\n * @property {string} auth.clientId Client Id provided by Auth0 for this application\n * @property {string} [auth.clientSecret] Client secret provided by Auth0 for this application. This\n * is optional for the auth0WebAuth SessionType, but required for the machineAuth SessionType\n * @property {string} [auth.domain] Auth0 domain for this application. This is an optional configuration\n * that defaults to the production Auth0 tenant\n * @property {Object.<string, CustomAudience>} [auth.customModuleConfigs] Custom environment setups\n * for individual modules. Requires clientId/host or env\n * @property {string} [auth.env = 'production'] The environment that every module should use for\n * their clientId and host\n * @property {function} [auth.onAuthenticate = (auth0WebAuthSessionInfo) => handleSuccessfulAuth(auth0WebAuthSessionInfo); ] An optional\n * hook for handling a successful authentication request or overriding returned values.\n * @property {function} [auth.onRedirect = (pathname) => { window.location = pathname; }] A redirect\n * method used for navigating through Auth0 callbacks in Web applications\n * @property {number} [auth.tokenExpiresAtBufferMs = 300000] The time (in milliseconds) before a\n * token truly expires that we consider it expired (i.e. the token's expiresAt - this = calculated\n * expiresAt). Defaults to 5 minutes.\n * @property {Object} [interceptors] Axios interceptors that can transform requests and responses.\n * More information at {@link https://github.com/axios/axios#interceptors axios Interceptors}\n * @property {AxiosInterceptor[]} [interceptors.request] Interceptors that act on every request\n * @property {AxiosInterceptor[]} [intercepotrs.response] Intereptors that act on every response\n */\n\n/**\n * Module that merges user assigned configurations with default configurations.\n *\n * @typicalname contxtSdk.config\n */\nclass Config {\n /**\n * @param {UserConfig} userConfig The user provided configuration options\n * @param {Object.<string, ExternalModule>} [externalModules] User provided external modules that should be treated as\n * first class citizens\n */\n constructor(userConfig, externalModules) {\n Object.assign(this, userConfig);\n\n this._dynamicAudienceNames = [];\n this._replacedAudiences = {};\n\n this.audiences = this._getAudiences({\n externalModules,\n customModuleConfigs: userConfig.auth.customModuleConfigs,\n env: userConfig.auth.env\n });\n\n this.auth = {\n ...defaultConfigs.auth,\n ...userConfig.auth\n };\n\n this.interceptors = {\n ...defaultConfigs.interceptors,\n ...userConfig.interceptors\n };\n\n this.bus = {\n ...defaultConfigs.bus,\n ...userConfig.bus\n };\n }\n\n addDynamicAudience(audienceName, { clientId, host }) {\n if (!clientId || !host) {\n throw new Error(\n 'A dynamic audience must contain `clientId` and `host` properties'\n );\n }\n\n if (this._dynamicAudienceNames.indexOf(audienceName) > -1) {\n throw new Error(\n `A dynamic audience of the name \\`${audienceName}\\` already exists. This problem can be rectified by using a different name for the audience.`\n );\n }\n\n this._dynamicAudienceNames = [...this._dynamicAudienceNames, audienceName];\n\n if (this.audiences[audienceName]) {\n this._replacedAudiences[audienceName] = this.audiences[audienceName];\n }\n\n this.audiences[audienceName] = {\n clientId,\n host\n };\n }\n\n removeDynamicAudience(audienceName) {\n if (this._dynamicAudienceNames.indexOf(audienceName) === -1) {\n throw new Error('There is no dynamic audience to remove.');\n }\n\n this.audiences[audienceName] = this._replacedAudiences[audienceName];\n\n delete this._replacedAudiences[audienceName];\n this._dynamicAudienceNames = this._dynamicAudienceNames.filter(\n (name) => name !== audienceName\n );\n }\n\n /**\n * Parses a custom module configuration for a valid environment/audience. Requires either a\n * clientId and host, or an environment that matches a default audience/environment.\n *\n * @param {CustomAudience} config A custom audience configuration to parse\n * @param {Object.<string, Audience>} audiences An object with keys for environment names and values of Audience information\n *\n * @returns {Audience}\n * @throws {Error}\n *\n * @private\n */\n _getAudienceFromCustomConfig(config, audiences) {\n if (config.clientId && config.host) {\n const audience = {\n clientId: config.clientId,\n host: config.host\n };\n\n if (config.webSocket) {\n audience.webSocket = config.webSocket;\n }\n\n return audience;\n } else if (config.env) {\n return audiences[config.env];\n } else {\n throw new Error(\n 'Custom module configurations must either contain a `host` and `clientId` or specify a specific target environment via the `env` property'\n );\n }\n }\n\n /**\n * Reconciles the main environment with custom environments and external modules.\n *\n * @param {Object} options\n * @param {Object.<string, CustomAudience>} [options.customModuleConfigs = {}] Any custom\n * configurations for internal modules\n * @param {string} [options.env = 'production'] The base environment for any\n * non-overridden modules\n * @param {Object.<string, ExternalModule>} [options.externalModules = {}] An object of external\n * modules from which to build a set of audiences\n *\n * @returns {Object.<string, Audience>}\n *\n * @private\n */\n _getAudiences(options = {}) {\n const {\n customModuleConfigs = {},\n env = 'production',\n externalModules = {}\n } = options;\n\n return {\n ...this._getInternalAudiences({\n customModuleConfigs,\n env,\n audiences: defaultAudiences\n }),\n ...this._getExternalAudiences({ externalModules })\n };\n }\n\n /**\n * Builds up the audiences for external modules.\n *\n * @param {Object}\n * @param {Object.<string, ExternalModule>} externalModules An object of external modules from\n * which to build a set of audiences\n *\n * @returns {Object.<string, Audience>}\n * @throws {Error}\n *\n * @private\n */\n _getExternalAudiences({ externalModules }) {\n return Object.keys(externalModules).reduce((memo, key) => {\n const clientId = externalModules[key].clientId;\n const host = externalModules[key].host;\n const hasClientId = !!clientId || clientId === null;\n const hasHost = !!host || host === null;\n\n if (!(hasClientId && hasHost)) {\n throw new Error(\n 'External modules must contain `clientId` and `host` properties'\n );\n }\n\n memo[key] = {\n clientId,\n host\n };\n\n return memo;\n }, {});\n }\n\n /**\n * Reconciles the main environment with custom environments to build up audiences for\n * internal modules.\n *\n * @param {Object.<string, Environments>} audiences All possible audiences/environments for\n * internal modules\n * @param {Object.<string, CustomAudience>} customModuleConfigs Any custom configurations for\n * internal modules\n * @param {string} env The base environment for any non-overridden modules\n *\n * @returns {Object.<string, Audience>}\n *\n * @private\n */\n _getInternalAudiences({ audiences, customModuleConfigs, env }) {\n return Object.keys(audiences).reduce((memo, key) => {\n const customModuleConfig = customModuleConfigs[key];\n const moduleAudiences = audiences[key];\n\n if (customModuleConfig) {\n memo[key] = this._getAudienceFromCustomConfig(\n customModuleConfig,\n moduleAudiences\n );\n } else {\n memo[key] = moduleAudiences[env];\n }\n\n return memo;\n }, {});\n }\n}\n\nexport default Config;\n"]}
|
package/esm/index.js
CHANGED
|
@@ -93,7 +93,7 @@ var ContxtSdk = function () {
|
|
|
93
93
|
this.config = new Config(config, externalModules);
|
|
94
94
|
|
|
95
95
|
this.auth = this._createAuthSession(sessionType);
|
|
96
|
-
this.bus = new Bus(this, this._createRequest('bus'));
|
|
96
|
+
this.bus = new Bus(this, this._createRequest('bus'), this.config.bus);
|
|
97
97
|
this.coordinator = new Coordinator(this, this._createRequest('coordinator'));
|
|
98
98
|
this.events = new Events(this, this._createRequest('events'));
|
|
99
99
|
this.files = new Files(this, this._createRequest('files'));
|
package/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["index.js"],"names":["Bus","Config","Coordinator","Events","Files","Iot","Nionic","Request","sessionTypes","toSnakeCase","toCamelCase","ContxtSdk","config","externalModules","sessionType","_dynamicModuleNames","_replacedModules","auth","_createAuthSession","bus","_createRequest","coordinator","events","files","iot","nionic","_decorate","moduleName","clientId","host","module","indexOf","Error","addDynamicAudience","clearCurrentApiToken","removeDynamicAudience","filter","name","TYPES","AUTH0_WEB_AUTH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f,MAAL,CAAYuB,qBAAZ,CAAkCR,UAAlC;;AAEA,WAAKA,UAAL,IAAmB,KAAKX,gBAAL,CAAsBW,UAAtB,CAAnB;;AAEA,aAAO,KAAKX,gBAAL,CAAsBW,UAAtB,CAAP;AACA,WAAKZ,mBAAL,GAA2B,KAAKA,mBAAL,CAAyBqB,MAAzB,CACzB,UAACC,IAAD;AAAA,eAAUA,SAASV,UAAnB;AAAA,OADyB,CAA3B;AAGD;;AAED;;;;;;;;;;;;;uCAUmBb,W,EAAa;AAC9B,cAAQA,WAAR;AACE,aAAKN,aAAa8B,KAAb,CAAmBC,cAAxB;AACE,iBAAO,IAAI/B,aAAagC,YAAjB,CAA8B,IAA9B,CAAP;;AAEF,aAAKhC,aAAa8B,KAAb,CAAmBG,mBAAxB;AACE,iBAAO,IAAIjC,aAAakC,iBAAjB,CAAmC,IAAnC,CAAP;;AAEF,aAAKlC,aAAa8B,KAAb,CAAmBK,YAAxB;AACE,iBAAO,IAAInC,aAAaoC,WAAjB,CAA6B,IAA7B,CAAP;;AAEF;AACE,gBAAM,IAAIZ,KAAJ,CAAU,8BAAV,CAAN;AAXJ;AAaD;;AAED;;;;;;;;;;;;;mCAUea,Y,EAAc;AAC3B,aAAO,IAAItC,OAAJ,CAAY,IAAZ,EAAkBsC,YAAlB,CAAP;AACD;;AAED;;;;;;;;;;;8BAQUC,O,EAAS;AAAA;;AACjBC,aAAOC,IAAP,CAAYF,OAAZ,EAAqBG,OAArB,CAA6B,UAACtB,UAAD,EAAgB;AAC3C,cAAKA,UAAL,IAAmB,IAAImB,QAAQnB,UAAR,EAAoBG,MAAxB,CACjB,KADiB,EAEjB,MAAKV,cAAL,CAAoBO,UAApB,CAFiB,CAAnB;AAID,OALD;AAMD;;;;;;AAGH,eAAehB,SAAf;AACA,SAASF,WAAT,EAAsBC,WAAtB","file":"index.js","sourcesContent":["import Bus from './bus';\nimport Config from './config';\nimport Coordinator from './coordinator';\nimport Events from './events';\nimport Files from './files';\nimport Iot from './iot';\nimport Nionic from './nionic';\nimport Request from './request';\nimport * as sessionTypes from './sessionTypes';\nimport { toSnakeCase, toCamelCase } from './utils/objects';\n\n/**\n * An adapter that allows the SDK to authenticate with different services and manage various tokens.\n * Can authenticate with a service like Auth0 and then with Contxt or can communicate directly\n * with Contxt. The adapter must implement required methods, but most methods are optional. Some of\n * the optional methods are documented below.\n *\n * @typedef {Object} SessionType\n * @property {function} [getCurrentAccessToken] Provides a current access token from Auth0 that is\n * used for profile information and can be used to get API token for Contxt itself\n * @property {function} getCurrentApiToken Provides a current API token that is used across\n * different Contxt services\n * @property {function} [getProfile] Provides profile information about the current user\n * @property {function} [handleAuthentication] Is called by front-end code in the Auth0 reference\n * implementation to handle getting the access token from Auth0\n * @property {function} [isAuthenticated] Tells caller if the current user is authenticated.\n * Different session types may determine if a user is authenticated in different ways.\n * @property {function} [logIn] Is used by front-end code in the Auth0 reference implementation to\n * start the sign in process\n * @property {function} [logOut] Is used by the front-end code in the Auth0 reference implementation\n * to sign the user out\n */\n\n/**\n * ContxtSdk constructor\n *\n * @example\n * import ContxtSdk from '@ndustrial/contxt-sdk';\n * import ExternalModule1 from './ExternalModule1';\n * import history from '../services/history';\n *\n * const contxtSdk = new ContxtSdk({\n * config: {\n * auth: {\n * clientId: 'Auth0 client id of the application being built',\n * customModuleConfigs: {\n * facilities: {\n * env: 'production'\n * }\n * },\n * env: 'staging',\n * onAuthenticate: (auth0WebAuthSessionInfo) => handleSuccessfulAuth(auth0WebAuthSessionInfo),\n * onRedirect: (pathname) => history.push(pathname)\n * }\n * },\n * externalModules: {\n * externalModule1: {\n * clientId: 'Auth0 client id of the external module',\n * host: 'https://www.example.com/externalModule1',\n * module: ExternalModule1\n * }\n * },\n * sessionType: 'auth0WebAuth'\n * });\n */\nclass ContxtSdk {\n /**\n * @param {UserConfig} config The user provided configuration options\n * @param {Object.<string, ExternalModule>} [externalModules] User provided external modules that\n * should be treated as first class citizens\n * @param {string} sessionType The type of auth session you wish to use (e.g. auth0WebAuth\n * or machine)\n */\n constructor({ config = {}, externalModules = {}, sessionType }) {\n this._dynamicModuleNames = [];\n this._replacedModules = {};\n\n this.config = new Config(config, externalModules);\n\n this.auth = this._createAuthSession(sessionType);\n this.bus = new Bus(this, this._createRequest('bus'));\n this.coordinator = new Coordinator(\n this,\n this._createRequest('coordinator')\n );\n this.events = new Events(this, this._createRequest('events'));\n this.files = new Files(this, this._createRequest('files'));\n this.iot = new Iot(this, this._createRequest('iot'));\n this.nionic = new Nionic(this, this._createRequest('nionic'));\n\n this._decorate(externalModules);\n }\n\n /**\n * Mounts a dynamic module into the SDK. Is used to add a module after initial\n * instatiation that will use the SDK's authentication and request methods to\n * access an ndustrial.io API\n *\n * @param {string} moduleName The name (or key) that will serve as the mount\n * point for the module in the SDK (i.e. customModule -> sdk.customModule)\n * @param {ExternalModule} externalModule\n */\n mountDynamicModule(moduleName, { clientId, host, module }) {\n if (this._dynamicModuleNames.indexOf(moduleName) > -1) {\n throw new Error(\n `An dynamic module of the name \\`${moduleName}\\` already exists. This problem can be rectified by using a different name for the new module.`\n );\n }\n\n this.config.addDynamicAudience(moduleName, { clientId, host });\n\n this._dynamicModuleNames = [...this._dynamicModuleNames, moduleName];\n\n if (this[moduleName]) {\n this._replacedModules[moduleName] = this[moduleName];\n }\n\n this[moduleName] = new module(this, this._createRequest(moduleName));\n }\n\n /**\n * Unmounts a dynamic module from the SDK\n *\n * @param {string} moduleName The name of the dynamic module to unmount\n */\n unmountDynamicModule(moduleName) {\n if (this._dynamicModuleNames.indexOf(moduleName) === -1) {\n throw new Error('There is no external module to unmount.');\n }\n\n this.auth.clearCurrentApiToken(moduleName);\n this.config.removeDynamicAudience(moduleName);\n\n this[moduleName] = this._replacedModules[moduleName];\n\n delete this._replacedModules[moduleName];\n this._dynamicModuleNames = this._dynamicModuleNames.filter(\n (name) => name !== moduleName\n );\n }\n\n /**\n * Returns a new instance of the session type requested\n *\n * @param {string} sessionType\n *\n * @returns {SessionType} sessionType\n * @throws {Error}\n *\n * @private\n */\n _createAuthSession(sessionType) {\n switch (sessionType) {\n case sessionTypes.TYPES.AUTH0_WEB_AUTH:\n return new sessionTypes.Auth0WebAuth(this);\n\n case sessionTypes.TYPES.PASSWORD_GRANT_AUTH:\n return new sessionTypes.PasswordGrantAuth(this);\n\n case sessionTypes.TYPES.MACHINE_AUTH:\n return new sessionTypes.MachineAuth(this);\n\n default:\n throw new Error('Invalid sessionType provided');\n }\n }\n\n /**\n * Returns an instance of the Request module that is tied to the requested audience\n *\n * @param {string} audienceName The audience name of the service you are trying to reach\n * (e.g. facilities or feeds)\n *\n * @returns {Object} Request module\n *\n * @private\n */\n _createRequest(audienceName) {\n return new Request(this, audienceName);\n }\n\n /**\n * Decorates custom modules onto the SDK instance so they behave as first-class citizens.\n *\n * @param {Object} modules\n * @param {function} modules.module\n *\n * @private\n */\n _decorate(modules) {\n Object.keys(modules).forEach((moduleName) => {\n this[moduleName] = new modules[moduleName].module(\n this,\n this._createRequest(moduleName)\n );\n });\n }\n}\n\nexport default ContxtSdk;\nexport { toSnakeCase, toCamelCase };\n"]}
|
|
1
|
+
{"version":3,"sources":["index.js"],"names":["Bus","Config","Coordinator","Events","Files","Iot","Nionic","Request","sessionTypes","toSnakeCase","toCamelCase","ContxtSdk","config","externalModules","sessionType","_dynamicModuleNames","_replacedModules","auth","_createAuthSession","bus","_createRequest","coordinator","events","files","iot","nionic","_decorate","moduleName","clientId","host","module","indexOf","Error","addDynamicAudience","clearCurrentApiToken","removeDynamicAudience","filter","name","TYPES","AUTH0_WEB_AUTH","Auth0WebAuth","PASSWORD_GRANT_AUTH","PasswordGrantAuth","MACHINE_AUTH","MachineAuth","audienceName","modules","Object","keys","forEach"],"mappings":";;;;;;AAAA,OAAOA,GAAP,MAAgB,OAAhB;AACA,OAAOC,MAAP,MAAmB,UAAnB;AACA,OAAOC,WAAP,MAAwB,eAAxB;AACA,OAAOC,MAAP,MAAmB,UAAnB;AACA,OAAOC,KAAP,MAAkB,SAAlB;AAC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A,eAAUA,SAASV,UAAnB;AAAA,OADyB,CAA3B;AAGD;;AAED;;;;;;;;;;;;;uCAUmBb,W,EAAa;AAC9B,cAAQA,WAAR;AACE,aAAKN,aAAa8B,KAAb,CAAmBC,cAAxB;AACE,iBAAO,IAAI/B,aAAagC,YAAjB,CAA8B,IAA9B,CAAP;;AAEF,aAAKhC,aAAa8B,KAAb,CAAmBG,mBAAxB;AACE,iBAAO,IAAIjC,aAAakC,iBAAjB,CAAmC,IAAnC,CAAP;;AAEF,aAAKlC,aAAa8B,KAAb,CAAmBK,YAAxB;AACE,iBAAO,IAAInC,aAAaoC,WAAjB,CAA6B,IAA7B,CAAP;;AAEF;AACE,gBAAM,IAAIZ,KAAJ,CAAU,8BAAV,CAAN;AAXJ;AAaD;;AAED;;;;;;;;;;;;;mCAUea,Y,EAAc;AAC3B,aAAO,IAAItC,OAAJ,CAAY,IAAZ,EAAkBsC,YAAlB,CAAP;AACD;;AAED;;;;;;;;;;;8BAQUC,O,EAAS;AAAA;;AACjBC,aAAOC,IAAP,CAAYF,OAAZ,EAAqBG,OAArB,CAA6B,UAACtB,UAAD,EAAgB;AAC3C,cAAKA,UAAL,IAAmB,IAAImB,QAAQnB,UAAR,EAAoBG,MAAxB,CACjB,KADiB,EAEjB,MAAKV,cAAL,CAAoBO,UAApB,CAFiB,CAAnB;AAID,OALD;AAMD;;;;;;AAGH,eAAehB,SAAf;AACA,SAASF,WAAT,EAAsBC,WAAtB","file":"index.js","sourcesContent":["import Bus from './bus';\nimport Config from './config';\nimport Coordinator from './coordinator';\nimport Events from './events';\nimport Files from './files';\nimport Iot from './iot';\nimport Nionic from './nionic';\nimport Request from './request';\nimport * as sessionTypes from './sessionTypes';\nimport { toSnakeCase, toCamelCase } from './utils/objects';\n\n/**\n * An adapter that allows the SDK to authenticate with different services and manage various tokens.\n * Can authenticate with a service like Auth0 and then with Contxt or can communicate directly\n * with Contxt. The adapter must implement required methods, but most methods are optional. Some of\n * the optional methods are documented below.\n *\n * @typedef {Object} SessionType\n * @property {function} [getCurrentAccessToken] Provides a current access token from Auth0 that is\n * used for profile information and can be used to get API token for Contxt itself\n * @property {function} getCurrentApiToken Provides a current API token that is used across\n * different Contxt services\n * @property {function} [getProfile] Provides profile information about the current user\n * @property {function} [handleAuthentication] Is called by front-end code in the Auth0 reference\n * implementation to handle getting the access token from Auth0\n * @property {function} [isAuthenticated] Tells caller if the current user is authenticated.\n * Different session types may determine if a user is authenticated in different ways.\n * @property {function} [logIn] Is used by front-end code in the Auth0 reference implementation to\n * start the sign in process\n * @property {function} [logOut] Is used by the front-end code in the Auth0 reference implementation\n * to sign the user out\n */\n\n/**\n * ContxtSdk constructor\n *\n * @example\n * import ContxtSdk from '@ndustrial/contxt-sdk';\n * import ExternalModule1 from './ExternalModule1';\n * import history from '../services/history';\n *\n * const contxtSdk = new ContxtSdk({\n * config: {\n * auth: {\n * clientId: 'Auth0 client id of the application being built',\n * customModuleConfigs: {\n * facilities: {\n * env: 'production'\n * }\n * },\n * env: 'staging',\n * onAuthenticate: (auth0WebAuthSessionInfo) => handleSuccessfulAuth(auth0WebAuthSessionInfo),\n * onRedirect: (pathname) => history.push(pathname)\n * }\n * },\n * externalModules: {\n * externalModule1: {\n * clientId: 'Auth0 client id of the external module',\n * host: 'https://www.example.com/externalModule1',\n * module: ExternalModule1\n * }\n * },\n * sessionType: 'auth0WebAuth'\n * });\n */\nclass ContxtSdk {\n /**\n * @param {UserConfig} config The user provided configuration options\n * @param {Object.<string, ExternalModule>} [externalModules] User provided external modules that\n * should be treated as first class citizens\n * @param {string} sessionType The type of auth session you wish to use (e.g. auth0WebAuth\n * or machine)\n */\n constructor({ config = {}, externalModules = {}, sessionType }) {\n this._dynamicModuleNames = [];\n this._replacedModules = {};\n\n this.config = new Config(config, externalModules);\n\n this.auth = this._createAuthSession(sessionType);\n this.bus = new Bus(this, this._createRequest('bus'), this.config.bus);\n this.coordinator = new Coordinator(\n this,\n this._createRequest('coordinator')\n );\n this.events = new Events(this, this._createRequest('events'));\n this.files = new Files(this, this._createRequest('files'));\n this.iot = new Iot(this, this._createRequest('iot'));\n this.nionic = new Nionic(this, this._createRequest('nionic'));\n\n this._decorate(externalModules);\n }\n\n /**\n * Mounts a dynamic module into the SDK. Is used to add a module after initial\n * instatiation that will use the SDK's authentication and request methods to\n * access an ndustrial.io API\n *\n * @param {string} moduleName The name (or key) that will serve as the mount\n * point for the module in the SDK (i.e. customModule -> sdk.customModule)\n * @param {ExternalModule} externalModule\n */\n mountDynamicModule(moduleName, { clientId, host, module }) {\n if (this._dynamicModuleNames.indexOf(moduleName) > -1) {\n throw new Error(\n `An dynamic module of the name \\`${moduleName}\\` already exists. This problem can be rectified by using a different name for the new module.`\n );\n }\n\n this.config.addDynamicAudience(moduleName, { clientId, host });\n\n this._dynamicModuleNames = [...this._dynamicModuleNames, moduleName];\n\n if (this[moduleName]) {\n this._replacedModules[moduleName] = this[moduleName];\n }\n\n this[moduleName] = new module(this, this._createRequest(moduleName));\n }\n\n /**\n * Unmounts a dynamic module from the SDK\n *\n * @param {string} moduleName The name of the dynamic module to unmount\n */\n unmountDynamicModule(moduleName) {\n if (this._dynamicModuleNames.indexOf(moduleName) === -1) {\n throw new Error('There is no external module to unmount.');\n }\n\n this.auth.clearCurrentApiToken(moduleName);\n this.config.removeDynamicAudience(moduleName);\n\n this[moduleName] = this._replacedModules[moduleName];\n\n delete this._replacedModules[moduleName];\n this._dynamicModuleNames = this._dynamicModuleNames.filter(\n (name) => name !== moduleName\n );\n }\n\n /**\n * Returns a new instance of the session type requested\n *\n * @param {string} sessionType\n *\n * @returns {SessionType} sessionType\n * @throws {Error}\n *\n * @private\n */\n _createAuthSession(sessionType) {\n switch (sessionType) {\n case sessionTypes.TYPES.AUTH0_WEB_AUTH:\n return new sessionTypes.Auth0WebAuth(this);\n\n case sessionTypes.TYPES.PASSWORD_GRANT_AUTH:\n return new sessionTypes.PasswordGrantAuth(this);\n\n case sessionTypes.TYPES.MACHINE_AUTH:\n return new sessionTypes.MachineAuth(this);\n\n default:\n throw new Error('Invalid sessionType provided');\n }\n }\n\n /**\n * Returns an instance of the Request module that is tied to the requested audience\n *\n * @param {string} audienceName The audience name of the service you are trying to reach\n * (e.g. facilities or feeds)\n *\n * @returns {Object} Request module\n *\n * @private\n */\n _createRequest(audienceName) {\n return new Request(this, audienceName);\n }\n\n /**\n * Decorates custom modules onto the SDK instance so they behave as first-class citizens.\n *\n * @param {Object} modules\n * @param {function} modules.module\n *\n * @private\n */\n _decorate(modules) {\n Object.keys(modules).forEach((moduleName) => {\n this[moduleName] = new modules[moduleName].module(\n this,\n this._createRequest(moduleName)\n );\n });\n }\n}\n\nexport default ContxtSdk;\nexport { toSnakeCase, toCamelCase };\n"]}
|
package/lib/bus/index.js
CHANGED
|
@@ -54,6 +54,20 @@ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Cons
|
|
|
54
54
|
* @property {WebSocket} _webSocket The raw WebSocket connection to the message bus
|
|
55
55
|
*/
|
|
56
56
|
|
|
57
|
+
/**
|
|
58
|
+
* Configuration object for the Bus
|
|
59
|
+
*
|
|
60
|
+
* @typedef {Object} BusConfig
|
|
61
|
+
* @property {boolean} autoAcknowledge
|
|
62
|
+
*/
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* @type {BusConfig}
|
|
66
|
+
*/
|
|
67
|
+
var defaultBusConfig = {
|
|
68
|
+
autoAcknowledge: true
|
|
69
|
+
};
|
|
70
|
+
|
|
57
71
|
/**
|
|
58
72
|
* Module that provides access to the message bus. This is for Node
|
|
59
73
|
* environments. Documentation for browser environments is found under
|
|
@@ -61,12 +75,14 @@ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Cons
|
|
|
61
75
|
*
|
|
62
76
|
* @typicalname contxtSdk.bus
|
|
63
77
|
*/
|
|
78
|
+
|
|
64
79
|
var Bus = function () {
|
|
65
80
|
/**
|
|
66
81
|
* @param {Object} sdk An instance of the SDK so the module can communicate with other modules
|
|
67
82
|
* @param {Object} request An instance of the request module tied to this module's audience.
|
|
83
|
+
* @param {BusConfig} config A config object for the Bus instance
|
|
68
84
|
*/
|
|
69
|
-
function Bus(sdk, request) {
|
|
85
|
+
function Bus(sdk, request, config) {
|
|
70
86
|
_classCallCheck(this, Bus);
|
|
71
87
|
|
|
72
88
|
var baseUrl = '' + sdk.config.audiences.bus.host;
|
|
@@ -77,6 +93,7 @@ var Bus = function () {
|
|
|
77
93
|
this._request = request;
|
|
78
94
|
this._sdk = sdk;
|
|
79
95
|
this._webSockets = {};
|
|
96
|
+
this._config = Object.assign({}, defaultBusConfig, config);
|
|
80
97
|
|
|
81
98
|
this.channels = new _channels2.default(sdk, request, baseUrl);
|
|
82
99
|
}
|
|
@@ -120,7 +137,7 @@ var Bus = function () {
|
|
|
120
137
|
});
|
|
121
138
|
|
|
122
139
|
ws.onopen = function (event) {
|
|
123
|
-
_this._webSockets[organizationId] = new _webSocketConnection2.default(ws, organizationId);
|
|
140
|
+
_this._webSockets[organizationId] = new _webSocketConnection2.default(ws, organizationId, _this._config.autoAcknowledge);
|
|
124
141
|
|
|
125
142
|
resolve(_this._webSockets[organizationId]);
|
|
126
143
|
};
|
package/lib/bus/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["bus/index.js"],"names":["Bus","sdk","request","
|
|
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,m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CN,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"]}
|
|
@@ -44,10 +44,13 @@ var WebSocketConnection = function () {
|
|
|
44
44
|
/**
|
|
45
45
|
* @param {WebSocket} webSocket A WebSocket connection to the message bus
|
|
46
46
|
* @param {string} organizationId UUID corresponding with an organization
|
|
47
|
+
* @param {boolean} autoAcknowledge Whether the messages should be ACK'd explicitly or not
|
|
47
48
|
*/
|
|
48
49
|
function WebSocketConnection(webSocket, organizationId) {
|
|
49
50
|
var _this = this;
|
|
50
51
|
|
|
52
|
+
var autoAcknowledge = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
|
|
53
|
+
|
|
51
54
|
_classCallCheck(this, WebSocketConnection);
|
|
52
55
|
|
|
53
56
|
this._onError = function (error) {
|
|
@@ -73,6 +76,7 @@ var WebSocketConnection = function () {
|
|
|
73
76
|
this._messageHandlers = {};
|
|
74
77
|
this._organizationId = organizationId;
|
|
75
78
|
this._webSocket = webSocket;
|
|
79
|
+
this._autoAck = autoAcknowledge;
|
|
76
80
|
|
|
77
81
|
if (this._webSocket) {
|
|
78
82
|
this._webSocket.onerror = this._onError;
|
|
@@ -311,20 +315,24 @@ var WebSocketConnection = function () {
|
|
|
311
315
|
|
|
312
316
|
if (error) {
|
|
313
317
|
return resolve(errorHandler(error));
|
|
314
|
-
}
|
|
315
|
-
try {
|
|
316
|
-
var ack = (0, _lodash2.default)(function () {
|
|
317
|
-
return _this2._acknowledge(result.id);
|
|
318
|
-
});
|
|
318
|
+
}
|
|
319
319
|
|
|
320
|
-
|
|
320
|
+
try {
|
|
321
|
+
var ack = (0, _lodash2.default)(function () {
|
|
322
|
+
return _this2._acknowledge(result.id);
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
return resolve(Promise.resolve(handler(result.body, ack)).then(function (res) {
|
|
326
|
+
if (_this2._autoAck) {
|
|
321
327
|
return ack().then(function () {
|
|
322
328
|
return res;
|
|
323
329
|
});
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
return
|
|
327
|
-
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
return res;
|
|
333
|
+
}));
|
|
334
|
+
} catch (throwable) {
|
|
335
|
+
return reject(throwable);
|
|
328
336
|
}
|
|
329
337
|
});
|
|
330
338
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["bus/webSocketConnection.js"],"names":["WebSocketConnection","webSocket","organizationId","_onError","error","_messageHandlers","console","log","_onMessage","message","messageData","JSON","parse","data","err","Error","id","_organizationId","_webSocket","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;;;;AAIA,+BAAYC,SAAZ,EAAuBC,cAAvB,EAAuC;AAAA;;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vBD;;AAyBA,eAAOR,MAAP;AACD,OA5BI,CAAP;AA8BD;;AAED;;;;;;;;;;;;;iCAUaS,qB,EAAuB;AAClC,UAAI,CAAC,KAAKpB,YAAL,EAAL,EAA0B;AACxB,eAAOF,QAAQC,MAAR,CAAe,IAAIR,KAAJ,CAAU,+BAAV,CAAf,CAAP;AACD;;AAED,aAAO,KAAKU,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,eAAK1C,gBAAL,CAAsB0C,SAAtB,IAAmC,UAACtC,OAAD,EAAa;AAC9C,cAAML,QAAQK,QAAQL,KAAtB;AACA,iBAAO,OAAKC,gBAAL,CAAsB0C,SAAtB,CAAP;;AAEA,cAAI3C,KAAJ,EAAW;AACT,mBAAOmB,OAAOnB,KAAP,CAAP;AACD;;AAED,iBAAOkC,QAAQ7B,QAAQ0B,MAAhB,CAAP;AACD,SATD;;AAWA,eAAKjB,UAAL,CAAgB8B,IAAhB,CACErC,KAAKsC,SAAL,CAAe;AACbC,mBAAS,KADI;AAEbJ,kCAAsBA,MAFT;AAGbb,wBAHa;AAIbjB,cAAI+B;AAJS,SAAf,CADF;AAQD,OAtBM,CAAP;AAuBD;;AAED;;;;;;;;;;mCAOe;AACb,aACE,KAAK7B,UAAL,IAAmB,KAAKA,UAAL,CAAgBiC,UAAhB,KAA+B,KAAKjC,UAAL,CAAgBkC,IADpE;AAGD;;;;;;kBAGYpD,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 */\n constructor(webSocket, organizationId) {\n this._messageHandlers = {};\n this._organizationId = organizationId;\n this._webSocket = webSocket;\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 } else {\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 return ack().then(() => res);\n })\n );\n } catch (throwable) {\n return reject(throwable);\n }\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","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,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,EAAxB;AACA,SAAKY,eAAL,GAAuBhB,cAAvB;AACA,SAAKiB,UAAL,GAAkBlB,SAAl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AtB;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"]}
|
package/lib/config/defaults.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["config/defaults.js"],"names":["auth","domain","authorizationPath","tokenExpiresAtBufferMs","interceptors","request","response"],"mappings":";;;;;kBAAe;AACbA,QAAM;AACJC,YAAQ,qBADJ;AAEJC,uBAAmB,WAFf;AAGJC,4BAAwB,IAAI,EAAJ,GAAS,IAH7B,CAGkC;AAHlC,GADO;AAMbC,gBAAc;AACZC,aAAS,EADG;AAEZC,cAAU;AAFE;
|
|
1
|
+
{"version":3,"sources":["config/defaults.js"],"names":["auth","domain","authorizationPath","tokenExpiresAtBufferMs","interceptors","request","response","bus","autoAcknowledge"],"mappings":";;;;;kBAAe;AACbA,QAAM;AACJC,YAAQ,qBADJ;AAEJC,uBAAmB,WAFf;AAGJC,4BAAwB,IAAI,EAAJ,GAAS,IAH7B,CAGkC;AAHlC,GADO;AAMbC,gBAAc;AACZC,aAAS,EADG;AAEZC,cAAU;AAFE,GAND;AAUbC,OAAK;AACHC,qBAAiB;AADd;AAVQ,C","file":"defaults.js","sourcesContent":["export default {\n auth: {\n domain: 'ndustrial.auth0.com',\n authorizationPath: '/callback',\n tokenExpiresAtBufferMs: 5 * 60 * 1000 // 5 minutes\n },\n interceptors: {\n request: [],\n response: []\n },\n bus: {\n autoAcknowledge: true\n }\n};\n"]}
|
package/lib/config/index.js
CHANGED
|
@@ -133,6 +133,8 @@ var Config = function () {
|
|
|
133
133
|
this.auth = _extends({}, _defaults2.default.auth, userConfig.auth);
|
|
134
134
|
|
|
135
135
|
this.interceptors = _extends({}, _defaults2.default.interceptors, userConfig.interceptors);
|
|
136
|
+
|
|
137
|
+
this.bus = _extends({}, _defaults2.default.bus, userConfig.bus);
|
|
136
138
|
}
|
|
137
139
|
|
|
138
140
|
_createClass(Config, [{
|
package/lib/config/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["config/index.js"],"names":["Config","userConfig","externalModules","Object","assign","_dynamicAudienceNames","_replacedAudiences","audiences","_getAudiences","customModuleConfigs","auth","env","defaultConfigs","interceptors","audienceName","clientId","host","Error","indexOf","filter","name","config","audience","webSocket","options","_getInternalAudiences","defaultAudiences","_getExternalAudiences","keys","reduce","memo","key","hasClientId","hasHost","customModuleConfig","moduleAudiences","_getAudienceFromCustomConfig"],"mappings":";;;;;;;;;;AAAA;;;;AACA;;;;;;;;;;AAEA;;;;;;;;;;AAUA;;;;;;;;;;;;;AAaA;;;;;;;AAOA;;;;;;;;;;;;;;AAcA;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;;;;;;;;;;;;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udiences from './audiences';\nimport defaultConfigs from './defaults';\n\n/**\n * A single audience used for authenticating and communicating with an individual API.\n *\n * @typedef {Object} Audience\n * @param {string} config.clientId Client Id provided by Auth0 for the environment you are\n * trying to communicate with\n * @param {string} config.host Hostname for the API that corresponds with the clientId provided\n * @param {string} [config.webSocket] WebSocket URL for the API that corresponds with the clientId provided\n */\n\n/**\n * A custom audience that will override the configuration of an individual module. Consists of\n * either a reference to an environment that already exists or a clientId and host for a\n * custom environment.\n *\n * @typedef {Object} CustomAudience\n * @param {string} [config.clientId] Client Id provided by Auth0 for the environment you are\n * trying to communicate with\n * @param {string} [config.env] The SDK provided environment name you are trying to reach\n * @param {string} [config.host] Hostname for the API that corresponds with the clientId provided\n * @param {string} [config.webSocket] WebSocket URL for the API that corresponds with the clientId provided\n */\n\n/**\n * An object of audiences that corresponds to all the different environments available for a\n * single module.\n *\n * @typedef {Object.<string, Audience>} Environments\n */\n\n/**\n * An external module to be integrated into the SDK as a first class citizen. Includes information\n * for authenticating and communicating with an individual API and the external module itself.\n *\n * @typedef {Object} ExternalModule\n * @param {string} config.clientId Client Id provided by Auth0 for the environment you are\n * trying to communicate with. Can be a `null` value if the value is not needed. Some SessionType\n * adapters (currently, just the MachineAuth adapter) require a value other than `null` if the\n * built-in `request` module is used since they acquire contxt tokens based on a single clientId.\n * @param {string} config.host Hostname for the API that corresponds with the clientId provided.\n * Can be a `null` value if the value is not needed.\n * @param {function} config.module The module that will be decorated into the SDK\n */\n\n/**\n * An object of interceptors that get called on every request or response.\n * More information at {@link https://github.com/axios/axios#interceptors axios Interceptors}\n *\n * @typedef {Object} AxiosInterceptor\n * @param {function} interceptor.fulfilled A function that is run on every successful request or\n * response\n * @param {function} interceptor.rejected A function that is run on every failed request or response\n */\n\n/**\n * User provided configuration options\n *\n * @typedef {Object} UserConfig\n * @property {Object} auth User assigned configurations specific for their authentication methods\n * @property {string} [auth.authorizationPath] Path Auth0WebAuth process should redirect to after a\n * successful sign in attempt\n * @property {string} auth.clientId Client Id provided by Auth0 for this application\n * @property {string} [auth.clientSecret] Client secret provided by Auth0 for this application. This\n * is optional for the auth0WebAuth SessionType, but required for the machineAuth SessionType\n * @property {string} [auth.domain] Auth0 domain for this application. This is an optional configuration\n * that defaults to the production Auth0 tenant\n * @property {Object.<string, CustomAudience>} [auth.customModuleConfigs] Custom environment setups\n * for individual modules. Requires clientId/host or env\n * @property {string} [auth.env = 'production'] The environment that every module should use for\n * their clientId and host\n * @property {function} [auth.onAuthenticate = (auth0WebAuthSessionInfo) => handleSuccessfulAuth(auth0WebAuthSessionInfo); ] An optional\n * hook for handling a successful authentication request or overriding returned values.\n * @property {function} [auth.onRedirect = (pathname) => { window.location = pathname; }] A redirect\n * method used for navigating through Auth0 callbacks in Web applications\n * @property {number} [auth.tokenExpiresAtBufferMs = 300000] The time (in milliseconds) before a\n * token truly expires that we consider it expired (i.e. the token's expiresAt - this = calculated\n * expiresAt). Defaults to 5 minutes.\n * @property {Object} [interceptors] Axios interceptors that can transform requests and responses.\n * More information at {@link https://github.com/axios/axios#interceptors axios Interceptors}\n * @property {AxiosInterceptor[]} [interceptors.request] Interceptors that act on every request\n * @property {AxiosInterceptor[]} [intercepotrs.response] Intereptors that act on every response\n */\n\n/**\n * Module that merges user assigned configurations with default configurations.\n *\n * @typicalname contxtSdk.config\n */\nclass Config {\n /**\n * @param {UserConfig} userConfig The user provided configuration options\n * @param {Object.<string, ExternalModule>} [externalModules] User provided external modules that should be treated as\n * first class citizens\n */\n constructor(userConfig, externalModules) {\n Object.assign(this, userConfig);\n\n this._dynamicAudienceNames = [];\n this._replacedAudiences = {};\n\n this.audiences = this._getAudiences({\n externalModules,\n customModuleConfigs: userConfig.auth.customModuleConfigs,\n env: userConfig.auth.env\n });\n\n this.auth = {\n ...defaultConfigs.auth,\n ...userConfig.auth\n };\n\n this.interceptors = {\n ...defaultConfigs.interceptors,\n ...userConfig.interceptors\n };\n }\n\n addDynamicAudience(audienceName, { clientId, host }) {\n if (!clientId || !host) {\n throw new Error(\n 'A dynamic audience must contain `clientId` and `host` properties'\n );\n }\n\n if (this._dynamicAudienceNames.indexOf(audienceName) > -1) {\n throw new Error(\n `A dynamic audience of the name \\`${audienceName}\\` already exists. This problem can be rectified by using a different name for the audience.`\n );\n }\n\n this._dynamicAudienceNames = [...this._dynamicAudienceNames, audienceName];\n\n if (this.audiences[audienceName]) {\n this._replacedAudiences[audienceName] = this.audiences[audienceName];\n }\n\n this.audiences[audienceName] = {\n clientId,\n host\n };\n }\n\n removeDynamicAudience(audienceName) {\n if (this._dynamicAudienceNames.indexOf(audienceName) === -1) {\n throw new Error('There is no dynamic audience to remove.');\n }\n\n this.audiences[audienceName] = this._replacedAudiences[audienceName];\n\n delete this._replacedAudiences[audienceName];\n this._dynamicAudienceNames = this._dynamicAudienceNames.filter(\n (name) => name !== audienceName\n );\n }\n\n /**\n * Parses a custom module configuration for a valid environment/audience. Requires either a\n * clientId and host, or an environment that matches a default audience/environment.\n *\n * @param {CustomAudience} config A custom audience configuration to parse\n * @param {Object.<string, Audience>} audiences An object with keys for environment names and values of Audience information\n *\n * @returns {Audience}\n * @throws {Error}\n *\n * @private\n */\n _getAudienceFromCustomConfig(config, audiences) {\n if (config.clientId && config.host) {\n const audience = {\n clientId: config.clientId,\n host: config.host\n };\n\n if (config.webSocket) {\n audience.webSocket = config.webSocket;\n }\n\n return audience;\n } else if (config.env) {\n return audiences[config.env];\n } else {\n throw new Error(\n 'Custom module configurations must either contain a `host` and `clientId` or specify a specific target environment via the `env` property'\n );\n }\n }\n\n /**\n * Reconciles the main environment with custom environments and external modules.\n *\n * @param {Object} options\n * @param {Object.<string, CustomAudience>} [options.customModuleConfigs = {}] Any custom\n * configurations for internal modules\n * @param {string} [options.env = 'production'] The base environment for any\n * non-overridden modules\n * @param {Object.<string, ExternalModule>} [options.externalModules = {}] An object of external\n * modules from which to build a set of audiences\n *\n * @returns {Object.<string, Audience>}\n *\n * @private\n */\n _getAudiences(options = {}) {\n const {\n customModuleConfigs = {},\n env = 'production',\n externalModules = {}\n } = options;\n\n return {\n ...this._getInternalAudiences({\n customModuleConfigs,\n env,\n audiences: defaultAudiences\n }),\n ...this._getExternalAudiences({ externalModules })\n };\n }\n\n /**\n * Builds up the audiences for external modules.\n *\n * @param {Object}\n * @param {Object.<string, ExternalModule>} externalModules An object of external modules from\n * which to build a set of audiences\n *\n * @returns {Object.<string, Audience>}\n * @throws {Error}\n *\n * @private\n */\n _getExternalAudiences({ externalModules }) {\n return Object.keys(externalModules).reduce((memo, key) => {\n const clientId = externalModules[key].clientId;\n const host = externalModules[key].host;\n const hasClientId = !!clientId || clientId === null;\n const hasHost = !!host || host === null;\n\n if (!(hasClientId && hasHost)) {\n throw new Error(\n 'External modules must contain `clientId` and `host` properties'\n );\n }\n\n memo[key] = {\n clientId,\n host\n };\n\n return memo;\n }, {});\n }\n\n /**\n * Reconciles the main environment with custom environments to build up audiences for\n * internal modules.\n *\n * @param {Object.<string, Environments>} audiences All possible audiences/environments for\n * internal modules\n * @param {Object.<string, CustomAudience>} customModuleConfigs Any custom configurations for\n * internal modules\n * @param {string} env The base environment for any non-overridden modules\n *\n * @returns {Object.<string, Audience>}\n *\n * @private\n */\n _getInternalAudiences({ audiences, customModuleConfigs, env }) {\n return Object.keys(audiences).reduce((memo, key) => {\n const customModuleConfig = customModuleConfigs[key];\n const moduleAudiences = audiences[key];\n\n if (customModuleConfig) {\n memo[key] = this._getAudienceFromCustomConfig(\n customModuleConfig,\n moduleAudiences\n );\n } else {\n memo[key] = moduleAudiences[env];\n }\n\n return memo;\n }, {});\n }\n}\n\nexport default Config;\n"]}
|
|
1
|
+
{"version":3,"sources":["config/index.js"],"names":["Config","userConfig","externalModules","Object","assign","_dynamicAudienceNames","_replacedAudiences","audiences","_getAudiences","customModuleConfigs","auth","env","defaultConfigs","interceptors","bus","audienceName","clientId","host","Error","indexOf","filter","name","config","audience","webSocket","options","_getInternalAudiences","defaultAudiences","_getExternalAudiences","keys","reduce","memo","key","hasClientId","hasH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;AAEA,YAAIG,kBAAJ,EAAwB;AACtBJ,eAAKC,GAAL,IAAY,MAAKK,4BAAL,CACVF,kBADU,EAEVC,eAFU,CAAZ;AAID,SALD,MAKO;AACLL,eAAKC,GAAL,IAAYI,gBAAgBzB,GAAhB,CAAZ;AACD;;AAED,eAAOoB,IAAP;AACD,OAdM,EAcJ,EAdI,CAAP;AAeD;;;;;;kBAGY/B,M","file":"index.js","sourcesContent":["import defaultAudiences from './audiences';\nimport defaultConfigs from './defaults';\n\n/**\n * A single audience used for authenticating and communicating with an individual API.\n *\n * @typedef {Object} Audience\n * @param {string} config.clientId Client Id provided by Auth0 for the environment you are\n * trying to communicate with\n * @param {string} config.host Hostname for the API that corresponds with the clientId provided\n * @param {string} [config.webSocket] WebSocket URL for the API that corresponds with the clientId provided\n */\n\n/**\n * A custom audience that will override the configuration of an individual module. Consists of\n * either a reference to an environment that already exists or a clientId and host for a\n * custom environment.\n *\n * @typedef {Object} CustomAudience\n * @param {string} [config.clientId] Client Id provided by Auth0 for the environment you are\n * trying to communicate with\n * @param {string} [config.env] The SDK provided environment name you are trying to reach\n * @param {string} [config.host] Hostname for the API that corresponds with the clientId provided\n * @param {string} [config.webSocket] WebSocket URL for the API that corresponds with the clientId provided\n */\n\n/**\n * An object of audiences that corresponds to all the different environments available for a\n * single module.\n *\n * @typedef {Object.<string, Audience>} Environments\n */\n\n/**\n * An external module to be integrated into the SDK as a first class citizen. Includes information\n * for authenticating and communicating with an individual API and the external module itself.\n *\n * @typedef {Object} ExternalModule\n * @param {string} config.clientId Client Id provided by Auth0 for the environment you are\n * trying to communicate with. Can be a `null` value if the value is not needed. Some SessionType\n * adapters (currently, just the MachineAuth adapter) require a value other than `null` if the\n * built-in `request` module is used since they acquire contxt tokens based on a single clientId.\n * @param {string} config.host Hostname for the API that corresponds with the clientId provided.\n * Can be a `null` value if the value is not needed.\n * @param {function} config.module The module that will be decorated into the SDK\n */\n\n/**\n * An object of interceptors that get called on every request or response.\n * More information at {@link https://github.com/axios/axios#interceptors axios Interceptors}\n *\n * @typedef {Object} AxiosInterceptor\n * @param {function} interceptor.fulfilled A function that is run on every successful request or\n * response\n * @param {function} interceptor.rejected A function that is run on every failed request or response\n */\n\n/**\n * User provided configuration options\n *\n * @typedef {Object} UserConfig\n * @property {Object} auth User assigned configurations specific for their authentication methods\n * @property {string} [auth.authorizationPath] Path Auth0WebAuth process should redirect to after a\n * successful sign in attempt\n * @property {string} auth.clientId Client Id provided by Auth0 for this application\n * @property {string} [auth.clientSecret] Client secret provided by Auth0 for this application. This\n * is optional for the auth0WebAuth SessionType, but required for the machineAuth SessionType\n * @property {string} [auth.domain] Auth0 domain for this application. This is an optional configuration\n * that defaults to the production Auth0 tenant\n * @property {Object.<string, CustomAudience>} [auth.customModuleConfigs] Custom environment setups\n * for individual modules. Requires clientId/host or env\n * @property {string} [auth.env = 'production'] The environment that every module should use for\n * their clientId and host\n * @property {function} [auth.onAuthenticate = (auth0WebAuthSessionInfo) => handleSuccessfulAuth(auth0WebAuthSessionInfo); ] An optional\n * hook for handling a successful authentication request or overriding returned values.\n * @property {function} [auth.onRedirect = (pathname) => { window.location = pathname; }] A redirect\n * method used for navigating through Auth0 callbacks in Web applications\n * @property {number} [auth.tokenExpiresAtBufferMs = 300000] The time (in milliseconds) before a\n * token truly expires that we consider it expired (i.e. the token's expiresAt - this = calculated\n * expiresAt). Defaults to 5 minutes.\n * @property {Object} [interceptors] Axios interceptors that can transform requests and responses.\n * More information at {@link https://github.com/axios/axios#interceptors axios Interceptors}\n * @property {AxiosInterceptor[]} [interceptors.request] Interceptors that act on every request\n * @property {AxiosInterceptor[]} [intercepotrs.response] Intereptors that act on every response\n */\n\n/**\n * Module that merges user assigned configurations with default configurations.\n *\n * @typicalname contxtSdk.config\n */\nclass Config {\n /**\n * @param {UserConfig} userConfig The user provided configuration options\n * @param {Object.<string, ExternalModule>} [externalModules] User provided external modules that should be treated as\n * first class citizens\n */\n constructor(userConfig, externalModules) {\n Object.assign(this, userConfig);\n\n this._dynamicAudienceNames = [];\n this._replacedAudiences = {};\n\n this.audiences = this._getAudiences({\n externalModules,\n customModuleConfigs: userConfig.auth.customModuleConfigs,\n env: userConfig.auth.env\n });\n\n this.auth = {\n ...defaultConfigs.auth,\n ...userConfig.auth\n };\n\n this.interceptors = {\n ...defaultConfigs.interceptors,\n ...userConfig.interceptors\n };\n\n this.bus = {\n ...defaultConfigs.bus,\n ...userConfig.bus\n };\n }\n\n addDynamicAudience(audienceName, { clientId, host }) {\n if (!clientId || !host) {\n throw new Error(\n 'A dynamic audience must contain `clientId` and `host` properties'\n );\n }\n\n if (this._dynamicAudienceNames.indexOf(audienceName) > -1) {\n throw new Error(\n `A dynamic audience of the name \\`${audienceName}\\` already exists. This problem can be rectified by using a different name for the audience.`\n );\n }\n\n this._dynamicAudienceNames = [...this._dynamicAudienceNames, audienceName];\n\n if (this.audiences[audienceName]) {\n this._replacedAudiences[audienceName] = this.audiences[audienceName];\n }\n\n this.audiences[audienceName] = {\n clientId,\n host\n };\n }\n\n removeDynamicAudience(audienceName) {\n if (this._dynamicAudienceNames.indexOf(audienceName) === -1) {\n throw new Error('There is no dynamic audience to remove.');\n }\n\n this.audiences[audienceName] = this._replacedAudiences[audienceName];\n\n delete this._replacedAudiences[audienceName];\n this._dynamicAudienceNames = this._dynamicAudienceNames.filter(\n (name) => name !== audienceName\n );\n }\n\n /**\n * Parses a custom module configuration for a valid environment/audience. Requires either a\n * clientId and host, or an environment that matches a default audience/environment.\n *\n * @param {CustomAudience} config A custom audience configuration to parse\n * @param {Object.<string, Audience>} audiences An object with keys for environment names and values of Audience information\n *\n * @returns {Audience}\n * @throws {Error}\n *\n * @private\n */\n _getAudienceFromCustomConfig(config, audiences) {\n if (config.clientId && config.host) {\n const audience = {\n clientId: config.clientId,\n host: config.host\n };\n\n if (config.webSocket) {\n audience.webSocket = config.webSocket;\n }\n\n return audience;\n } else if (config.env) {\n return audiences[config.env];\n } else {\n throw new Error(\n 'Custom module configurations must either contain a `host` and `clientId` or specify a specific target environment via the `env` property'\n );\n }\n }\n\n /**\n * Reconciles the main environment with custom environments and external modules.\n *\n * @param {Object} options\n * @param {Object.<string, CustomAudience>} [options.customModuleConfigs = {}] Any custom\n * configurations for internal modules\n * @param {string} [options.env = 'production'] The base environment for any\n * non-overridden modules\n * @param {Object.<string, ExternalModule>} [options.externalModules = {}] An object of external\n * modules from which to build a set of audiences\n *\n * @returns {Object.<string, Audience>}\n *\n * @private\n */\n _getAudiences(options = {}) {\n const {\n customModuleConfigs = {},\n env = 'production',\n externalModules = {}\n } = options;\n\n return {\n ...this._getInternalAudiences({\n customModuleConfigs,\n env,\n audiences: defaultAudiences\n }),\n ...this._getExternalAudiences({ externalModules })\n };\n }\n\n /**\n * Builds up the audiences for external modules.\n *\n * @param {Object}\n * @param {Object.<string, ExternalModule>} externalModules An object of external modules from\n * which to build a set of audiences\n *\n * @returns {Object.<string, Audience>}\n * @throws {Error}\n *\n * @private\n */\n _getExternalAudiences({ externalModules }) {\n return Object.keys(externalModules).reduce((memo, key) => {\n const clientId = externalModules[key].clientId;\n const host = externalModules[key].host;\n const hasClientId = !!clientId || clientId === null;\n const hasHost = !!host || host === null;\n\n if (!(hasClientId && hasHost)) {\n throw new Error(\n 'External modules must contain `clientId` and `host` properties'\n );\n }\n\n memo[key] = {\n clientId,\n host\n };\n\n return memo;\n }, {});\n }\n\n /**\n * Reconciles the main environment with custom environments to build up audiences for\n * internal modules.\n *\n * @param {Object.<string, Environments>} audiences All possible audiences/environments for\n * internal modules\n * @param {Object.<string, CustomAudience>} customModuleConfigs Any custom configurations for\n * internal modules\n * @param {string} env The base environment for any non-overridden modules\n *\n * @returns {Object.<string, Audience>}\n *\n * @private\n */\n _getInternalAudiences({ audiences, customModuleConfigs, env }) {\n return Object.keys(audiences).reduce((memo, key) => {\n const customModuleConfig = customModuleConfigs[key];\n const moduleAudiences = audiences[key];\n\n if (customModuleConfig) {\n memo[key] = this._getAudienceFromCustomConfig(\n customModuleConfig,\n moduleAudiences\n );\n } else {\n memo[key] = moduleAudiences[env];\n }\n\n return memo;\n }, {});\n }\n}\n\nexport default Config;\n"]}
|
package/lib/index.js
CHANGED
|
@@ -130,7 +130,7 @@ var ContxtSdk = function () {
|
|
|
130
130
|
this.config = new _config2.default(config, externalModules);
|
|
131
131
|
|
|
132
132
|
this.auth = this._createAuthSession(sessionType);
|
|
133
|
-
this.bus = new _bus2.default(this, this._createRequest('bus'));
|
|
133
|
+
this.bus = new _bus2.default(this, this._createRequest('bus'), this.config.bus);
|
|
134
134
|
this.coordinator = new _coordinator2.default(this, this._createRequest('coordinator'));
|
|
135
135
|
this.events = new _events2.default(this, this._createRequest('events'));
|
|
136
136
|
this.files = new _files2.default(this, this._createRequest('files'));
|
package/lib/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["index.js"],"names":["sessionTypes","ContxtSdk","config","externalModules","sessionType","_dynamicModuleNames","_replacedModules","Config","auth","_createAuthSession","bus","Bus","_createRequest","coordinator","Coordinator","events","Events","files","Files","iot","Iot","nionic","Nionic","_decorate","moduleName","clientId","host","module","indexOf","Error","addDynamicAudience","clearCurrentApiToken","removeDynamicAudience","filter","name","TYPES","AUTH0_WEB_AUTH","Auth0WebAuth","PASSWORD_GRANT_AUTH","PasswordGrantAuth","MACHINE_AUTH","MachineAuth","audienceName","Request","modules","Object","keys","forEach","toSnakeCase","toCamelCase"],"mappings":";;;;;;;;;AAAA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;IAAYA,Y;;AACZ;;;;;;;;;;AAEA;;;;;;;;;;;;;;;;;;;;;;AAsBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAgCMC,S;AACJ;;;;;;;AAOA,2BAAgE;AAAA,2BAAlDC,MAAkD;AAAA,QAAlDA,MAAkD,+BAAzC,EAAyC;AAAA,oCAArCC,eAAqC;AAAA,QAArCA,eAAqC,wCAAnB,EAAmB;AA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J,CAAU,8BAAV,CAAN;AAXJ;AAaD;;AAED;;;;;;;;;;;;;mCAUea,Y,EAAc;AAC3B,aAAO,IAAIC,iBAAJ,CAAY,IAAZ,EAAkBD,YAAlB,CAAP;AACD;;AAED;;;;;;;;;;;8BAQUE,O,EAAS;AAAA;;AACjBC,aAAOC,IAAP,CAAYF,OAAZ,EAAqBG,OAArB,CAA6B,UAACvB,UAAD,EAAgB;AAC3C,cAAKA,UAAL,IAAmB,IAAIoB,QAAQpB,UAAR,EAAoBG,MAAxB,CACjB,KADiB,EAEjB,MAAKf,cAAL,CAAoBY,UAApB,CAFiB,CAAnB;AAID,OALD;AAMD;;;;;;kBAGYvB,S;QACN+C,W,GAAAA,oB;QAAaC,W,GAAAA,oB","file":"index.js","sourcesContent":["import Bus from './bus';\nimport Config from './config';\nimport Coordinator from './coordinator';\nimport Events from './events';\nimport Files from './files';\nimport Iot from './iot';\nimport Nionic from './nionic';\nimport Request from './request';\nimport * as sessionTypes from './sessionTypes';\nimport { toSnakeCase, toCamelCase } from './utils/objects';\n\n/**\n * An adapter that allows the SDK to authenticate with different services and manage various tokens.\n * Can authenticate with a service like Auth0 and then with Contxt or can communicate directly\n * with Contxt. The adapter must implement required methods, but most methods are optional. Some of\n * the optional methods are documented below.\n *\n * @typedef {Object} SessionType\n * @property {function} [getCurrentAccessToken] Provides a current access token from Auth0 that is\n * used for profile information and can be used to get API token for Contxt itself\n * @property {function} getCurrentApiToken Provides a current API token that is used across\n * different Contxt services\n * @property {function} [getProfile] Provides profile information about the current user\n * @property {function} [handleAuthentication] Is called by front-end code in the Auth0 reference\n * implementation to handle getting the access token from Auth0\n * @property {function} [isAuthenticated] Tells caller if the current user is authenticated.\n * Different session types may determine if a user is authenticated in different ways.\n * @property {function} [logIn] Is used by front-end code in the Auth0 reference implementation to\n * start the sign in process\n * @property {function} [logOut] Is used by the front-end code in the Auth0 reference implementation\n * to sign the user out\n */\n\n/**\n * ContxtSdk constructor\n *\n * @example\n * import ContxtSdk from '@ndustrial/contxt-sdk';\n * import ExternalModule1 from './ExternalModule1';\n * import history from '../services/history';\n *\n * const contxtSdk = new ContxtSdk({\n * config: {\n * auth: {\n * clientId: 'Auth0 client id of the application being built',\n * customModuleConfigs: {\n * facilities: {\n * env: 'production'\n * }\n * },\n * env: 'staging',\n * onAuthenticate: (auth0WebAuthSessionInfo) => handleSuccessfulAuth(auth0WebAuthSessionInfo),\n * onRedirect: (pathname) => history.push(pathname)\n * }\n * },\n * externalModules: {\n * externalModule1: {\n * clientId: 'Auth0 client id of the external module',\n * host: 'https://www.example.com/externalModule1',\n * module: ExternalModule1\n * }\n * },\n * sessionType: 'auth0WebAuth'\n * });\n */\nclass ContxtSdk {\n /**\n * @param {UserConfig} config The user provided configuration options\n * @param {Object.<string, ExternalModule>} [externalModules] User provided external modules that\n * should be treated as first class citizens\n * @param {string} sessionType The type of auth session you wish to use (e.g. auth0WebAuth\n * or machine)\n */\n constructor({ config = {}, externalModules = {}, sessionType }) {\n this._dynamicModuleNames = [];\n this._replacedModules = {};\n\n this.config = new Config(config, externalModules);\n\n this.auth = this._createAuthSession(sessionType);\n this.bus = new Bus(this, this._createRequest('bus'));\n this.coordinator = new Coordinator(\n this,\n this._createRequest('coordinator')\n );\n this.events = new Events(this, this._createRequest('events'));\n this.files = new Files(this, this._createRequest('files'));\n this.iot = new Iot(this, this._createRequest('iot'));\n this.nionic = new Nionic(this, this._createRequest('nionic'));\n\n this._decorate(externalModules);\n }\n\n /**\n * Mounts a dynamic module into the SDK. Is used to add a module after initial\n * instatiation that will use the SDK's authentication and request methods to\n * access an ndustrial.io API\n *\n * @param {string} moduleName The name (or key) that will serve as the mount\n * point for the module in the SDK (i.e. customModule -> sdk.customModule)\n * @param {ExternalModule} externalModule\n */\n mountDynamicModule(moduleName, { clientId, host, module }) {\n if (this._dynamicModuleNames.indexOf(moduleName) > -1) {\n throw new Error(\n `An dynamic module of the name \\`${moduleName}\\` already exists. This problem can be rectified by using a different name for the new module.`\n );\n }\n\n this.config.addDynamicAudience(moduleName, { clientId, host });\n\n this._dynamicModuleNames = [...this._dynamicModuleNames, moduleName];\n\n if (this[moduleName]) {\n this._replacedModules[moduleName] = this[moduleName];\n }\n\n this[moduleName] = new module(this, this._createRequest(moduleName));\n }\n\n /**\n * Unmounts a dynamic module from the SDK\n *\n * @param {string} moduleName The name of the dynamic module to unmount\n */\n unmountDynamicModule(moduleName) {\n if (this._dynamicModuleNames.indexOf(moduleName) === -1) {\n throw new Error('There is no external module to unmount.');\n }\n\n this.auth.clearCurrentApiToken(moduleName);\n this.config.removeDynamicAudience(moduleName);\n\n this[moduleName] = this._replacedModules[moduleName];\n\n delete this._replacedModules[moduleName];\n this._dynamicModuleNames = this._dynamicModuleNames.filter(\n (name) => name !== moduleName\n );\n }\n\n /**\n * Returns a new instance of the session type requested\n *\n * @param {string} sessionType\n *\n * @returns {SessionType} sessionType\n * @throws {Error}\n *\n * @private\n */\n _createAuthSession(sessionType) {\n switch (sessionType) {\n case sessionTypes.TYPES.AUTH0_WEB_AUTH:\n return new sessionTypes.Auth0WebAuth(this);\n\n case sessionTypes.TYPES.PASSWORD_GRANT_AUTH:\n return new sessionTypes.PasswordGrantAuth(this);\n\n case sessionTypes.TYPES.MACHINE_AUTH:\n return new sessionTypes.MachineAuth(this);\n\n default:\n throw new Error('Invalid sessionType provided');\n }\n }\n\n /**\n * Returns an instance of the Request module that is tied to the requested audience\n *\n * @param {string} audienceName The audience name of the service you are trying to reach\n * (e.g. facilities or feeds)\n *\n * @returns {Object} Request module\n *\n * @private\n */\n _createRequest(audienceName) {\n return new Request(this, audienceName);\n }\n\n /**\n * Decorates custom modules onto the SDK instance so they behave as first-class citizens.\n *\n * @param {Object} modules\n * @param {function} modules.module\n *\n * @private\n */\n _decorate(modules) {\n Object.keys(modules).forEach((moduleName) => {\n this[moduleName] = new modules[moduleName].module(\n this,\n this._createRequest(moduleName)\n );\n });\n }\n}\n\nexport default ContxtSdk;\nexport { toSnakeCase, toCamelCase };\n"]}
|
|
1
|
+
{"version":3,"sources":["index.js"],"names":["sessionTypes","ContxtSdk","config","externalModules","sessionType","_dynamicModuleNames","_replacedModules","Config","auth","_createAuthSession","bus","Bus","_createRequest","coordinator","Coordinator","events","Events","files","Files","iot","Iot","nionic","Nionic","_decorate","moduleName","clientId","host","module","indexOf","Error","addDynamicAudience","clearCurrentApiToken","removeDynamicAudience","filter","name","TYPES","AUTH0_WEB_AUTH","Auth0WebAuth","PASSWORD_GRANT_AUTH","PasswordGrantAuth","MACHINE_AUTH","MachineAuth","audienceName","Request","modules","Object","keys","forEach","toSnakeCase","toCamelCase"],"mappings":";;;;;;;;;AAAA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;IAAYA,Y;;AACZ;;;;;;;;;;AAEA;;;;;;;;;;;;;;;;;;;;;;AAsBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAgCMC,S;AACJ;;;;;;;AAOA,2BAAgE;AAAA,2BAAlDC,MAAkD;AAAA,QAAlDA,MAAkD,+BAAzC,EAAyC;AAAA,oCAArCC,eAAqC;AAAA,QAArCA,eAAqC,wCAAnB,EAAmB;AAAA,QAAfC,WAAe,QAAfA,WAAe;;AAAA;;AAC9D,SAAKC,mBAAL,GAA2B,EAA3B;AACA,SAAKC,gBAAL,GAAwB,EAAxB;;AAEA,SAAKJ,MAAL,GAAc,IAAIK,gBAAJ,CAAWL,MAAX,EAAmBC,eAAnB,CAAd;;AAEA,SAAKK,IAAL,GAAY,KAAKC,kBAAL,CAAwBL,WAAxB,CAAZ;AACA,SAAKM,GAAL,GAAW,IAAIC,aAAJ,CAAQ,IAAR,EAAc,KAAKC,cAAL,CAAoB,KAApB,CAAd,EAA0C,KAAKV,MAAL,CAAYQ,GAAtD,CAAX;AACA,SAAKG,WAAL,GAAmB,IAAIC,qBAAJ,CACjB,IADiB,EAEjB,KAAKF,cAAL,CAAoB,aAApB,CAFiB,CAAnB;AAIA,SAAKG,M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","file":"index.js","sourcesContent":["import Bus from './bus';\nimport Config from './config';\nimport Coordinator from './coordinator';\nimport Events from './events';\nimport Files from './files';\nimport Iot from './iot';\nimport Nionic from './nionic';\nimport Request from './request';\nimport * as sessionTypes from './sessionTypes';\nimport { toSnakeCase, toCamelCase } from './utils/objects';\n\n/**\n * An adapter that allows the SDK to authenticate with different services and manage various tokens.\n * Can authenticate with a service like Auth0 and then with Contxt or can communicate directly\n * with Contxt. The adapter must implement required methods, but most methods are optional. Some of\n * the optional methods are documented below.\n *\n * @typedef {Object} SessionType\n * @property {function} [getCurrentAccessToken] Provides a current access token from Auth0 that is\n * used for profile information and can be used to get API token for Contxt itself\n * @property {function} getCurrentApiToken Provides a current API token that is used across\n * different Contxt services\n * @property {function} [getProfile] Provides profile information about the current user\n * @property {function} [handleAuthentication] Is called by front-end code in the Auth0 reference\n * implementation to handle getting the access token from Auth0\n * @property {function} [isAuthenticated] Tells caller if the current user is authenticated.\n * Different session types may determine if a user is authenticated in different ways.\n * @property {function} [logIn] Is used by front-end code in the Auth0 reference implementation to\n * start the sign in process\n * @property {function} [logOut] Is used by the front-end code in the Auth0 reference implementation\n * to sign the user out\n */\n\n/**\n * ContxtSdk constructor\n *\n * @example\n * import ContxtSdk from '@ndustrial/contxt-sdk';\n * import ExternalModule1 from './ExternalModule1';\n * import history from '../services/history';\n *\n * const contxtSdk = new ContxtSdk({\n * config: {\n * auth: {\n * clientId: 'Auth0 client id of the application being built',\n * customModuleConfigs: {\n * facilities: {\n * env: 'production'\n * }\n * },\n * env: 'staging',\n * onAuthenticate: (auth0WebAuthSessionInfo) => handleSuccessfulAuth(auth0WebAuthSessionInfo),\n * onRedirect: (pathname) => history.push(pathname)\n * }\n * },\n * externalModules: {\n * externalModule1: {\n * clientId: 'Auth0 client id of the external module',\n * host: 'https://www.example.com/externalModule1',\n * module: ExternalModule1\n * }\n * },\n * sessionType: 'auth0WebAuth'\n * });\n */\nclass ContxtSdk {\n /**\n * @param {UserConfig} config The user provided configuration options\n * @param {Object.<string, ExternalModule>} [externalModules] User provided external modules that\n * should be treated as first class citizens\n * @param {string} sessionType The type of auth session you wish to use (e.g. auth0WebAuth\n * or machine)\n */\n constructor({ config = {}, externalModules = {}, sessionType }) {\n this._dynamicModuleNames = [];\n this._replacedModules = {};\n\n this.config = new Config(config, externalModules);\n\n this.auth = this._createAuthSession(sessionType);\n this.bus = new Bus(this, this._createRequest('bus'), this.config.bus);\n this.coordinator = new Coordinator(\n this,\n this._createRequest('coordinator')\n );\n this.events = new Events(this, this._createRequest('events'));\n this.files = new Files(this, this._createRequest('files'));\n this.iot = new Iot(this, this._createRequest('iot'));\n this.nionic = new Nionic(this, this._createRequest('nionic'));\n\n this._decorate(externalModules);\n }\n\n /**\n * Mounts a dynamic module into the SDK. Is used to add a module after initial\n * instatiation that will use the SDK's authentication and request methods to\n * access an ndustrial.io API\n *\n * @param {string} moduleName The name (or key) that will serve as the mount\n * point for the module in the SDK (i.e. customModule -> sdk.customModule)\n * @param {ExternalModule} externalModule\n */\n mountDynamicModule(moduleName, { clientId, host, module }) {\n if (this._dynamicModuleNames.indexOf(moduleName) > -1) {\n throw new Error(\n `An dynamic module of the name \\`${moduleName}\\` already exists. This problem can be rectified by using a different name for the new module.`\n );\n }\n\n this.config.addDynamicAudience(moduleName, { clientId, host });\n\n this._dynamicModuleNames = [...this._dynamicModuleNames, moduleName];\n\n if (this[moduleName]) {\n this._replacedModules[moduleName] = this[moduleName];\n }\n\n this[moduleName] = new module(this, this._createRequest(moduleName));\n }\n\n /**\n * Unmounts a dynamic module from the SDK\n *\n * @param {string} moduleName The name of the dynamic module to unmount\n */\n unmountDynamicModule(moduleName) {\n if (this._dynamicModuleNames.indexOf(moduleName) === -1) {\n throw new Error('There is no external module to unmount.');\n }\n\n this.auth.clearCurrentApiToken(moduleName);\n this.config.removeDynamicAudience(moduleName);\n\n this[moduleName] = this._replacedModules[moduleName];\n\n delete this._replacedModules[moduleName];\n this._dynamicModuleNames = this._dynamicModuleNames.filter(\n (name) => name !== moduleName\n );\n }\n\n /**\n * Returns a new instance of the session type requested\n *\n * @param {string} sessionType\n *\n * @returns {SessionType} sessionType\n * @throws {Error}\n *\n * @private\n */\n _createAuthSession(sessionType) {\n switch (sessionType) {\n case sessionTypes.TYPES.AUTH0_WEB_AUTH:\n return new sessionTypes.Auth0WebAuth(this);\n\n case sessionTypes.TYPES.PASSWORD_GRANT_AUTH:\n return new sessionTypes.PasswordGrantAuth(this);\n\n case sessionTypes.TYPES.MACHINE_AUTH:\n return new sessionTypes.MachineAuth(this);\n\n default:\n throw new Error('Invalid sessionType provided');\n }\n }\n\n /**\n * Returns an instance of the Request module that is tied to the requested audience\n *\n * @param {string} audienceName The audience name of the service you are trying to reach\n * (e.g. facilities or feeds)\n *\n * @returns {Object} Request module\n *\n * @private\n */\n _createRequest(audienceName) {\n return new Request(this, audienceName);\n }\n\n /**\n * Decorates custom modules onto the SDK instance so they behave as first-class citizens.\n *\n * @param {Object} modules\n * @param {function} modules.module\n *\n * @private\n */\n _decorate(modules) {\n Object.keys(modules).forEach((moduleName) => {\n this[moduleName] = new modules[moduleName].module(\n this,\n this._createRequest(moduleName)\n );\n });\n }\n}\n\nexport default ContxtSdk;\nexport { toSnakeCase, toCamelCase };\n"]}
|
package/package.json
CHANGED
package/src/bus/index.js
CHANGED
|
@@ -35,6 +35,20 @@ import WebSocketConnection from './webSocketConnection';
|
|
|
35
35
|
* @property {WebSocket} _webSocket The raw WebSocket connection to the message bus
|
|
36
36
|
*/
|
|
37
37
|
|
|
38
|
+
/**
|
|
39
|
+
* Configuration object for the Bus
|
|
40
|
+
*
|
|
41
|
+
* @typedef {Object} BusConfig
|
|
42
|
+
* @property {boolean} autoAcknowledge
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* @type {BusConfig}
|
|
47
|
+
*/
|
|
48
|
+
const defaultBusConfig = {
|
|
49
|
+
autoAcknowledge: true
|
|
50
|
+
};
|
|
51
|
+
|
|
38
52
|
/**
|
|
39
53
|
* Module that provides access to the message bus. This is for Node
|
|
40
54
|
* environments. Documentation for browser environments is found under
|
|
@@ -46,8 +60,9 @@ class Bus {
|
|
|
46
60
|
/**
|
|
47
61
|
* @param {Object} sdk An instance of the SDK so the module can communicate with other modules
|
|
48
62
|
* @param {Object} request An instance of the request module tied to this module's audience.
|
|
63
|
+
* @param {BusConfig} config A config object for the Bus instance
|
|
49
64
|
*/
|
|
50
|
-
constructor(sdk, request) {
|
|
65
|
+
constructor(sdk, request, config) {
|
|
51
66
|
const baseUrl = `${sdk.config.audiences.bus.host}`;
|
|
52
67
|
const baseWebSocketUrl = `${sdk.config.audiences.bus.webSocket}`;
|
|
53
68
|
|
|
@@ -56,6 +71,7 @@ class Bus {
|
|
|
56
71
|
this._request = request;
|
|
57
72
|
this._sdk = sdk;
|
|
58
73
|
this._webSockets = {};
|
|
74
|
+
this._config = Object.assign({}, defaultBusConfig, config);
|
|
59
75
|
|
|
60
76
|
this.channels = new Channels(sdk, request, baseUrl);
|
|
61
77
|
}
|
|
@@ -101,7 +117,8 @@ class Bus {
|
|
|
101
117
|
ws.onopen = (event) => {
|
|
102
118
|
this._webSockets[organizationId] = new WebSocketConnection(
|
|
103
119
|
ws,
|
|
104
|
-
organizationId
|
|
120
|
+
organizationId,
|
|
121
|
+
this._config.autoAcknowledge
|
|
105
122
|
);
|
|
106
123
|
|
|
107
124
|
resolve(this._webSockets[organizationId]);
|
package/src/bus/index.spec.js
CHANGED
|
@@ -290,6 +290,48 @@ describe('Bus', function() {
|
|
|
290
290
|
);
|
|
291
291
|
}
|
|
292
292
|
);
|
|
293
|
+
|
|
294
|
+
context('when providing custom config', function() {
|
|
295
|
+
let bus;
|
|
296
|
+
let expectedApiToken;
|
|
297
|
+
let promise;
|
|
298
|
+
let sdk;
|
|
299
|
+
let server;
|
|
300
|
+
let busConfig
|
|
301
|
+
|
|
302
|
+
beforeEach(function() {
|
|
303
|
+
expectedApiToken = faker.internet.password();
|
|
304
|
+
|
|
305
|
+
sdk = {
|
|
306
|
+
...baseSdk,
|
|
307
|
+
auth: {
|
|
308
|
+
...baseSdk.auth,
|
|
309
|
+
getCurrentApiToken: sinon.stub().resolves(expectedApiToken)
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
|
|
313
|
+
server = new Server(
|
|
314
|
+
`${expectedHost}/organizations/${expectedOrganization.id}/stream`
|
|
315
|
+
);
|
|
316
|
+
|
|
317
|
+
busConfig = { autoAcknowledge: false };
|
|
318
|
+
bus = new Bus(sdk, baseRequest, busConfig);
|
|
319
|
+
bus._baseWebSocketUrl = expectedHost;
|
|
320
|
+
|
|
321
|
+
promise = bus.connect(expectedOrganization.id);
|
|
322
|
+
});
|
|
323
|
+
|
|
324
|
+
afterEach(function() {
|
|
325
|
+
server.stop();
|
|
326
|
+
});
|
|
327
|
+
|
|
328
|
+
it('passes the auto-acknowledge flag to the WebSocketConnection', function() {
|
|
329
|
+
return promise.then((resolvedWebSocket) => {
|
|
330
|
+
expect(resolvedWebSocket._autoAck).to.equal(busConfig.autoAcknowledge);
|
|
331
|
+
});
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
});
|
|
293
335
|
});
|
|
294
336
|
|
|
295
337
|
describe('getWebSocketConnection', function() {
|
|
@@ -29,11 +29,13 @@ class WebSocketConnection {
|
|
|
29
29
|
/**
|
|
30
30
|
* @param {WebSocket} webSocket A WebSocket connection to the message bus
|
|
31
31
|
* @param {string} organizationId UUID corresponding with an organization
|
|
32
|
+
* @param {boolean} autoAcknowledge Whether the messages should be ACK'd explicitly or not
|
|
32
33
|
*/
|
|
33
|
-
constructor(webSocket, organizationId) {
|
|
34
|
+
constructor(webSocket, organizationId, autoAcknowledge = true) {
|
|
34
35
|
this._messageHandlers = {};
|
|
35
36
|
this._organizationId = organizationId;
|
|
36
37
|
this._webSocket = webSocket;
|
|
38
|
+
this._autoAck = autoAcknowledge;
|
|
37
39
|
|
|
38
40
|
if (this._webSocket) {
|
|
39
41
|
this._webSocket.onerror = this._onError;
|
|
@@ -282,20 +284,24 @@ class WebSocketConnection {
|
|
|
282
284
|
|
|
283
285
|
if (error) {
|
|
284
286
|
return resolve(errorHandler(error));
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
try {
|
|
290
|
+
const ack = once(() => {
|
|
291
|
+
return this._acknowledge(result.id);
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
return resolve(
|
|
295
|
+
Promise.resolve(handler(result.body, ack)).then((res) => {
|
|
296
|
+
if (this._autoAck) {
|
|
293
297
|
return ack().then(() => res);
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
return res;
|
|
301
|
+
})
|
|
302
|
+
);
|
|
303
|
+
} catch (throwable) {
|
|
304
|
+
return reject(throwable);
|
|
299
305
|
}
|
|
300
306
|
});
|
|
301
307
|
};
|
|
@@ -1755,6 +1755,51 @@ describe('Bus/WebSocketConnection', function() {
|
|
|
1755
1755
|
});
|
|
1756
1756
|
});
|
|
1757
1757
|
});
|
|
1758
|
+
|
|
1759
|
+
context('and the client does not auto-ack', function() {
|
|
1760
|
+
let errorHandler;
|
|
1761
|
+
|
|
1762
|
+
beforeEach(function() {
|
|
1763
|
+
handler = sinon.stub().returns(null);
|
|
1764
|
+
errorHandler = sinon.stub().returns(null);
|
|
1765
|
+
|
|
1766
|
+
ws = new WebSocketConnection(
|
|
1767
|
+
expectedWebSocket,
|
|
1768
|
+
expectedOrganization.id,
|
|
1769
|
+
false
|
|
1770
|
+
);
|
|
1771
|
+
|
|
1772
|
+
promise = ws.subscribe(
|
|
1773
|
+
serviceId,
|
|
1774
|
+
channel,
|
|
1775
|
+
group,
|
|
1776
|
+
handler,
|
|
1777
|
+
errorHandler
|
|
1778
|
+
);
|
|
1779
|
+
|
|
1780
|
+
jsonRpcId = Object.keys(ws._messageHandlers)[0];
|
|
1781
|
+
|
|
1782
|
+
ws._messageHandlers[jsonRpcId]({
|
|
1783
|
+
result: {
|
|
1784
|
+
subscription
|
|
1785
|
+
}
|
|
1786
|
+
});
|
|
1787
|
+
});
|
|
1788
|
+
|
|
1789
|
+
it('doesn\'t call the ack function', function() {
|
|
1790
|
+
return promise
|
|
1791
|
+
.then(() => {
|
|
1792
|
+
return ws._messageHandlers[subscription]({
|
|
1793
|
+
result: {
|
|
1794
|
+
error: message
|
|
1795
|
+
}
|
|
1796
|
+
});
|
|
1797
|
+
})
|
|
1798
|
+
.catch(() => {
|
|
1799
|
+
expect(acknowledge).to.not.be.called;
|
|
1800
|
+
});
|
|
1801
|
+
});
|
|
1802
|
+
});
|
|
1758
1803
|
});
|
|
1759
1804
|
|
|
1760
1805
|
context('without a group', function() {
|
package/src/config/defaults.js
CHANGED
package/src/config/index.js
CHANGED
package/src/index.js
CHANGED
|
@@ -78,7 +78,7 @@ class ContxtSdk {
|
|
|
78
78
|
this.config = new Config(config, externalModules);
|
|
79
79
|
|
|
80
80
|
this.auth = this._createAuthSession(sessionType);
|
|
81
|
-
this.bus = new Bus(this, this._createRequest('bus'));
|
|
81
|
+
this.bus = new Bus(this, this._createRequest('bus'), this.config.bus);
|
|
82
82
|
this.coordinator = new Coordinator(
|
|
83
83
|
this,
|
|
84
84
|
this._createRequest('coordinator')
|
package/src/index.spec.js
CHANGED
|
@@ -76,6 +76,15 @@ describe('ContxtSdk', function() {
|
|
|
76
76
|
expect(contxtSdk.bus).to.be.an.instanceof(Bus);
|
|
77
77
|
});
|
|
78
78
|
|
|
79
|
+
it('passes bus config to the bus constructor', function() {
|
|
80
|
+
contxtSdk = new ContxtSdk({
|
|
81
|
+
config: {...baseConfig, bus: {autoAcknowledge: false}},
|
|
82
|
+
externalModules: expectedExternalModules,
|
|
83
|
+
sessionType: expectedAuthSessionType
|
|
84
|
+
});
|
|
85
|
+
expect(contxtSdk.bus._config).to.deep.equal({autoAcknowledge: false});
|
|
86
|
+
});
|
|
87
|
+
|
|
79
88
|
it('sets an instance of Config', function() {
|
|
80
89
|
expect(contxtSdk.config).to.be.an.instanceof(Config);
|
|
81
90
|
});
|