Coder Social home page Coder Social logo

twilio / twilio-taskrouter.js Goto Github PK

View Code? Open in Web Editor NEW
23.0 18.0 32.0 5.28 MB

JS SDK v2 for Twilio's TaskRouter skills based routing system.

Home Page: https://www.twilio.com/docs/taskrouter

License: Other

Makefile 0.02% Shell 0.52% JavaScript 97.24% Dockerfile 0.01% TypeScript 2.21% CSS 0.01%
twilio taskrouter twilio-flex twilio-api sdk javascript

twilio-taskrouter.js's Issues

Using with React.js?

Hi. I'm trying to experiment with this package in React.js. Following the docs from https://www.twilio.com/docs/taskrouter/js-sdk/workspace/worker#how-does-it-work I am successful in generating a capability token and then using it as the WORKER_TOKEN variable that is passed in as an argument to TaskRouter.Worker's constructor. In a vanilla HTML/JS file, I imported the url-hosted package for taskrouter from here: https://sdk.twilio.com/js/taskrouter/v1.21/taskrouter.min.js. I can connect to the WebSocket server successfully and receive a ready event when connected.

However, when trying to use twilio-taskrouter package installed via npm on a React project, I am not able to connect to the WebSocket server successfully despite generating the access token the same way it was instructed in the code here: https://www.twilio.com/docs/taskrouter/js-sdk/workspace/worker?code-sample=code-creating-a-taskrouter-worker-capability-token&code-language=Node.js&code-sdk-version=3.x

image

This leads me to wonder a few things:

  1. Are these two packages entirely different and have no overlap in terms of connecting to the WebSocket server?
  2. Does the new package have an entirely new way of authenticating the client to connect to the WebSocket server? On TaskRouter.js docs, it mentions to create a capability token, which you can do on a Web Server and request it from the client via HTTP and use it to connect to the WebSocket server. In this new package, it mentions a few additional parameters, such as a signingKeySid and signingKeySecret which is very ambiguous and I was not able to find anything regarding these two terms in the docs or on Twilio Console.
  3. If this library currently does not support React, will it in the future? If it does, is there a sample recipe we can use for reference that can be later added to TaskRouter's docs?

React Native support?

Can't make it work with React Native. Is it even possible?

05-16 23:10:04.746 13860 14128 E ReactNativeJS: TypeError: this.methodFactory is not a function. (In 'this.methodFactory(o,e,n)', 'this.methodFactory' is undefined)
05-16 23:10:04.751 13860 14128 E ReactNativeJS: Invariant Violation: "main" has not been registered. This can happen if:
05-16 23:10:04.751 13860 14128 E ReactNativeJS: * Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
05-16 23:10:04.751 13860 14128 E ReactNativeJS: * A module failed to load due to an error and `AppRegistry.registerComponent` wasn't called.

Angular v17: Uncaught ReferenceError: process is not defined

I am using 'twilio-taskrouter' v2.0.3 npm package in Angular v17 app.
Getting error on accessing the app from browser:

    at node_modules/util/util.js (util.js:109:1)
    at __require (chunk-ZTDPENTR.js?v=8eb4eef9:38:50)
    at 6464 (index.window.js:3:115268)
    at r2 (index.window.js:3:119424)
    at 5600 (index.window.js:3:108312)
    at r2 (index.window.js:3:119424)
    at 568 (index.window.js:3:95429)
    at r2 (index.window.js:3:119424)
    at 6427 (index.window.js:3:97502)
    at r2 (index.window.js:3:119424)

I have debugged this further, twilio-taskrouter is importing 'util' package, which tries to access the (Node) 'process' variable:

if (process.env.NODE_DEBUG) {
  var debugEnv = process.env.NODE_DEBUG;
  debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&')
    .replace(/\*/g, '.*')
    .replace(/,/g, '$|^')
    .toUpperCase();
  debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i');
}

