├── .babelrc ├── .eslintrc ├── .gitignore ├── .prettierrc.json ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE ├── README.md ├── dist └── amazon-connect-task.js ├── package-lock.json ├── package.json ├── src ├── constants.js ├── core │ ├── agentApis.js │ ├── agentApis.spec.js │ ├── connectionHelpers │ │ └── LpcConnectionHelper.js │ ├── taskController.js │ ├── taskSession.js │ └── taskSession.spec.js ├── index.js └── testUtils │ └── mockConnect.js └── webpack.config.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | "@babel/preset-env" 4 | ] 5 | } -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "rules": { 3 | "no-console": "off", 4 | "eqeqeq": ["error", "always"], 5 | "semi": ["error", "always"] 6 | }, 7 | "env": { 8 | "es6": true, 9 | "browser": true, 10 | "node": true, 11 | "jest": true 12 | }, 13 | "extends": [ 14 | "eslint:recommended", 15 | "prettier" 16 | ], 17 | "globals": { 18 | "module": true, 19 | "require": true, 20 | "process": true, 21 | "connect": true, 22 | "AWS": true 23 | }, 24 | "parserOptions": { 25 | "ecmaVersion": 2017, 26 | "sourceType": "module" 27 | } 28 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules 2 | npm-debug.log* 3 | coverage 4 | .DS_Store 5 | build 6 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 180, 3 | "singleQuote": true 4 | } 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # CHANGELOG.md 2 | 3 | ## 2.0.0 4 | Added functions: 5 | * `agent.updateContact` method to update a task contact created from a template. 6 | * `agent.listTaskTemplates` method to load a list of task templates that belong to a connect instance. 7 | * `agent.getTaskTemplate` method to load a template data, including fields, default values and constraints. 8 | 9 | Other changes: 10 | * `agent.createTask` method supports new parameteres and allows to create templated tasks. See README.md for more details. 11 | * `connect.ReferenceType` new reference types supported. 12 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *main* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## AmazonConnectTaskJS 2 | 3 | # About 4 | The Amazon Connect Task javascript library (TaskJS) gives you the power to handle task contacts when used together with [Amazon Connect Streams](https://github.com/aws/amazon-connect-streams). 5 | 6 | # Learn More 7 | To learn more about Amazon Connect and its capabilities, please check out 8 | the [Amazon Connect User Guide](https://docs.aws.amazon.com/connect/latest/userguide/). 9 | 10 | # Getting Started 11 | 12 | ### Using TaskJS from Github 13 | ``` 14 | $ git clone https://github.com/amazon-connect/amazon-connect-taskjs 15 | ``` 16 | 17 | ### Including TaskJS 18 | 19 | [Amazon Connect Streams](https://github.com/aws/amazon-connect-streams) is required to use TaskJS. Ensure you import TaskJS after Streams. 20 | 21 | TaskJs v2.0 requires Streams v2.2 or later. 22 | 23 | # Building 24 | 1. Install latest LTS version of [NodeJS](https://nodejs.org) 25 | 2. Checkout this package into workspace and navigate to root folder 26 | 3. `npm install` 27 | 4. To build (non-minified): 28 | 1. `npm run devo` for a non-minified build. 29 | 2. Find build artifacts in **dist** directory. 30 | 5. To build (minified): 31 | 1. `npm run release` for a minified build. 32 | 2. Find build artifacts in **dist** directory. 33 | 6. To run unit tests: 34 | 1. `npm run test` 35 | 7. To clean node_modules: 36 | 1. `npm run clean` 37 | 8. To make webpack watch all files: 38 | 1. `npm run watch` 39 | 40 | Find build artifacts in **dist** directory - This will generate a file called `amazon-connect-task.js` - this is the full Connect TaskJS API which you will want to include in your page. 41 | 42 | 43 | # Usage: 44 | 45 | TaskJS provides a `taskSession` instance for each task contact. You can access the `taskSession` by calling the `getMediaController` method on a `taskConnection`. `getMediaController` returns a promise that resolves with a `taskSession` instance. 46 | 47 | For example: 48 | 49 | ```js 50 | taskConnection.getMediaController().then((taskSession) => { /* ... */ }); 51 | ``` 52 | 53 | ## Event Handlers 54 | 55 | Each of the following event handlers will pass a message object to the callback function containing the following fields: 56 | 57 | * `AbsoluteTime`: UTC timestamp of when the event occurred. 58 | * `ContentType`: One of the following strings depending on the event: 59 | * `application/vnd.amazonaws.connect.event.transfer.initiated` 60 | * `application/vnd.amazonaws.connect.event.transfer.succeeded` 61 | * `application/vnd.amazonaws.connect.event.transfer.failed` 62 | * ` application/vnd.amazonaws.connect.event.expire.warning` 63 | * `application/vnd.amazonaws.connect.event.expire.complete` 64 | * `Id`: The contact ID 65 | * `InitialContactId`: The [initial contact id](https://github.com/amazon-connect/amazon-connect-streams/blob/master/Documentation.md#contactgetoriginalcontactid--contactgetinitialcontactid). 66 | 67 | ### `taskSession.onTransferInitiated` 68 | 69 | Subscribe a method to be invoked when the server has initiated the task transfer. 70 | 71 | ```js 72 | taskSession.onTransferInitiated((message) => console.log("Transfer has initiated")) 73 | ``` 74 | 75 | ### `taskSession.onTransferSucceeded` 76 | 77 | Subscribe a method to be invoked when the task transfer has succeeded. 78 | 79 | ```js 80 | taskSession.onTransferSucceeded((message) => console.log("Transfer has succeeded")) 81 | ``` 82 | 83 | ### `taskSession.onTransferFailed` 84 | 85 | Subscribe a method to be invoked when the task transfer has failed. 86 | 87 | ```js 88 | taskSession.onTransferFailed((message) => console.log("Transfer has failed")) 89 | ``` 90 | 91 | ### `taskSession.onTaskExpiring` 92 | 93 | Subscribe a method to be invoked two hours before the task expires. 94 | 95 | ```js 96 | taskSession.onTaskExpiring((message) => console.log("Task will expire in two hours")) 97 | ``` 98 | 99 | ### `taskSession.onTaskExpired` 100 | 101 | Subscribe a method to be invoked when the task has expired. 102 | 103 | ```js 104 | taskSession.onTaskExpired((message) => console.log("Task has expired")) 105 | ``` 106 | 107 | ### `taskSession.onMessage` 108 | 109 | Subscribe a method to be invoked when any one of the above events has occurred. 110 | 111 | ```js 112 | taskSession.onMessage((message) => console.log("The following event has occurred:", message.ContentType)) 113 | ``` 114 | 115 | ## Methods 116 | 117 | ### `agent.createTask()` 118 | 119 | Create a new task. 120 | 121 | ```js 122 | const newTask = { 123 | name: "string", //required, max len: 512 124 | description: "string", //optional, max len: 4096 125 | endpoint: endpointObject, //required for non templated tasks, can be retrieved via `agent.getEndpoints()`. Agent and queue endpoints supported. 126 | taskTemplateId: "string", //required for templated tasks, ID of the template the task is created from. Template should belong to connect instance 127 | previousContactId: "string", //optional, the previous contact ID for a linked task 128 | references: { //optional. Only URL references are supported for non templated tasks 129 | "reference name 1": { // string, max len: 4096 130 | type: "URL" //required, string, one of connect.ReferenceType types, 131 | value: "https://www.amazon.com" //required, string, max len: 4096 132 | }, 133 | "reference name 2": { // string, max len: 4096 134 | type: "EMAIL" //required, string, one of connect.ReferenceType types 135 | value: "example@abc.com" //required, string, max len: 4096 136 | }, 137 | "reference name 3": { // string, max len: 4096 138 | type: "NUMBER" //required, one of connect.ReferenceType types 139 | value: 1000 //required, number 140 | }, 141 | "reference name 4": { // string, max len: 4096 142 | type: "DATE", //required, string, one of connect.ReferenceType types 143 | value: 1649961230 //required, number 144 | }, 145 | "reference name 5": { // string, max len: 4096 146 | type: "STRING" //required, string, one of connect.ReferenceType types 147 | value: "example@abc.com" //required, string, max len: 4096 148 | } 149 | }, 150 | scheduledTime: "number" //optional, UTC timestamp in seconds when the task should be delivered. 151 | }; 152 | 153 | agent.createTask(newTask, { 154 | success: function(data) { console.log("Created a task with contact id: ", data.contactId) }, 155 | failure: function(err) { /* ... */ } 156 | }); 157 | ``` 158 | 159 | ### `agent.updateContact()` 160 | 161 | Update a task contact created from a template. 162 | 163 | ```js 164 | const updatedTaskData = { 165 | contactId: "string", // required, task contact identifier 166 | name: "string", // optional, task name 167 | description: "string", // optional, task description 168 | references: { //optional, used to specify updated template fields 169 | "reference name": { // string 170 | type: "NUMBER" //required, one of connect.ReferenceType types 171 | value: 1001 //required, number 172 | } 173 | //see more examples in agent.createTask() description 174 | } 175 | }; 176 | 177 | agent.updateContact(updatedTaskData, { 178 | success: function() { console.log("The task updated successfully") }, 179 | failure: function(err) { /* ... */ } 180 | }); 181 | 182 | ``` 183 | 184 | ### `agent.listTaskTemplates()` 185 | 186 | Load a list of task templates that belong to a connect instance 187 | 188 | ```js 189 | 190 | const queryParams = {// required 191 | status: 'active', //optional, string, can be either 'active' or 'inactive' 192 | maxResults: 50 //optional, number, max value of 100 193 | }; 194 | 195 | agent.listTaskTemplates(queryParams, { 196 | success: function(data) { console.log("List of task templates loaded successfully", data) }, 197 | failure: function(err) { /* ... */ } 198 | }); 199 | 200 | ``` 201 | 202 | 203 | ### `agent.getTaskTemplate()` 204 | 205 | Load a template data, including fields, default values and constraints 206 | 207 | ```js 208 | 209 | const templateParams = {// required 210 | id: 'string', //required, string, template ID, template should belong to connect instance 211 | version: 'string' //optional, string, task template version 212 | }; 213 | 214 | agent.getTaskTemplate(templateParams, { 215 | success: function(data) { console.log("Template data loaded successfully", templateParams.id, data) }, 216 | failure: function(err) { /* ... */ } 217 | }); 218 | 219 | ``` 220 | 221 | 222 | ## Enumerations 223 | 224 | ### `connect.ReferenceType` 225 | This enumeration lists the different reference types for a task. Currently supported types: URL, EMAIL, NUMBER, STRING, DATE. 226 | 227 | * `ReferenceType.URL`: A URL reference. 228 | 229 | ## Security 230 | 231 | See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information. 232 | 233 | ## License 234 | 235 | This project is licensed under the Apache-2.0 License. 236 | -------------------------------------------------------------------------------- /dist/amazon-connect-task.js: -------------------------------------------------------------------------------- 1 | (()=>{"use strict";var t={};t.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}();const n="NeverStarted",e="Ended",s="ConnectionLost",o="ConnectionGained",c="Ended",i="IncomingMessage";class a{constructor(t,n,e){a.baseInstance||(a.baseInstance=new r(e)),this.contactId=t,this.initialContactId=n,this.status=null,this.eventBus=new connect.EventBus,this.subscriptions=[a.baseInstance.onEnded(this.handleEnded.bind(this)),a.baseInstance.onConnectionGain(this.handleConnectionGain.bind(this)),a.baseInstance.onConnectionLost(this.handleConnectionLost.bind(this)),a.baseInstance.onMessage(this.handleMessage.bind(this))]}start(){return a.baseInstance.start()}end(){this.eventBus.unsubscribeAll(),this.subscriptions.forEach((t=>t.unsubscribe())),this.status=e}getStatus(){return this.status||a.baseInstance.getStatus()}onEnded(t){return this.eventBus.subscribe(c,t)}handleEnded(){this.eventBus.trigger(c,{})}onConnectionGain(t){return this.eventBus.subscribe(o,t)}handleConnectionGain(){this.eventBus.trigger(o,{})}onConnectionLost(t){return this.eventBus.subscribe(s,t)}handleConnectionLost(){this.eventBus.trigger(s,{})}onMessage(t){return this.eventBus.subscribe(i,t)}handleMessage(t){t.InitialContactId!==this.initialContactId&&t.ContactId!==this.contactId||this.eventBus.trigger(i,t)}}a.baseInstance=null;class r{constructor(t){this.status=n,this.eventBus=new connect.EventBus,this.initWebsocketManager(t)}initWebsocketManager(t){this.websocketManager=t,this.websocketManager.subscribeTopics(["aws/task"]),this.subscriptions=[this.websocketManager.onMessage("aws/task",this.handleMessage.bind(this)),this.websocketManager.onConnectionGain(this.handleConnectionGain.bind(this)),this.websocketManager.onConnectionLost(this.handleConnectionLost.bind(this)),this.websocketManager.onInitFailure(this.handleEnded.bind(this))]}start(){return this.status===n&&(this.status="Starting"),Promise.resolve()}onEnded(t){return this.eventBus.subscribe(c,t)}handleEnded(){this.status=e,this.eventBus.trigger(c,{})}onConnectionGain(t){return this.eventBus.subscribe(o,t)}handleConnectionGain(){this.status="Connected",this.eventBus.trigger(o,{})}onConnectionLost(t){return this.eventBus.subscribe(s,t)}handleConnectionLost(){this.status="ConnectionLost",this.eventBus.trigger(s,{})}onMessage(t){return this.eventBus.subscribe(i,t)}handleMessage(t){let n;try{n=JSON.parse(t.content),this.eventBus.trigger(i,n)}catch(n){connect.getLog().error("Wrong message format: %s",t)}}getStatus(){return this.status}}const l=a,h="INCOMING_MESSAGE",u="TRANSFER_FAILED",d="TRANSFER_SUCCEEDED",g="TRANSFER_INITIATED",b="CONNECTION_ESTABLISHED",p="CONNECTION_BROKEN",C="TASK_EXPIRING",T="TASK_EXPIRED",E={"application/vnd.amazonaws.connect.event.transfer.initiated":g,"application/vnd.amazonaws.connect.event.transfer.succeeded":d,"application/vnd.amazonaws.connect.event.transfer.failed":u,"application/vnd.amazonaws.connect.event.expire.warning":C,"application/vnd.amazonaws.connect.event.expire.complete":T};class I{constructor(t){this.pubsub=new connect.EventBus,this.initialContactId=t.initialContactId,this.contactId=t.contactId,this.websocketManager=t.websocketManager}subscribe(t,n){this.pubsub.subscribe(t,n),connect.getLog().info(connect.LogComponent.TASK,"Subscribed successfully to eventName: %s",t)}connect(){return this._initConnectionHelper().then(this._onConnectSuccess.bind(this),this._onConnectFailure.bind(this))}getTaskDetails(){return{initialContactId:this.initialContactId,contactId:this.contactId}}unsubscribeAll(){this.pubsub.unsubscribeAll(),this.connectionHelper.end()}_triggerEvent(t,n){connect.getLog().debug(connect.LogComponent.TASK,"Triggering event for subscribers: %s",t).withObject({data:n,taskDetails:this.getTaskDetails()}),this.pubsub.trigger(t,n)}_onConnectSuccess(t){connect.getLog().info(connect.LogComponent.TASK,"Connect successful!");const n={_debug:t,connectSuccess:!0,connectCalled:!0};return this._triggerEvent(b,n),n}_onConnectFailure(t){const n={_debug:t,connectSuccess:!1,connectCalled:!0,metadata:this.sessionMetadata};return connect.getLog().error(connect.LogComponent.TASK,"Connect Failed").withException(n),Promise.reject(n)}_initConnectionHelper(){return this.connectionHelper=new l(this.contactId,this.initialContactId,this.websocketManager),this.connectionHelper.onEnded(this._handleEndedConnection.bind(this)),this.connectionHelper.onConnectionLost(this._handleLostConnection.bind(this)),this.connectionHelper.onConnectionGain(this._handleGainedConnection.bind(this)),this.connectionHelper.onMessage(this._handleIncomingMessage.bind(this)),this.connectionHelper.start()}_handleEndedConnection(t){this._triggerEvent(p,t)}_handleGainedConnection(t){this._triggerEvent(b,t)}_handleLostConnection(t){this._triggerEvent("CONNECTION_LOST",t)}_handleIncomingMessage(t){const n=t.ContentType;E[n]&&this._triggerEvent(E[n],t),this._triggerEvent(h,t)}}class v{constructor(t){this.controller=t}onMessage(t){this.controller.subscribe(h,t)}onTransferSucceeded(t){this.controller.subscribe(d,t)}onTransferFailed(t){this.controller.subscribe(u,t)}onTransferInitiated(t){this.controller.subscribe(g,t)}onTaskExpiring(t){this.controller.subscribe(C,t)}onTaskExpired(t){this.controller.subscribe(T,t)}onConnectionBroken(t){this.controller.subscribe(p,t)}onConnectionEstablished(t){this.controller.subscribe(b,t)}connect(t){return this.controller.connect(t)}cleanUp(){this.controller.unsubscribeAll()}}const A={create:t=>{const n=new I(t);return new v(n)}},k=connect.makeEnum(["URL","EMAIL","NUMBER","STRING","DATE"]);function m(t){Object.keys(t).forEach((n=>{const e=(s=n).charAt(0).toUpperCase()+s.slice(1);var s;e!==n&&(t[e]=t[n],delete t[n]),"References"===e&&Object.values(t[e]).forEach((t=>m(t)))}))}t.g.connect=t.g.connect||{},connect.TaskSession=A,connect.Agent.prototype.createTask||(connect.Agent.prototype.createTask=function(t,n){connect.assertNotNull(t,"Task contact object"),connect.assertNotNull(t.name,"Task name");var e=connect.core.getClient();t.taskTemplateId?(t.endpoint&&(t.quickConnectId=t.endpoint.endpointARN.split("/").pop(),delete t.endpoint),m(t),e.call(connect.TaskTemplatesClientMethods.CREATE_TEMPLATED_TASK,t,n)):(connect.assertNotNull(t.endpoint,"Task endpoint"),t.idempotencyToken=AWS.util.uuid.v4(),delete t.endpoint.endpointId,e.call(connect.ClientMethods.CREATE_TASK_CONTACT,t,n))}),connect.Agent.prototype.getTaskTemplate||(connect.Agent.prototype.getTaskTemplate=function(t,n){connect.assertNotNull(t,"Task template params"),connect.assertNotNull(t.id,"Task template id");var e=connect.core.getClient(),s=connect.core.getAgentDataProvider().getInstanceId();e.call(connect.TaskTemplatesClientMethods.GET_TASK_TEMPLATE,{instanceId:s,templateParams:t},n)}),connect.Agent.prototype.listTaskTemplates||(connect.Agent.prototype.listTaskTemplates=function(t,n){connect.assertNotNull(t,"Query params for listTaskTemplates");var e=connect.core.getClient(),s=connect.core.getAgentDataProvider().getInstanceId();e.call(connect.TaskTemplatesClientMethods.LIST_TASK_TEMPLATES,{instanceId:s,queryParams:t},n)}),connect.Agent.prototype.updateContact||(connect.Agent.prototype.updateContact=function(t,n){connect.assertNotNull(t,"Update for templated task"),connect.assertNotNull(t.contactId,"Task contact id");var e=connect.core.getClient();m(t),e.call(connect.TaskTemplatesClientMethods.UPDATE_CONTACT,t,n)}),connect.ReferenceType=k})(); -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "amazon-connect-taskjs", 3 | "version": "2.0.0", 4 | "author": "Amazon Web Services", 5 | "license": "Apache-2.0", 6 | "description": "Provides task support to AmazonConnect customers", 7 | "main": "dist/amazon-connect-task.js", 8 | "engines": { 9 | "node": ">=12.0.0" 10 | }, 11 | "directories": { 12 | "lib": "./dist" 13 | }, 14 | "repository": { 15 | "type": "git", 16 | "url": "git+https://github.com/amazon-connect/amazon-connect-taskjs.git" 17 | }, 18 | "scripts": { 19 | "test": "jest", 20 | "release": "jest && webpack --mode=production", 21 | "devo": "jest && webpack --mode=development", 22 | "watch": "webpack --watch", 23 | "dev": "webpack --mode=development && webpack --watch", 24 | "clean": "rm -rf build/ node_modules build", 25 | "release-watch": "npm run release && npm run watch" 26 | }, 27 | "browserslist": [ 28 | "Firefox ESR", 29 | "firefox > 67", 30 | "chrome > 62", 31 | "edge > 78", 32 | "opera > 49" 33 | ], 34 | "jest": { 35 | "collectCoverage": true, 36 | "coverageReporters": [ 37 | "json", 38 | "text", 39 | "cobertura", 40 | "lcov" 41 | ], 42 | "coverageDirectory": "build/jest-coverage" 43 | }, 44 | "devDependencies": { 45 | "@babel/core": "^7.11.6", 46 | "@babel/preset-env": "^7.11.5", 47 | "babel-loader": "^8.1.0", 48 | "eslint": "^7.9.0", 49 | "eslint-config-prettier": "^6.11.0", 50 | "eslint-webpack-plugin": "^2.1.0", 51 | "jest": "^26.4.2", 52 | "ssri": ">=8.0.1", 53 | "webpack": "^5.73.0", 54 | "webpack-cli": "^3.3.12" 55 | }, 56 | "npm-pretty-much": { 57 | "runRelease": "always" 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/constants.js: -------------------------------------------------------------------------------- 1 | export const TASK_EVENTS = { 2 | INCOMING_MESSAGE: 'INCOMING_MESSAGE', 3 | TRANSFER_FAILED: 'TRANSFER_FAILED', 4 | TRANSFER_SUCCEEDED: 'TRANSFER_SUCCEEDED', 5 | TRANSFER_INITIATED: 'TRANSFER_INITIATED', 6 | CONNECTION_ESTABLISHED: "CONNECTION_ESTABLISHED", 7 | CONNECTION_LOST: "CONNECTION_LOST", 8 | CONNECTION_BROKEN: "CONNECTION_BROKEN", 9 | CONNECTION_ACK: "CONNECTION_ACK", 10 | TASK_EXPIRING: "TASK_EXPIRING", 11 | TASK_EXPIRED: "TASK_EXPIRED" 12 | }; 13 | 14 | export const CONTENT_TYPE = { 15 | transferSucceeded: 'application/vnd.amazonaws.connect.event.transfer.succeeded', 16 | transferFailed: 'application/vnd.amazonaws.connect.event.transfer.failed', 17 | transferInitiated: 'application/vnd.amazonaws.connect.event.transfer.initiated', 18 | taskExpiring: 'application/vnd.amazonaws.connect.event.expire.warning', 19 | taskExpired: 'application/vnd.amazonaws.connect.event.expire.complete', 20 | }; 21 | 22 | export const CONTENT_TYPE_TO_EVENT_MAP = { 23 | 'application/vnd.amazonaws.connect.event.transfer.initiated': TASK_EVENTS.TRANSFER_INITIATED, 24 | 'application/vnd.amazonaws.connect.event.transfer.succeeded': TASK_EVENTS.TRANSFER_SUCCEEDED, 25 | 'application/vnd.amazonaws.connect.event.transfer.failed': TASK_EVENTS.TRANSFER_FAILED, 26 | 'application/vnd.amazonaws.connect.event.expire.warning': TASK_EVENTS.TASK_EXPIRING, 27 | 'application/vnd.amazonaws.connect.event.expire.complete': TASK_EVENTS.TASK_EXPIRED 28 | }; 29 | 30 | export const EVENT = 'EVENT'; 31 | export const MESSAGE = 'MESSAGE'; 32 | -------------------------------------------------------------------------------- /src/core/agentApis.js: -------------------------------------------------------------------------------- 1 | const ReferenceType = connect.makeEnum([ 2 | 'URL', 3 | 'EMAIL', 4 | 'NUMBER', 5 | 'STRING', 6 | 'DATE' 7 | ]); 8 | 9 | function capitalizeFirstLetter(string) { 10 | return string.charAt(0).toUpperCase() + string.slice(1); 11 | } 12 | 13 | function normalizeTaskTemplateAPIParams(params) { 14 | Object.keys(params).forEach(key => { 15 | const uppercaseKey = capitalizeFirstLetter(key); 16 | if (uppercaseKey !== key) { 17 | params[uppercaseKey] = params[key]; 18 | delete params[key]; 19 | } 20 | if (uppercaseKey === 'References') { 21 | Object.values(params[uppercaseKey]).forEach(obj => normalizeTaskTemplateAPIParams(obj)); 22 | } 23 | }); 24 | } 25 | 26 | const createTask = function(taskContact, callbacks) { 27 | connect.assertNotNull(taskContact, 'Task contact object'); 28 | connect.assertNotNull(taskContact.name, 'Task name'); 29 | var client = connect.core.getClient(); 30 | if (taskContact.taskTemplateId) { 31 | if (taskContact.endpoint) { 32 | taskContact.quickConnectId = taskContact.endpoint.endpointARN.split('/').pop(); 33 | delete taskContact.endpoint; 34 | } 35 | normalizeTaskTemplateAPIParams(taskContact); 36 | client.call(connect.TaskTemplatesClientMethods.CREATE_TEMPLATED_TASK, taskContact, callbacks); 37 | } else { 38 | connect.assertNotNull(taskContact.endpoint, 'Task endpoint'); 39 | taskContact.idempotencyToken = AWS.util.uuid.v4(); 40 | delete taskContact.endpoint.endpointId; 41 | client.call(connect.ClientMethods.CREATE_TASK_CONTACT, taskContact, callbacks); 42 | } 43 | }; 44 | 45 | const listTaskTemplates = function(queryParams, callbacks) { 46 | connect.assertNotNull(queryParams, 'Query params for listTaskTemplates'); 47 | var client = connect.core.getClient(); 48 | var instanceId = connect.core.getAgentDataProvider().getInstanceId(); 49 | client.call(connect.TaskTemplatesClientMethods.LIST_TASK_TEMPLATES, { instanceId, queryParams }, callbacks); 50 | }; 51 | 52 | const getTaskTemplate = function(templateParams, callbacks) { 53 | connect.assertNotNull(templateParams, 'Task template params'); 54 | connect.assertNotNull(templateParams.id, 'Task template id'); 55 | var client = connect.core.getClient(); 56 | var instanceId = connect.core.getAgentDataProvider().getInstanceId(); 57 | client.call(connect.TaskTemplatesClientMethods.GET_TASK_TEMPLATE, { instanceId, templateParams }, callbacks); 58 | }; 59 | 60 | const updateContact = function(taskObject, callbacks) { 61 | connect.assertNotNull(taskObject, 'Update for templated task'); 62 | connect.assertNotNull(taskObject.contactId, 'Task contact id'); 63 | var client = connect.core.getClient(); 64 | normalizeTaskTemplateAPIParams(taskObject); 65 | client.call(connect.TaskTemplatesClientMethods.UPDATE_CONTACT, taskObject, callbacks); 66 | }; 67 | 68 | export { createTask, getTaskTemplate, listTaskTemplates, updateContact, ReferenceType }; 69 | -------------------------------------------------------------------------------- /src/core/agentApis.spec.js: -------------------------------------------------------------------------------- 1 | 2 | import '../testUtils/mockConnect.js'; 3 | import { createTask, getTaskTemplate, listTaskTemplates, updateContact } from './agentApis'; 4 | 5 | describe('AgentApis', () => { 6 | const idempotencyToken = '4383f0b7-ddcb-4f8c-a63b-cbd53c852d39'; 7 | const instanceId = 'baf4b555-fa63-445f-8359-5866f35ab09b'; 8 | const taskTemplateId = '61c100a4-1cd4-49fe-9237-6b771e2f0df1'; 9 | const contactId = '2a75a6b8-323d-4f8d-9f73-b15509d98b88'; 10 | const quickConnectId = 'a6a2c310-b91a-4926-8d36-dbc7b758a11d'; 11 | const client = {call: () => {}}; 12 | connect.core.getClient = () => client; 13 | global.AWS = { util: { uuid: { v4: () => idempotencyToken } } }; 14 | 15 | describe('CreateTask API', () => { 16 | let params; 17 | const taskName = 'Task name'; 18 | const taskDescription = 'Task description'; 19 | 20 | 21 | beforeEach(() => { 22 | params = { 23 | name: taskName, 24 | description: taskDescription, 25 | endpoint: { 26 | "endpointARN":`arn:aws:connect:us-west-2:XXXXXX:instance/XXXXXXX/transfer-destination/${quickConnectId}`, 27 | "type":"queue", 28 | "name":"John Smith" 29 | } 30 | }; 31 | }); 32 | it('When CreateTask parameters contain taskTemplateId then CreateTemplatedTask should be called with normalized params', () => { 33 | params.taskTemplateId = taskTemplateId; 34 | client.call = jest.fn(); 35 | createTask(params); 36 | expect(client.call).toHaveBeenCalledWith( 37 | connect.TaskTemplatesClientMethods.CREATE_TEMPLATED_TASK, 38 | { 39 | Name: taskName, 40 | Description: taskDescription, 41 | TaskTemplateId: taskTemplateId, 42 | QuickConnectId: quickConnectId 43 | }, 44 | undefined); 45 | }); 46 | it('When CreateTask parameters doesn not contain taskTemplateId then CreateTaskContact should be called', () => { 47 | client.call = jest.fn(); 48 | createTask(params); 49 | params.idempotencyToken = idempotencyToken; 50 | expect(client.call).toHaveBeenCalledWith( 51 | connect.ClientMethods.CREATE_TASK_CONTACT, 52 | params, 53 | undefined); 54 | }); 55 | }); 56 | 57 | describe('UpdateTemplatedTask API', () => { 58 | let params; 59 | const name = 'updated task name'; 60 | const references = { 61 | 'Phone number': { 62 | type: 'STRING', 63 | value: '+1 234 567 8900', 64 | }, 65 | 'Claim amount': { 66 | type: 'NUMBER', 67 | value: '1000', 68 | } 69 | }; 70 | const normalizedReferences = { 71 | 'Phone number': { 72 | Type: 'STRING', 73 | Value: '+1 234 567 8900', 74 | }, 75 | 'Claim amount': { 76 | Type: 'NUMBER', 77 | Value: '1000', 78 | } 79 | }; 80 | 81 | beforeEach(() => { 82 | params = { 83 | contactId, 84 | name, 85 | references 86 | }; 87 | }); 88 | it('Should call an approipriate Streams client api with normalized paramateres', () => { 89 | client.call = jest.fn(); 90 | updateContact(params); 91 | expect(client.call).toHaveBeenCalledWith( 92 | connect.TaskTemplatesClientMethods.UPDATE_CONTACT, 93 | { 94 | ContactId: contactId, 95 | Name: name, 96 | References: normalizedReferences 97 | }, 98 | undefined); 99 | }); 100 | it('Should throw an error if a required parameter missed', () => { 101 | client.call = jest.fn(); 102 | delete params.contactId; 103 | expect(() => { 104 | updateContact(params); 105 | }).toThrow(); 106 | }); 107 | }); 108 | 109 | describe('ListTaskTemplates API', () => { 110 | const queryParams = { 111 | status: 'active', 112 | maxResults: 50 113 | }; 114 | it('Should call an approipriate Streams client api', () => { 115 | client.call = jest.fn(); 116 | listTaskTemplates(queryParams); 117 | expect(client.call).toHaveBeenCalledWith( 118 | connect.TaskTemplatesClientMethods.LIST_TASK_TEMPLATES, 119 | { 120 | instanceId, 121 | queryParams 122 | }, 123 | undefined); 124 | }); 125 | it('Should throw an error if a required parameter missed', () => { 126 | client.call = jest.fn(); 127 | expect(() => { 128 | listTaskTemplates(); 129 | }).toThrow(); 130 | }); 131 | }); 132 | 133 | describe('GetTaskTemplate API', () => { 134 | let templateParams; 135 | 136 | beforeEach(() => { 137 | templateParams = { 138 | id: taskTemplateId, 139 | version: 5 140 | }; 141 | }); 142 | it('Should call an approipriate Streams client api', () => { 143 | client.call = jest.fn(); 144 | getTaskTemplate(templateParams); 145 | expect(client.call).toHaveBeenCalledWith( 146 | connect.TaskTemplatesClientMethods.GET_TASK_TEMPLATE, 147 | { 148 | instanceId, 149 | templateParams 150 | }, 151 | undefined); 152 | }); 153 | it('Should throw an error if a required parameter missed', () => { 154 | client.call = jest.fn(); 155 | delete templateParams.id; 156 | expect(() => { 157 | getTaskTemplate(templateParams); 158 | }).toThrow(); 159 | }); 160 | }); 161 | }); -------------------------------------------------------------------------------- /src/core/connectionHelpers/LpcConnectionHelper.js: -------------------------------------------------------------------------------- 1 | const ConnectionHelperStatus = { 2 | NeverStarted: 'NeverStarted', 3 | Starting: 'Starting', 4 | Connected: 'Connected', 5 | ConnectionLost: 'ConnectionLost', 6 | Ended: 'Ended', 7 | }; 8 | 9 | const ConnectionHelperEvents = { 10 | ConnectionLost: 'ConnectionLost', 11 | ConnectionGained: 'ConnectionGained', 12 | Ended: 'Ended', 13 | IncomingMessage: 'IncomingMessage', 14 | }; 15 | 16 | class LpcConnectionHelper { 17 | constructor(contactId, initialContactId, websocketManager) { 18 | if (!LpcConnectionHelper.baseInstance) { 19 | LpcConnectionHelper.baseInstance = new LPCConnectionHelperBase(websocketManager); 20 | } 21 | this.contactId = contactId; 22 | this.initialContactId = initialContactId; 23 | this.status = null; 24 | this.eventBus = new connect.EventBus(); 25 | this.subscriptions = [ 26 | LpcConnectionHelper.baseInstance.onEnded(this.handleEnded.bind(this)), 27 | LpcConnectionHelper.baseInstance.onConnectionGain(this.handleConnectionGain.bind(this)), 28 | LpcConnectionHelper.baseInstance.onConnectionLost(this.handleConnectionLost.bind(this)), 29 | LpcConnectionHelper.baseInstance.onMessage(this.handleMessage.bind(this)), 30 | ]; 31 | } 32 | 33 | start() { 34 | return LpcConnectionHelper.baseInstance.start(); 35 | } 36 | 37 | end() { 38 | this.eventBus.unsubscribeAll(); 39 | this.subscriptions.forEach(f => f.unsubscribe()); 40 | this.status = ConnectionHelperStatus.Ended; 41 | } 42 | 43 | getStatus() { 44 | return this.status || LpcConnectionHelper.baseInstance.getStatus(); 45 | } 46 | 47 | onEnded(handler) { 48 | return this.eventBus.subscribe(ConnectionHelperEvents.Ended, handler); 49 | } 50 | 51 | handleEnded() { 52 | this.eventBus.trigger(ConnectionHelperEvents.Ended, {}); 53 | } 54 | 55 | onConnectionGain(handler) { 56 | return this.eventBus.subscribe(ConnectionHelperEvents.ConnectionGained, handler); 57 | } 58 | 59 | handleConnectionGain() { 60 | this.eventBus.trigger(ConnectionHelperEvents.ConnectionGained, {}); 61 | } 62 | 63 | onConnectionLost(handler) { 64 | return this.eventBus.subscribe(ConnectionHelperEvents.ConnectionLost, handler); 65 | } 66 | 67 | handleConnectionLost() { 68 | this.eventBus.trigger(ConnectionHelperEvents.ConnectionLost, {}); 69 | } 70 | 71 | onMessage(handler) { 72 | return this.eventBus.subscribe(ConnectionHelperEvents.IncomingMessage, handler); 73 | } 74 | 75 | handleMessage(message) { 76 | if (message.InitialContactId === this.initialContactId || message.ContactId === this.contactId) { 77 | this.eventBus.trigger(ConnectionHelperEvents.IncomingMessage, message); 78 | } 79 | } 80 | } 81 | 82 | LpcConnectionHelper.baseInstance = null; 83 | 84 | class LPCConnectionHelperBase { 85 | constructor(websocketManager) { 86 | this.status = ConnectionHelperStatus.NeverStarted; 87 | this.eventBus = new connect.EventBus(); 88 | this.initWebsocketManager(websocketManager); 89 | } 90 | 91 | initWebsocketManager(websocketManager) { 92 | this.websocketManager = websocketManager; 93 | this.websocketManager.subscribeTopics(['aws/task']); 94 | this.subscriptions = [ 95 | this.websocketManager.onMessage('aws/task', this.handleMessage.bind(this)), 96 | this.websocketManager.onConnectionGain(this.handleConnectionGain.bind(this)), 97 | this.websocketManager.onConnectionLost(this.handleConnectionLost.bind(this)), 98 | this.websocketManager.onInitFailure(this.handleEnded.bind(this)), 99 | ]; 100 | } 101 | 102 | start() { 103 | if (this.status === ConnectionHelperStatus.NeverStarted) { 104 | this.status = ConnectionHelperStatus.Starting; 105 | } 106 | return Promise.resolve(); 107 | 108 | } 109 | 110 | onEnded(handler) { 111 | return this.eventBus.subscribe(ConnectionHelperEvents.Ended, handler); 112 | } 113 | 114 | handleEnded() { 115 | this.status = ConnectionHelperStatus.Ended; 116 | this.eventBus.trigger(ConnectionHelperEvents.Ended, {}); 117 | } 118 | 119 | onConnectionGain(handler) { 120 | return this.eventBus.subscribe(ConnectionHelperEvents.ConnectionGained, handler); 121 | } 122 | 123 | handleConnectionGain() { 124 | this.status = ConnectionHelperStatus.Connected; 125 | this.eventBus.trigger(ConnectionHelperEvents.ConnectionGained, {}); 126 | } 127 | 128 | onConnectionLost(handler) { 129 | return this.eventBus.subscribe(ConnectionHelperEvents.ConnectionLost, handler); 130 | } 131 | 132 | handleConnectionLost() { 133 | this.status = ConnectionHelperStatus.ConnectionLost; 134 | this.eventBus.trigger(ConnectionHelperEvents.ConnectionLost, {}); 135 | } 136 | 137 | onMessage(handler) { 138 | return this.eventBus.subscribe(ConnectionHelperEvents.IncomingMessage, handler); 139 | } 140 | 141 | handleMessage(message) { 142 | let parsedMessage; 143 | try { 144 | parsedMessage = JSON.parse(message.content); 145 | this.eventBus.trigger(ConnectionHelperEvents.IncomingMessage, parsedMessage); 146 | } catch (e) { 147 | connect.getLog().error(`Wrong message format: %s`, message); 148 | } 149 | } 150 | 151 | getStatus() { 152 | return this.status; 153 | } 154 | } 155 | 156 | export default LpcConnectionHelper; 157 | -------------------------------------------------------------------------------- /src/core/taskController.js: -------------------------------------------------------------------------------- 1 | import LpcConnectionHelper from './connectionHelpers/LpcConnectionHelper'; 2 | import { CONTENT_TYPE_TO_EVENT_MAP, TASK_EVENTS } from '../constants'; 3 | 4 | class TaskController { 5 | constructor(args) { 6 | this.pubsub = new connect.EventBus(); 7 | this.initialContactId = args.initialContactId; 8 | this.contactId = args.contactId; 9 | this.websocketManager = args.websocketManager; 10 | } 11 | 12 | subscribe(eventName, callback) { 13 | this.pubsub.subscribe(eventName, callback); 14 | connect.getLog().info(connect.LogComponent.TASK, `Subscribed successfully to eventName: %s`, eventName); 15 | } 16 | 17 | connect() { 18 | return this._initConnectionHelper().then(this._onConnectSuccess.bind(this), this._onConnectFailure.bind(this)); 19 | } 20 | 21 | getTaskDetails() { 22 | return { 23 | initialContactId: this.initialContactId, 24 | contactId: this.contactId, 25 | }; 26 | } 27 | 28 | unsubscribeAll() { 29 | this.pubsub.unsubscribeAll(); 30 | this.connectionHelper.end(); 31 | } 32 | 33 | _triggerEvent(eventName, eventData) { 34 | connect.getLog().debug(connect.LogComponent.TASK, 'Triggering event for subscribers: %s', eventName).withObject({ 35 | data: eventData, 36 | taskDetails: this.getTaskDetails(), 37 | }); 38 | this.pubsub.trigger(eventName, eventData); 39 | } 40 | 41 | _onConnectSuccess(response) { 42 | connect.getLog().info(connect.LogComponent.TASK, 'Connect successful!'); 43 | const responseObject = { 44 | _debug: response, 45 | connectSuccess: true, 46 | connectCalled: true, 47 | }; 48 | 49 | this._triggerEvent(TASK_EVENTS.CONNECTION_ESTABLISHED, responseObject); 50 | 51 | return responseObject; 52 | } 53 | 54 | _onConnectFailure(error) { 55 | const errorObject = { 56 | _debug: error, 57 | connectSuccess: false, 58 | connectCalled: true, 59 | metadata: this.sessionMetadata, 60 | }; 61 | connect.getLog().error(connect.LogComponent.TASK, 'Connect Failed').withException(errorObject); 62 | return Promise.reject(errorObject); 63 | } 64 | 65 | _initConnectionHelper() { 66 | this.connectionHelper = new LpcConnectionHelper(this.contactId, this.initialContactId, this.websocketManager); 67 | this.connectionHelper.onEnded(this._handleEndedConnection.bind(this)); 68 | this.connectionHelper.onConnectionLost(this._handleLostConnection.bind(this)); 69 | this.connectionHelper.onConnectionGain(this._handleGainedConnection.bind(this)); 70 | this.connectionHelper.onMessage(this._handleIncomingMessage.bind(this)); 71 | return this.connectionHelper.start(); 72 | } 73 | 74 | _handleEndedConnection(eventData) { 75 | this._triggerEvent(TASK_EVENTS.CONNECTION_BROKEN, eventData); 76 | } 77 | 78 | _handleGainedConnection(eventData) { 79 | this._triggerEvent(TASK_EVENTS.CONNECTION_ESTABLISHED, eventData); 80 | } 81 | 82 | _handleLostConnection(eventData) { 83 | this._triggerEvent(TASK_EVENTS.CONNECTION_LOST, eventData); 84 | } 85 | 86 | _handleIncomingMessage(incomingData) { 87 | const eventType = incomingData.ContentType; 88 | if (CONTENT_TYPE_TO_EVENT_MAP[eventType]) { 89 | this._triggerEvent(CONTENT_TYPE_TO_EVENT_MAP[eventType], incomingData); 90 | } 91 | this._triggerEvent(TASK_EVENTS.INCOMING_MESSAGE, incomingData); 92 | } 93 | } 94 | 95 | export { TaskController }; 96 | -------------------------------------------------------------------------------- /src/core/taskSession.js: -------------------------------------------------------------------------------- 1 | import { TaskController } from './taskController'; 2 | import { TASK_EVENTS } from '../constants'; 3 | 4 | class TaskSession { 5 | constructor(controller) { 6 | this.controller = controller; 7 | } 8 | 9 | onMessage(callback){ 10 | this.controller.subscribe(TASK_EVENTS.INCOMING_MESSAGE, callback); 11 | } 12 | 13 | onTransferSucceeded(callback) { 14 | this.controller.subscribe(TASK_EVENTS.TRANSFER_SUCCEEDED, callback); 15 | } 16 | 17 | onTransferFailed(callback) { 18 | this.controller.subscribe(TASK_EVENTS.TRANSFER_FAILED, callback); 19 | } 20 | 21 | onTransferInitiated(callback) { 22 | this.controller.subscribe(TASK_EVENTS.TRANSFER_INITIATED, callback); 23 | } 24 | 25 | onTaskExpiring(callback) { 26 | this.controller.subscribe(TASK_EVENTS.TASK_EXPIRING, callback); 27 | } 28 | 29 | onTaskExpired(callback) { 30 | this.controller.subscribe(TASK_EVENTS.TASK_EXPIRED, callback); 31 | } 32 | 33 | onConnectionBroken(callback) { 34 | this.controller.subscribe(TASK_EVENTS.CONNECTION_BROKEN, callback); 35 | } 36 | 37 | onConnectionEstablished(callback) { 38 | this.controller.subscribe(TASK_EVENTS.CONNECTION_ESTABLISHED, callback); 39 | } 40 | 41 | connect(args) { 42 | return this.controller.connect(args); 43 | } 44 | 45 | cleanUp() { 46 | this.controller.unsubscribeAll(); 47 | } 48 | } 49 | 50 | const TaskSessionObject = { 51 | create: (args) => { 52 | const taskController = new TaskController(args); 53 | return new TaskSession(taskController); 54 | }, 55 | }; 56 | 57 | export { TaskSessionObject, TaskSession }; 58 | -------------------------------------------------------------------------------- /src/core/taskSession.spec.js: -------------------------------------------------------------------------------- 1 | describe('TaskSession', () => { 2 | test('create() should return TaskSession instance', () => { 3 | expect(true).toBe(true); 4 | }); 5 | }); 6 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import { TaskSessionObject } from './core/taskSession'; 2 | import { createTask, getTaskTemplate, listTaskTemplates, updateContact, ReferenceType } from './core/agentApis'; 3 | 4 | global.connect = global.connect || {}; 5 | connect.TaskSession = TaskSessionObject; 6 | 7 | if (!connect.Agent.prototype.createTask) connect.Agent.prototype.createTask = createTask; 8 | if (!connect.Agent.prototype.getTaskTemplate) connect.Agent.prototype.getTaskTemplate = getTaskTemplate; 9 | if (!connect.Agent.prototype.listTaskTemplates) connect.Agent.prototype.listTaskTemplates = listTaskTemplates; 10 | if (!connect.Agent.prototype.updateContact) connect.Agent.prototype.updateContact = updateContact; 11 | 12 | connect.ReferenceType = ReferenceType; 13 | 14 | export const TaskSession = TaskSessionObject; 15 | -------------------------------------------------------------------------------- /src/testUtils/mockConnect.js: -------------------------------------------------------------------------------- 1 | global.connect = { 2 | core: { 3 | getClient: () => ({ 4 | client: () => {} 5 | }), 6 | getAgentDataProvider: () => ({getInstanceId: () => 'baf4b555-fa63-445f-8359-5866f35ab09b'}) 7 | }, 8 | ClientMethods: { 9 | CREATE_TASK_CONTACT: 'CREATE_TASK_CONTACT' 10 | }, 11 | TaskTemplatesClientMethods: { 12 | CREATE_TEMPLATED_TASK: 'CREATE_TEMPLATED_TASK', 13 | LIST_TASK_TEMPLATES: 'LIST_TASK_TEMPLATES', 14 | GET_TASK_TEMPLATE: 'GET_TASK_TEMPLATE', 15 | UPDATE_CONTACT: 'UPDATE_CONTACT' 16 | }, 17 | makeEnum: () => {}, 18 | assertNotNull: (value, message) => { 19 | if (value === null || value === undefined) { 20 | throw new Error(`A value must be provided: ${message}`); 21 | } 22 | } 23 | }; -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const ESLintPlugin = require('eslint-webpack-plugin'); 3 | 4 | module.exports = { 5 | entry: './src/index', 6 | mode: 'production', 7 | output: { 8 | filename: 'amazon-connect-task.js', 9 | path: path.resolve(__dirname, 'dist'), 10 | }, 11 | module: { 12 | rules: [ 13 | { 14 | test: /\.m?js$/, 15 | exclude: /node_modules/, 16 | use: { 17 | loader: 'babel-loader', 18 | options: { 19 | // This is a feature of `babel-loader` for webpack (not Babel itself). 20 | // It enables caching results in ./node_modules/.cache/babel-loader/ 21 | // directory for faster rebuilds. 22 | cacheDirectory: true 23 | }, 24 | }, 25 | }, 26 | ], 27 | }, 28 | plugins: [ 29 | new ESLintPlugin({ 30 | context: 'src', 31 | }), 32 | ], 33 | }; 34 | --------------------------------------------------------------------------------