Undeclared variable i in function _emitPendingReservations and function fetchReservations

      WorkerClient.prototype.fetchReservations = function fetchReservations(completion, params) {
         var request = {
            url: this.workspaceUrl + "/Workers/" + this.workerSid + "/Reservations",
            method: "GET",
            token: this.token
         };
         if (params) {
            request.params = params
         }
         var jsonParams = JSON.stringify(request);
         var wrapperCompletionFunc = function (error, reservations) {
            if (error) {
               completion(error);
               return
            }
            var data = reservations.data;
            var promises = [];
            var setTaskProperties = function (reservation) {
               var promise = PropertyUtil.setTaskProperty(reservation);
               promises.push(promise)
            };

             // Undeclared variable i
            for (i = 0; i < data.length; i++) {
               setTaskProperties(data[i])
            }
            Promise.all(promises).then(function (results) {
               completion(null, reservations)
            })
         };
         this.apiRequester._postMessage(jsonParams, wrapperCompletionFunc)
      };
      WorkerClient.prototype._emitPendingReservations = function _emitPendingReservations() {
         var self = this;
         this._fetchPendingReservations().then(function (reservations) {
            if (reservations.length === 0 && self.connectActivitySid) {
               self.update("ActivitySid", self.connectActivitySid)
            }
           // Undeclared variable i
            for (i = 0; i < reservations.length; i++) {
               self._emitMessage("reservation.pending", reservations[i])
            }
         }, function (error) {
            self._log(error.code + " with " + error.message)
         })
      };

Make release-tool a dev dependency

When using Flex and Taskrouter, we are running into an issue in our deployment pipeline where the release-tool dependency is being blocked from accessing that GitHub repo.

Could that dependency be made a dev dependency? I believe that would solve our issue of trying to download that behind our proxy.

TypeError: Object.defineProperty called on non-object

This error seems to happen occasionally. Here's the Sentry info:

https://sentry.io/share/issue/1a50917f3599473b9abfbfc4a4451d1b/

TypeError: Object.defineProperty called on non-object
  at Function.defineProperty(<anonymous>)
  at Object.setProperties(/js/taskrouter/v1.21/taskrouter.min.js:2:20376)
  at Object.createEntity(/js/taskrouter/v1.21/taskrouter.min.js:2:13709)
  at WorkerClient._emitMessage(/js/taskrouter/v1.21/taskrouter.min.js:1:17529)
  at WebSocket.ws.onmessage(/js/taskrouter/v1.21/taskrouter.min.js:1:6896)

Issue importing types

In my project I am using typescript and require Twilio types. Inside this repository I can see a types.d.ts file which is exporting all the different types. However when attempting to import these types they can not be found.

Looking in node modules at was is installed for the package and it appears the types file or an equivalent is not included.

Could this be an issue with the package itself or the way in which I am trying to import the type?

Getting TS errors when using twilio-taskrouter

Two issues I would like to get resolved:

  1. remove the unnecessary async in front of the transfer function (like the surrounding functions)
    https://github.com/twilio/twilio-taskrouter.js/blob/master/types.d.ts#L89

Currently causing: TS1070: 'async' modifier cannot appear on a type member

  1. change int to number as there's no such primitive type in TS
    https://github.com/twilio/twilio-taskrouter.js/blob/master/types.d.ts#L109

Currently causing: TS2304: Cannot find name 'int'

reservation.conference looping

Hi there,

Firstly, i don't know if its a library error or my development mistake, then i'm opening this issue here anyway.

When i'm conferencing a reservation via reservation.conference command, it turns into a loop of "reservation.created -> reservation.canceled -> reservation.created" actions.

I noticed that it just occurs when Agent Conference is on in my Twilio dashboard.

Do you know what it may be?

bundle size

My team is trying to reduce the size of our app and twilio-taskrouter is one of the larger dependencies in the web app. Can efforts be made to reduce the size?

Two opportunities I see are:

  1. Use built-in web fetch API instead of axios (either directly or via a thin wrapper for convenience methods, e.g. ky).
  2. Avoid loading all (or any) of Lodash. Importing functions directly (rather than through _) should allow tree shaking for webpack/rollup/etc. Another option is to use Lodash custom builds. Some or all of the usages can be replaced using modern ES built-ins too. twilio-taskrouter currently only uses 13 methods from lodash (excluding a few other usages in tests/specs):
    1. difference
    2. every
    3. filter
    4. inRange
    5. isBoolean
    6. isDate
    7. isEmpty
    8. isInteger
    9. isNil
    10. isObject
    11. isString
    12. pick
    13. upperFirst

'on' does not exist on type Worker

I am seeing a TS compilation error whereby 'on' is not defined on type 'Worker'. I think this is because the Worker class which is extending NodeJS.EventEmitter should be an interface as opposed to a class.

So instead of export class Worker extends NodeJS.EventEmitter { it should be export interface Worker extends NodeJS.EventEmitter {.

This may be since the release of Node > 14, see here for a similar issue.

Chrome Extension Manifest V3 Support

In manifest V2, extensions have the ability to run the Twilio Voice JS SDK in the background. But with the introduction of manifest V3 (MV3), running the Twilio Voice JS SDK in the background using service workers does not work out of the box due to certain limitations which include DOM access and the ability to keep the service worker alive.

What will be the flow to register worker events in service worker or offscreen api?

WebSocket Connection Failure in Sample App

Environment variables were not correct


Description

I'm attempting to use the Twilio TaskRouter.js sample app but am encountering a persistent WebSocket connection error to 'wss://[invalid URL removed]...'. The worker immediately disconnects afterward.

Steps to Reproduce

  1. Clone the repository git clone https://github.com/twilio/twilio-taskrouter.js
  2. Choose correct directory and install dependencies cd twilio-taskrouter.js/sample-app && yarn
  3. Run the app yarn dev
  4. Supply correct values for environment variables.
  5. Start the sample application.

Observed Behavior

  • Console errors:
[2024-03-08T18:35:40.643Z] Disconnecting websocket
worker.client.tsx:80 [2024-03-08T18:35:40.644Z] Received Event: 'disconnected' from Signaling layer for Worker %s. %s  {message: 'SDK Disconnect'}
worker.client.tsx:80 [2024-03-08T18:35:40.644Z] Unsubscribing from TaskRouter events ... 
log-context.tsx:26 disconnected--Worker is disconnected. reason: {"message":"SDK Disconnect"}
log-context.tsx:26 ======================================================
log-context.tsx:26 Token generated
log-context.tsx:26 <valid_jwt_token>
log-context.tsx:26 Initializing Worker with the new token
worker.client.tsx:69 [2024-03-08T18:35:40.647Z] Subscribing to Signaling events .... 
worker.client.tsx:69 WebSocket connection to 'wss://event-bridge.stage-us1.twilio.com/v1/wschannels?token=<token>&closeExistingSessions=true&clientVersion=2.0.3' failed: 
worker.client.tsx:69 [2024-03-08T18:36:10.676Z] WebSocket error occurred:  
Event {isTrusted: true, type: 'error', target: WebSocket, currentTarget: WebSocket, eventPhase: 2, …}
index.window.js:4 [2024-03-08T18:36:10.678Z] Received Event: 'error' from Signaling layer for Worker %s. 
log-context.tsx:26 error--Worker errored out. error: {}
worker.client.tsx:127 [2024-03-08T18:36:10.679Z] Disconnecting websocket
worker.client.tsx:127 [2024-03-08T18:36:10.679Z] Received Event: 'disconnected' from Signaling layer for Worker %s. %s  
{message: 'SDK Disconnect'}
worker.client.tsx:127 [2024-03-08T18:36:10.679Z] Unsubscribing from TaskRouter events ... 
log-context.tsx:26 disconnected--Worker is disconnected. reason: {"message":"SDK Disconnect"}

Expected Behaviour

The sample app should establish a WebSocket connection to Twilio TaskRouter and maintain worker availability.

Attempted Troubleshooting

  • Verified the accuracy of provided credentials.
  • Checked firewall and proxy settings (cannot identify restrictions)
  • Used Twilio TaskRouter JS SDK v1 successfully, suggesting the issue might be specific to the sample app or SDK v2

Environment

Operating System: macOS Sonoma 14.3.1
Browser: Chrome Version 122.0.6261.112
Node.js Version: v18.19.1
Twilio TaskRouter JS SDK Version: v2.0.3

Request

I'd greatly appreciate any help on debugging this issue.

Could it be related to the sample app, or are there other troubleshooting steps I should consider?

Occasional uncaught exception

On rare occasion, I am getting a network timeout uncaught exception being thrown from axios.

"level":"error","message":"uncaughtException: timeout of 5000ms exceeded\nError: timeout of 5000ms exceeded\n at e.exports (/mytestproject/node_modules/twilio-taskrouter/dist/index.commonjs2.js:10:83369)\n at Timeout._onTimeout (/mytestproject/node_modules/twilio-taskrouter/dist/index.commonjs2.js:10:186399)\n at listOnTimeout (node:internal/timers:556:17)\n at processTimers (node:internal/timers:499:7)","stack":"Error: timeout of 5000ms exceeded\n at e.exports (/mytestproject/node_modules/twilio-taskrouter/dist/index.commonjs2.js:10:83369)\n at Timeout._onTimeout (/mytestproject/node_modules/twilio-taskrouter/dist/index.commonjs2.js:10:186399)\n at listOnTimeout (node:internal/timers:556:17)\n at processTimers (node:internal/timers:499:7)","exception":true,"date":"Wed Mar 24 2021 10:44:42 GMT-0400 (Eastern Daylight Time)"

Is there anyway to handle this in nodejs gracefully?

(1.21.0) taskrouter.min.js:3 Heartbeat timed out. closing socket

If the user sets the computer on sleep for long interval then on reconnection it starts giving error
Websocket closed
Websocket has disconnected
Received a message of type [disconnected]
Websocket had an error.

Even though I tried creating new worker with existing token (i.e. new Twilio.TaskRouter.Worker(workerToken, true, null, null, true), or with new token, or with worker.updateToken still the worker does not establishes connection again.
Screenshot from 2021-03-25 14-21-33

Change the version to start at 2.0.0

The documentation around task router V1 and V2 is very confusing. It would be helpful if this project started in the V2 semver range. Perhaps even a note in the readme to indicate there is an older version and main differences.

Shouldn't Task.setAttributes pass the task version in the request?

I'm experiencing conflicts in some tasks due to concurrent updates. So I'm tracking down all the places performing any updates to tasks: Backend systems, functions, and Flex plugins. I hope a can apply the conflict resolution suggested in the documentation. When investigating one of my plugins I realized this method doesn't handle the task version when setting the attributes. This could lead to the kind of conflict I'm trying to mitigate.

Is the version handling in the roadmap for this lib? In the meanwhile, there's a suggested way to handle the task update differently in Flex plugins?

setAttributes(attributes) {
if (!_.isObject(attributes)) {
throw new TypeError('Unable to set attributes on Task. <object>attributes is a required parameter.');
}
const requestURL = this._worker.getRoutes().getRoute(TASK_INSTANCE, this.sid).path;
const requestParams = { Attributes: attributes };
return this._request.post(requestURL, requestParams, API_V1).then(response => {
return this._update(response);
});
}

TaskRouter Incompatibilities between Flex UI versions

Hello,

I wasn't able to find reason for the following in TaskRouter release notes, but:

Prior to Flex UI 1.34.0 we relied on some Worker attributes and methods, part of which existed in TR 0.7.x but didn't exist in TR 0.5.x. As a result, when upgrading our custom plugin to [email protected] we're facing with compatibility issues. For example we used Worker.fetchLatestVersion method which we now cannot use with [email protected].

First of all.. how/where can we track such unexpected breaking changes when a part of dependencies is downgraded whereas with the Flex UI package version is upgraded?

What would be an alternative to this Worker.fetchLatestVersion method in TR 0.5.x?

We're also aiming to have our code compatible with Flex UI 2.x as much as possible, and that is one of the issues which 'caused a negative effect on this goal.

verifyJWT called but no longer exists

In TaskRouterBase, tools.verifyJWT is called, but verifyJWT was removed from Tools in 2.0.0. This throws an error when instantiating TaskRouterBase.
Using twilio-taskrouter 0.2.4 from npm.

screen shot 2018-08-17 at 12 32 53 pm

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.