diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..a286d11 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,24 @@ +name: Run Tests + +on: + push: + branches: + - '**' +jobs: + test: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v3 + + - name: Setup Node.js + uses: actions/setup-node@v3 + with: + node-version: '20' + + - name: Install dependencies + run: npm install + + - name: Run tests + run: npm run test diff --git a/babel-plugin.js b/babel-plugin.js new file mode 100644 index 0000000..a83c251 --- /dev/null +++ b/babel-plugin.js @@ -0,0 +1,12 @@ +module.exports = function replacePaths({ types: t }) { + return { + visitor: { + ImportDeclaration(path) { + const importPath = path.node.source.value; + if (importPath === '../package.json') { + path.node.source = t.stringLiteral('../../package.json'); + } + }, + }, + }; +}; diff --git a/babel.config.cjs.json b/babel.config.cjs.json new file mode 100644 index 0000000..f453b0b --- /dev/null +++ b/babel.config.cjs.json @@ -0,0 +1,19 @@ +{ + "presets": [ + [ "@babel/preset-env" ] + ], + "plugins": [ + [ "@babel/plugin-syntax-import-assertions" ], + [ "./babel-plugin.js" ], + [ + "babel-plugin-replace-import-extension", + { + "extMapping": { + ".mjs": "" + } + } + ], + ["@babel/plugin-transform-modules-commonjs", { "allowTopLevelThis": true }], + [ "babel-plugin-add-module-exports" ] + ] +} diff --git a/babel.config.esm.json b/babel.config.esm.json new file mode 100644 index 0000000..97e107e --- /dev/null +++ b/babel.config.esm.json @@ -0,0 +1,25 @@ +{ + "presets": [ + [ + "@babel/preset-env", + { + "targets": { + "esmodules": true + }, + "modules": false + } + ] + ], + "plugins": [ + [ "@babel/plugin-syntax-import-assertions" ], + [ "./babel-plugin.js" ], + [ + "babel-plugin-replace-import-extension", + { + "extMapping": { + ".mjs": "" + } + } + ] + ] +} diff --git a/dist/cjs/AppVerifyClient.js b/dist/cjs/AppVerifyClient.js new file mode 100644 index 0000000..b0b358c --- /dev/null +++ b/dist/cjs/AppVerifyClient.js @@ -0,0 +1,52 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var _RestClient2 = _interopRequireDefault(require("./RestClient")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +/*** + * App Verify is a secure, lightweight SDK that integrates a frictionless user verification + * process into existing native mobile applications. + */ +var AppVerifyClient = exports["default"] = /*#__PURE__*/function (_RestClient) { + function AppVerifyClient(requestWrapper, customerId, apiKey) { + var _this; + var restEndpoint = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + var timeout = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 15000; + var userAgent = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; + _classCallCheck(this, AppVerifyClient); + _this = _callSuper(this, AppVerifyClient, [requestWrapper, customerId, apiKey, restEndpoint, timeout, userAgent]); + _this.appverify_resource = "/v1/mobile/verification/status/"; + return _this; + } + + /*** + * Get status of app verification transaction. + * + * @param callback: Callback method to handle the response. + * @param externalId: External ID (xid) used in the JWT token during verification. + */ + _inherits(AppVerifyClient, _RestClient); + return _createClass(AppVerifyClient, [{ + key: "status", + value: function status(callback, externalId) { + this.execute(callback, "GET", this.appverify_resource + externalId); + } + }]); +}(_RestClient2["default"]); +module.exports = exports.default; \ No newline at end of file diff --git a/dist/cjs/Constants.js b/dist/cjs/Constants.js new file mode 100644 index 0000000..0000c8e --- /dev/null +++ b/dist/cjs/Constants.js @@ -0,0 +1,10 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AuthMethodNames = void 0; +var AuthMethodNames = exports.AuthMethodNames = { + BASIC: "Basic", + HMAC_SHA256: "HMAC-SHA256" +}; \ No newline at end of file diff --git a/dist/cjs/IntelligenceClient.js b/dist/cjs/IntelligenceClient.js new file mode 100644 index 0000000..9dff514 --- /dev/null +++ b/dist/cjs/IntelligenceClient.js @@ -0,0 +1,67 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var _RestClient2 = _interopRequireDefault(require("./RestClient")); +var _Constants = require("./Constants"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var INTELLIGENCE_ENDPOINT_PATH = "/intelligence"; +var contentType = "application/json"; + +/*** + * It is critical today to evaluate fraud risk throughout the entire customer journey. + * + * Telesign Intelligence makes it easy to understand the risk and the reason behind it with tailored scoring models + *and comprehensive reason codes. + */ +var IntelligenceClient = exports["default"] = /*#__PURE__*/function (_RestClient) { + function IntelligenceClient(requestWrapper, customerId, apiKey) { + var _this; + var restEndpoint = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + var timeout = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 15000; + var userAgent = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; + _classCallCheck(this, IntelligenceClient); + _this = _callSuper(this, IntelligenceClient, [requestWrapper, customerId, apiKey, restEndpoint, timeout, userAgent, contentType]); + _this.intelligenceResource = INTELLIGENCE_ENDPOINT_PATH; + return _this; + } + + /*** + * Telesign Intelligence is like a credit check for digital profiles. + * + * You submit a phone number, IP, and email to the service, the individual + *identifiers are each evaluated, and then a score is returned telling you how risky + *that user is. + * + * You decide whether to proceed based on the score. + * + * See https://developer.telesign.com/enterprise/docs/intelligence-overview + *for detailed API documentation. + * + * @param callback: Callback method to handle response. + * @param requestBody: requestBody to be passed to Intelligence API + */ + _inherits(IntelligenceClient, _RestClient); + return _createClass(IntelligenceClient, [{ + key: "intelligence", + value: function intelligence(callback, requestBody) { + this.execute(callback, "POST", this.intelligenceResource, requestBody, _Constants.AuthMethodNames.BASIC); + } + }]); +}(_RestClient2["default"]); +module.exports = exports.default; \ No newline at end of file diff --git a/dist/cjs/MessagingClient.js b/dist/cjs/MessagingClient.js new file mode 100644 index 0000000..c3e4a67 --- /dev/null +++ b/dist/cjs/MessagingClient.js @@ -0,0 +1,76 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var _RestClient2 = _interopRequireDefault(require("./RestClient")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +/*** + * TeleSign's Messaging API allows you to easily send SMS messages. You can send alerts, + * reminders, and notifications, or you can send verification messages containing + * one-time passcodes ( OTP ). + */ +var MessagingClient = exports["default"] = /*#__PURE__*/function (_RestClient) { + function MessagingClient(requestWrapper, customerId, apiKey) { + var _this; + var restEndpoint = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + var timeout = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 15000; + var userAgent = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; + _classCallCheck(this, MessagingClient); + _this = _callSuper(this, MessagingClient, [requestWrapper, customerId, apiKey, restEndpoint, timeout, userAgent]); + _this.messaging_resource = "/v1/messaging"; + _this.messaging_status_resource = "/v1/messaging/"; + return _this; + } + + /*** + * Send a message to the target phoneNumber. + * + * See https://developer.telesign.com/docs/messaging-api for detailed API documentation. + * + * @param callback: Callback method to handle response. + * @param phoneNumber: Phone number to call + * @param message: Text of the message to be sent to the end user. + * @param messageType: This parameter specifies the traffic type being sent in the message. + * transaction. + */ + _inherits(MessagingClient, _RestClient); + return _createClass(MessagingClient, [{ + key: "message", + value: function message(callback, phoneNumber, _message, messageType) { + var params = { + phone_number: phoneNumber, + message: _message, + message_type: messageType + }; + this.execute(callback, "POST", this.messaging_resource, params); + } + + /*** + * Get status of message transaction. + * + * @param callback: Callback method to handle the response. + * @param referenceId: Reference ID received in the response of message. + */ + }, { + key: "status", + value: function status(callback, referenceId) { + this.execute(callback, "GET", this.messaging_status_resource + referenceId, null); + } + }]); +}(_RestClient2["default"]); +module.exports = exports.default; \ No newline at end of file diff --git a/dist/cjs/PhoneIDClient.js b/dist/cjs/PhoneIDClient.js new file mode 100644 index 0000000..71b6d06 --- /dev/null +++ b/dist/cjs/PhoneIDClient.js @@ -0,0 +1,60 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var _RestClient2 = _interopRequireDefault(require("./RestClient")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +/*** + * A set of APIs that deliver deep phone number data attributes that help optimize the end user + * verification process and evaluate risk. + */ +var PhoneIDClient = exports["default"] = /*#__PURE__*/function (_RestClient) { + function PhoneIDClient(requestWrapper, customerId, apiKey) { + var _this; + var restEndpoint = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + var timeout = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 15000; + var useragent = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; + _classCallCheck(this, PhoneIDClient); + _this = _callSuper(this, PhoneIDClient, [requestWrapper, customerId, apiKey, restEndpoint, timeout, useragent]); + _this.phoneid_resource = "/v1/phoneid/"; + _this.contentType = "application/json"; + return _this; + } + + /*** + * The PhoneID API provides a cleansed phone number, phone type, and telecom carrier + * information to determine the best communication method - SMS or voice. + * + * See https://developer.telesign.com/docs/phoneid-api for detailed API documentation. + * + * @param callback: Callback method to handle response. + * @param phoneNumber: Phone number to call + * @param accountLifecycleEvent: (Optional) Indicates the phase in lifecycle for the + * transaction. + * @param originatingIP: IP address of request origination host + */ + _inherits(PhoneIDClient, _RestClient); + return _createClass(PhoneIDClient, [{ + key: "phoneID", + value: function phoneID(callback, phoneNumber) { + var params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + this.execute(callback, "POST", this.phoneid_resource + encodeURI(phoneNumber), params); + } + }]); +}(_RestClient2["default"]); +module.exports = exports.default; \ No newline at end of file diff --git a/dist/cjs/RequestWrapper.js b/dist/cjs/RequestWrapper.js new file mode 100644 index 0000000..ea88603 --- /dev/null +++ b/dist/cjs/RequestWrapper.js @@ -0,0 +1,194 @@ +"use strict"; + +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.RequestWrapper = exports.FetchRequestWrapper = void 0; +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } +function __transformExtension(filepath, extMapping) { + if (!filepath.startsWith('./') && !filepath.startsWith('../')) { + // Package import + return filepath; + } + var idx = filepath.lastIndexOf('.'); + if (idx === -1 || filepath.includes('/', idx)) { + // No extension + var newExt = extMapping['']; + if (newExt) { + return filepath + newExt; + } + return filepath; + } + var _iterator = _createForOfIteratorHelper(Object.entries(extMapping).sort(function (a, b) { + return b[0].length - a[0].length; + })), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var _step$value = _slicedToArray(_step.value, 2), + origExt = _step$value[0], + _newExt = _step$value[1]; + if (filepath.endsWith(origExt)) { + return filepath.slice(0, -origExt.length) + _newExt; + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + return filepath; +} +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var RequestWrapper = exports.RequestWrapper = /*#__PURE__*/function () { + function RequestWrapper() { + _classCallCheck(this, RequestWrapper); + } + return _createClass(RequestWrapper, [{ + key: "request", + value: function request(options, callback) { + throw new Error('makeRequest method must be implemented.'); + } + }]); +}(); +var handleResponse = function handleResponse(response, callback) { + var res = { + status: response.status, + headers: response.headers, + bodyStr: JSON.stringify(response) + }; + callback(null, res, res.bodyStr); +}; +var handleError = function handleError(error, callback) { + callback(error, null, error); +}; +function fetchWithTimeout(_x, _x2) { + return _fetchWithTimeout.apply(this, arguments); +} +function _fetchWithTimeout() { + _fetchWithTimeout = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(url, options) { + var fetch; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + /** @type {any} */ + fetch = (typeof window !== 'undefined' ? window : global).fetch || null; + if (fetch) { + _context.next = 5; + break; + } + _context.next = 4; + return function (specifier) { + return new Promise(function (r) { + return r("".concat(specifier)); + }).then(function (s) { + return _interopRequireWildcard(require(s)); + }); + }(__transformExtension('node-fetch', { + ".mjs": "" + })).then(function (m) { + var _m$default; + return (_m$default = m["default"]) !== null && _m$default !== void 0 ? _m$default : m; + }); + case 4: + fetch = _context.sent; + case 5: + _context.next = 7; + return Promise.race([fetch(url, options), new Promise(function (_, reject) { + return setTimeout(function () { + return reject({ + code: 408, + message: 'Timeout' + }); + }, options.timeout); + })]); + case 7: + return _context.abrupt("return", _context.sent); + case 8: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _fetchWithTimeout.apply(this, arguments); +} +var FetchRequestWrapper = exports.FetchRequestWrapper = /*#__PURE__*/function (_RequestWrapper) { + function FetchRequestWrapper() { + _classCallCheck(this, FetchRequestWrapper); + return _callSuper(this, FetchRequestWrapper, arguments); + } + _inherits(FetchRequestWrapper, _RequestWrapper); + return _createClass(FetchRequestWrapper, [{ + key: "request", + value: function request(options, callback) { + switch (options.method) { + case 'POST': + fetchWithTimeout(options.url, { + method: options.method, + headers: options.headers, + body: options.body, + timeout: options.timeout + }).then(function (response) { + return response.json(); + }).then(function (data) { + return handleResponse(data, callback); + })["catch"](function (error) { + return handleError(error, callback); + }); + break; + case 'PUT': + fetchWithTimeout(options.url, { + method: options.method, + headers: options.headers, + body: options.body, + timeout: options.timeout + }).then(function (response) { + return response.json(); + }).then(function (data) { + return handleResponse(data, callback); + })["catch"](function (error) { + return handleError(error, callback); + }); + break; + case 'GET': + fetchWithTimeout(options.url, { + method: options.method, + headers: options.headers, + timeout: options.timeout + }).then(function (response) { + return response.json(); + }).then(function (data) { + return handleResponse(data, callback); + })["catch"](function (error) { + return handleError(error, callback); + }); + break; + default: + console.error('Method: ' + options.method + ' not supported!'); + } + } + }]); +}(RequestWrapper); \ No newline at end of file diff --git a/dist/cjs/RestClient.js b/dist/cjs/RestClient.js new file mode 100644 index 0000000..3fd506a --- /dev/null +++ b/dist/cjs/RestClient.js @@ -0,0 +1,199 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var _crypto = _interopRequireDefault(require("crypto")); +var _Constants = require("./Constants"); +var _Util = require("./Util"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/*** + * The TeleSign RestClient is a generic HTTP REST client that can be extended to make + * requests against any of TeleSign's REST API endpoints. + * + * See https://developer.telesign.com for detailed API documentation. + */ +var RestClient = exports["default"] = /*#__PURE__*/function () { + function RestClient(requestWrapper, customerId, apiKey) { + var restEndpoint = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "https://rest-api.telesign.com"; + var timeout = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 15000; + var userAgent = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; + var source = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : "node_telesign"; + var sdkVersionOrigin = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : null; + var sdkVersionDependency = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : null; + var contentType = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : "application/x-www-form-urlencoded"; + _classCallCheck(this, RestClient); + this.requestWrapper = requestWrapper; + this.customerId = customerId; + this.apiKey = apiKey; + this.restEndpoint = restEndpoint === null ? "https://rest-api.telesign.com" : restEndpoint; + this.timeout = timeout; + this.contentType = contentType; + var currentVersionSdk = sdkVersionOrigin || (0, _Util.getInstalledVersion)(); + this.userAgent = "TeleSignSDK/ECMAScript-Node" + " ".concat(process.arch) + "/".concat(process.platform) + " ".concat(process.release.name) + "/".concat(process.version) // Generates a Node useragent - helpful in diagnosing errors + + " OriginatingSDK/".concat(source) + " SDKVersion/".concat(currentVersionSdk) + (source !== "node_telesign" ? " DependencySDKVersion/".concat(sdkVersionDependency) : ""); + } + + /*** + * Generates the TeleSign REST API headers used to authenticate requests. + * + * Creates the canonicalized stringToSign and generates the HMAC signature. This is used to + * authenticate requests against the TeleSign REST API. + * + * See https://developer.telesign.com/docs/authentication for detailed API documentation. + * + * @param customerId: Your account customerId. + * @param apiKey: Your account apiKey. + * @param methodName: The HTTP method name of the request as a upper case string, should be one + * of 'POST', 'GET', 'PUT' or 'DELETE'. + * @param resource: The partial resource URI to perform the request against, as a string. + * @param urlEncodedFields: HTTP body parameters to perform the HTTP request with, must be a + * urlencoded string. + * @param date: The date and time of the request formatted in rfc 2616, as a string. + * @param nonce: A unique cryptographic nonce for the request, as a string. + * @param userAgent: (optional) User Agent associated with the request, as a string. + * @param authMethod : (optional) Authentication type. For ex: Basic, HMAC etc + * @returns headers: {{Authorization: string, Date: *, Content-Type: string, + * x-ts-auth-method: string, x-ts-nonce: *}} + */ + return _createClass(RestClient, [{ + key: "execute", + value: + // method generateTeleSignHeaders + + /*** + * Generic TeleSign REST API request handler. + * + * @param callback: Callback method to handle response. + * @param methodName: The HTTP method name, as an upper case string. + * @param resource: The partial resource URI to perform the request against, as a string. + * @param authMethod: (optional) Authentication type. For ex: Basic, HMAC etc + * @param params: Body params to perform the HTTP request with, as a dictionary. + */ + function execute(callback, methodName, resource) { + var params = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + var authMethod = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null; + var nonce = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; + var date = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null; + var telesignURL = this.restEndpoint + resource; + var bodyData = this.contentType == "application/json" ? "{}" : null; + if (methodName == "POST" || methodName == "PUT") { + if (params != null && Object.keys(params).length > 0) { + if (this.contentType == "application/x-www-form-urlencoded") { + var urlSearchParams = new URLSearchParams(params); + bodyData = urlSearchParams.toString(); + } else { + bodyData = JSON.stringify(params); + } + } + } else { + // GET method + if (params != null) { + var url = new URL(this.restEndpoint + resource); + Object.keys(params).forEach(function (key) { + return url.searchParams.append(key, params[key]); + }); + telesignURL = url.toString(); + } else { + telesignURL = new URL(this.restEndpoint + resource).toString(); + } + } + var headers = RestClient.generateTeleSignHeaders(this.customerId, this.apiKey, methodName, resource, this.contentType, bodyData, date !== null ? date : null, nonce, this.userAgent, authMethod); + var requestParams = { + headers: headers, + url: telesignURL, + method: methodName, + timeout: this.timeout + }; + if (bodyData != null) { + requestParams.body = bodyData; + } + this.requestWrapper.request(requestParams, function (err, res, bodyStr) { + if (err) { + console.error("FATAL ERROR: ".concat(date !== null ? date : new Date()) + " Problems contacting Telesign Servers. Check your internet connection."); + if (callback) { + callback(err, bodyStr); + } + } + if (res) { + var body = JSON.parse(bodyStr); + if (callback) { + callback(err, body); + } + } + }); + } + + /** + * @param {string} restEndpoint + */ + }, { + key: "setRestEndpoint", + value: function setRestEndpoint(restEndpoint) { + this.restEndpoint = restEndpoint; + } + + /** + * @param {string} contentType + */ + }, { + key: "setContentType", + value: function setContentType(contentType) { + this.contentType = contentType; + } + }], [{ + key: "generateTeleSignHeaders", + value: function generateTeleSignHeaders(customerId, apiKey, methodName, resource, contentType, encodedFields) { + var date = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null; + var nonce = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : null; + var userAgent = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : null; + var authMethod = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : null; + return function (contentType, authMethod) { + if (date == null) { + date = new Date().toUTCString(); + } + if (nonce == null) { + nonce = _crypto["default"].randomUUID(); // generates a Random NONCE (Number Used Only Once) + } + var contentType = methodName == "POST" || methodName == "PUT" ? contentType : ""; + var authMethod = authMethod != null ? authMethod : _Constants.AuthMethodNames.HMAC_SHA256; + var urlencoded = ""; + if (encodedFields != null && encodedFields.length > 0) { + urlencoded = "\n" + encodedFields; + } + /** @type {any} */ + var stringToSignBuilder = methodName + "\n" + contentType + "\n" + date + "\n" + "x-ts-auth-method:" + authMethod + "\n" + "x-ts-nonce:" + nonce + urlencoded + "\n" + resource; + if (authMethod === _Constants.AuthMethodNames.BASIC) { + var authorization = "Basic " + Buffer.from(customerId + ":" + apiKey).toString('base64'); + } else { + var signedStrUTF8 = stringToSignBuilder.toString('utf8'); + var decodedAPIKey = Buffer.from(apiKey, 'base64'); + + /** @type {any} */ + var jsSignature = _crypto["default"].createHmac("sha256", decodedAPIKey).update(signedStrUTF8).digest("base64"); + jsSignature = jsSignature.toString('utf8'); + // console.log("js Signature: " + jsSignature); + + var authorization = "TSA " + customerId + ":" + jsSignature; + } + var headers = { + "Authorization": authorization, + "Date": date, + "Content-Type": contentType, + "x-ts-auth-method": authMethod, + "x-ts-nonce": nonce + }; + if (userAgent != null) headers["User-Agent"] = userAgent; + return headers; + }(contentType, authMethod); + } + }]); +}(); +module.exports = exports.default; \ No newline at end of file diff --git a/dist/cjs/ScoreClient.js b/dist/cjs/ScoreClient.js new file mode 100644 index 0000000..d4b3fd7 --- /dev/null +++ b/dist/cjs/ScoreClient.js @@ -0,0 +1,85 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var _RestClient2 = _interopRequireDefault(require("./RestClient")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +/*** + * Score provides risk information about a specified phone number. + */ +var ScoreClient = exports["default"] = /*#__PURE__*/function (_RestClient) { + function ScoreClient(requestWrapper, customerId, apiKey) { + var _this; + var restEndpoint = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + var timeout = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 15000; + var userAgent = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; + _classCallCheck(this, ScoreClient); + _this = _callSuper(this, ScoreClient, [requestWrapper, customerId, apiKey, restEndpoint, timeout, userAgent]); + _this.scoreResource = "/v1/score/"; + return _this; + } + + /*** + * Score is an API that delivers reputation scoring based on phone number intelligence, + * traffic patterns, machine learning, and a global data consortium. + * + * See https://developer.telesign.com/docs/score-api for detailed API documentation. + * + * @param callback: Callback method to handle response. + * @param phoneNumber: Phone number for which to check score + * @param accountLifecycleEvent: Indicate what phase of the lifecycle you are in when you + * send a transaction. + * @param originatingIP: (Optional) End user's IP address. + * @param deviceId: (Optional) End user’s device identifier. + * @param accountId: (Optional) End user’s account id + * @param emailAddress: (Optional) End user’s email address + * @param requestRiskInsights: (Optional) Boolean value of true, false or null for reason codes + * ONLY SET IF Score 2.0 requests is enabled, confirm with your Telesign representative + */ + _inherits(ScoreClient, _RestClient); + return _createClass(ScoreClient, [{ + key: "score", + value: function score(callback, phoneNumber, accountLifecycleEvent) { + var originatingIP = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + var deviceId = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null; + var accountId = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; + var emailAddress = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null; + var requestRiskInsights = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : null; + var params = { + account_lifecycle_event: accountLifecycleEvent + }; + if (originatingIP != null) { + params.originating_ip = originatingIP; + } + if (deviceId != null) { + params.device_id = deviceId; + } + if (accountId != null) { + params.account_id = accountId; + } + if (emailAddress != null) { + params.email_address = emailAddress; + } + if (requestRiskInsights != null) { + params.request_risk_insights = requestRiskInsights; + } + this.execute(callback, "POST", this.scoreResource + encodeURI(phoneNumber), params); + } + }]); +}(_RestClient2["default"]); +module.exports = exports.default; \ No newline at end of file diff --git a/dist/cjs/TeleSign.js b/dist/cjs/TeleSign.js new file mode 100644 index 0000000..735c56a --- /dev/null +++ b/dist/cjs/TeleSign.js @@ -0,0 +1,40 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var _RestClient = _interopRequireDefault(require("./RestClient")); +var _MessagingClient = _interopRequireDefault(require("./MessagingClient")); +var _ScoreClient = _interopRequireDefault(require("./ScoreClient")); +var _PhoneIDClient = _interopRequireDefault(require("./PhoneIDClient")); +var _VoiceClient = _interopRequireDefault(require("./VoiceClient")); +var _AppVerifyClient = _interopRequireDefault(require("./AppVerifyClient")); +var _IntelligenceClient = _interopRequireDefault(require("./IntelligenceClient")); +var _RequestWrapper = require("./RequestWrapper"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +var TeleSign = exports["default"] = /*#__PURE__*/_createClass(function TeleSign(customerId, apiKey) { + var restEndpoint = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "https://rest-api.telesign.com"; + var timeout = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 15000; + var useragent = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null; + var source = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : "node_telesign"; + var sdkVersionOrigin = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null; + var sdkVersionDependency = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : null; + _classCallCheck(this, TeleSign); + var requestWrapper = new _RequestWrapper.FetchRequestWrapper(); + this.rest = new _RestClient["default"](requestWrapper, customerId, apiKey, restEndpoint, timeout, useragent, source, sdkVersionOrigin, sdkVersionDependency); + this.sms = new _MessagingClient["default"](requestWrapper, customerId, apiKey, restEndpoint, timeout, useragent); + this.voice = new _VoiceClient["default"](requestWrapper, customerId, apiKey, restEndpoint, timeout, useragent); + this.score = new _ScoreClient["default"](requestWrapper, customerId, apiKey, restEndpoint, timeout, useragent); + this.phoneid = new _PhoneIDClient["default"](requestWrapper, customerId, apiKey, restEndpoint, timeout, useragent); + this.appverify = new _AppVerifyClient["default"](requestWrapper, customerId, apiKey, restEndpoint, timeout, useragent); + this.intelligence = new _IntelligenceClient["default"](requestWrapper, customerId, apiKey, restEndpoint, timeout, useragent); +}); +; +module.exports = exports.default; \ No newline at end of file diff --git a/dist/cjs/Util.js b/dist/cjs/Util.js new file mode 100644 index 0000000..87bda3d --- /dev/null +++ b/dist/cjs/Util.js @@ -0,0 +1,11 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getInstalledVersion = getInstalledVersion; +var _package = _interopRequireDefault(require("../../package.json")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function getInstalledVersion() { + return _package["default"].version; +} \ No newline at end of file diff --git a/dist/cjs/VoiceClient.js b/dist/cjs/VoiceClient.js new file mode 100644 index 0000000..49d4d7b --- /dev/null +++ b/dist/cjs/VoiceClient.js @@ -0,0 +1,100 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var _RestClient2 = _interopRequireDefault(require("./RestClient")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +/*** + * TeleSign's Voice API allows you to easily send voice messages. You can send alerts, + * reminders, and notifications, or you can send verification messages containing time-based, + * one-time passcodes (TOTP). + */ +var VoiceClient = exports["default"] = /*#__PURE__*/function (_RestClient) { + function VoiceClient(requestWrapper, customerId, apiKey) { + var _this; + var restEndpoint = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + var timeout = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 15000; + var useragent = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; + _classCallCheck(this, VoiceClient); + _this = _callSuper(this, VoiceClient, [requestWrapper, customerId, apiKey, restEndpoint, timeout, useragent]); + _this.voice_resource = "/v1/voice"; + _this.voice_status_resource = "/v1/voice/"; + return _this; + } + + /*** + * Send a voice callto the target phoneNumber. + * + * See https://developer.telesign.com/docs/voice-api for detailed API documentation. + * + * @param callback: Callback method to handle response. + * @param phoneNumber: Phone number to call + * @param message: Text of the message to be converted to voice on call to the end + * user. [max 2000 code points] + * @param messageType: This parameter specifies the traffic type being sent in the message. + * @param voice: The voice parameter allows you to specify a voice to be used to speak your + * text to speech message. + * @param callbackURL: (Optional) URL of the callback server you would like to receive updates + * on. + * @param accountLifecycleEvent: (Optional) Indicates the phase in lifecycle for the + * transaction. + * @param originatingIP: (Optional) End user's IP address. + */ + _inherits(VoiceClient, _RestClient); + return _createClass(VoiceClient, [{ + key: "call", + value: function call(callback, phoneNumber, message, messageType) { + var voice = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null; + var callbackURL = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; + var accountLifecycleEvent = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null; + var originatingIP = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : null; + var params = { + phone_number: phoneNumber, + message: message, + message_type: messageType + }; + if (voice != null) { + params.voice = voice; + } + if (callbackURL != null) { + params.callbackURL = callbackURL; + } + if (accountLifecycleEvent != null) { + params.account_lifecycle_event = accountLifecycleEvent; + } + if (originatingIP != null) { + params.originating_ip = originatingIP; + } + this.execute(callback, "POST", this.voice_resource, params); + } + + /*** + * Get status of voice call transaction. + * + * @param callback: Callback method to handle the response. + * @param referenceId: Reference ID received in the response of call. + */ + }, { + key: "status", + value: function status(callback, referenceId) { + var status_resource = this.voice_status_resource + referenceId; + this.execute(callback, "GET", status_resource); + } + }]); +}(_RestClient2["default"]); +module.exports = exports.default; \ No newline at end of file diff --git a/dist/esm/AppVerifyClient.js b/dist/esm/AppVerifyClient.js new file mode 100644 index 0000000..0458cf8 --- /dev/null +++ b/dist/esm/AppVerifyClient.js @@ -0,0 +1,25 @@ +import RestClient from "./RestClient"; + +/*** + * App Verify is a secure, lightweight SDK that integrates a frictionless user verification + * process into existing native mobile applications. + */ +export default class AppVerifyClient extends RestClient { + constructor(requestWrapper, customerId, apiKey) { + var restEndpoint = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + var timeout = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 15000; + var userAgent = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; + super(requestWrapper, customerId, apiKey, restEndpoint, timeout, userAgent); + this.appverify_resource = "/v1/mobile/verification/status/"; + } + + /*** + * Get status of app verification transaction. + * + * @param callback: Callback method to handle the response. + * @param externalId: External ID (xid) used in the JWT token during verification. + */ + status(callback, externalId) { + this.execute(callback, "GET", this.appverify_resource + externalId); + } +} \ No newline at end of file diff --git a/dist/esm/Constants.js b/dist/esm/Constants.js new file mode 100644 index 0000000..e817763 --- /dev/null +++ b/dist/esm/Constants.js @@ -0,0 +1,4 @@ +export var AuthMethodNames = { + BASIC: "Basic", + HMAC_SHA256: "HMAC-SHA256" +}; \ No newline at end of file diff --git a/dist/esm/IntelligenceClient.js b/dist/esm/IntelligenceClient.js new file mode 100644 index 0000000..58eba19 --- /dev/null +++ b/dist/esm/IntelligenceClient.js @@ -0,0 +1,39 @@ +import RestClient from "./RestClient"; +import { AuthMethodNames } from "./Constants"; +var INTELLIGENCE_ENDPOINT_PATH = "/intelligence"; +var contentType = "application/json"; + +/*** + * It is critical today to evaluate fraud risk throughout the entire customer journey. + * + * Telesign Intelligence makes it easy to understand the risk and the reason behind it with tailored scoring models + *and comprehensive reason codes. + */ +export default class IntelligenceClient extends RestClient { + constructor(requestWrapper, customerId, apiKey) { + var restEndpoint = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + var timeout = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 15000; + var userAgent = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; + super(requestWrapper, customerId, apiKey, restEndpoint, timeout, userAgent, contentType); + this.intelligenceResource = INTELLIGENCE_ENDPOINT_PATH; + } + + /*** + * Telesign Intelligence is like a credit check for digital profiles. + * + * You submit a phone number, IP, and email to the service, the individual + *identifiers are each evaluated, and then a score is returned telling you how risky + *that user is. + * + * You decide whether to proceed based on the score. + * + * See https://developer.telesign.com/enterprise/docs/intelligence-overview + *for detailed API documentation. + * + * @param callback: Callback method to handle response. + * @param requestBody: requestBody to be passed to Intelligence API + */ + intelligence(callback, requestBody) { + this.execute(callback, "POST", this.intelligenceResource, requestBody, AuthMethodNames.BASIC); + } +} \ No newline at end of file diff --git a/dist/esm/MessagingClient.js b/dist/esm/MessagingClient.js new file mode 100644 index 0000000..1723c85 --- /dev/null +++ b/dist/esm/MessagingClient.js @@ -0,0 +1,47 @@ +import RestClient from "./RestClient"; + +/*** + * TeleSign's Messaging API allows you to easily send SMS messages. You can send alerts, + * reminders, and notifications, or you can send verification messages containing + * one-time passcodes ( OTP ). + */ +export default class MessagingClient extends RestClient { + constructor(requestWrapper, customerId, apiKey) { + var restEndpoint = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + var timeout = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 15000; + var userAgent = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; + super(requestWrapper, customerId, apiKey, restEndpoint, timeout, userAgent); + this.messaging_resource = "/v1/messaging"; + this.messaging_status_resource = "/v1/messaging/"; + } + + /*** + * Send a message to the target phoneNumber. + * + * See https://developer.telesign.com/docs/messaging-api for detailed API documentation. + * + * @param callback: Callback method to handle response. + * @param phoneNumber: Phone number to call + * @param message: Text of the message to be sent to the end user. + * @param messageType: This parameter specifies the traffic type being sent in the message. + * transaction. + */ + message(callback, phoneNumber, message, messageType) { + var params = { + phone_number: phoneNumber, + message: message, + message_type: messageType + }; + this.execute(callback, "POST", this.messaging_resource, params); + } + + /*** + * Get status of message transaction. + * + * @param callback: Callback method to handle the response. + * @param referenceId: Reference ID received in the response of message. + */ + status(callback, referenceId) { + this.execute(callback, "GET", this.messaging_status_resource + referenceId, null); + } +} \ No newline at end of file diff --git a/dist/esm/PhoneIDClient.js b/dist/esm/PhoneIDClient.js new file mode 100644 index 0000000..b732771 --- /dev/null +++ b/dist/esm/PhoneIDClient.js @@ -0,0 +1,33 @@ +import RestClient from "./RestClient"; + +/*** + * A set of APIs that deliver deep phone number data attributes that help optimize the end user + * verification process and evaluate risk. + */ +export default class PhoneIDClient extends RestClient { + constructor(requestWrapper, customerId, apiKey) { + var restEndpoint = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + var timeout = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 15000; + var useragent = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; + super(requestWrapper, customerId, apiKey, restEndpoint, timeout, useragent); + this.phoneid_resource = "/v1/phoneid/"; + this.contentType = "application/json"; + } + + /*** + * The PhoneID API provides a cleansed phone number, phone type, and telecom carrier + * information to determine the best communication method - SMS or voice. + * + * See https://developer.telesign.com/docs/phoneid-api for detailed API documentation. + * + * @param callback: Callback method to handle response. + * @param phoneNumber: Phone number to call + * @param accountLifecycleEvent: (Optional) Indicates the phase in lifecycle for the + * transaction. + * @param originatingIP: IP address of request origination host + */ + phoneID(callback, phoneNumber) { + var params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + this.execute(callback, "POST", this.phoneid_resource + encodeURI(phoneNumber), params); + } +} \ No newline at end of file diff --git a/dist/esm/RequestWrapper.js b/dist/esm/RequestWrapper.js new file mode 100644 index 0000000..7f1ce53 --- /dev/null +++ b/dist/esm/RequestWrapper.js @@ -0,0 +1,92 @@ +function __transformExtension(filepath, extMapping) { + if (!filepath.startsWith('./') && !filepath.startsWith('../')) { + // Package import + return filepath; + } + var idx = filepath.lastIndexOf('.'); + if (idx === -1 || filepath.includes('/', idx)) { + // No extension + var newExt = extMapping['']; + if (newExt) { + return filepath + newExt; + } + return filepath; + } + for (var [origExt, _newExt] of Object.entries(extMapping).sort((a, b) => b[0].length - a[0].length)) { + if (filepath.endsWith(origExt)) { + return filepath.slice(0, -origExt.length) + _newExt; + } + } + return filepath; +} +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +export class RequestWrapper { + request(options, callback) { + throw new Error('makeRequest method must be implemented.'); + } +} +var handleResponse = (response, callback) => { + var res = { + status: response.status, + headers: response.headers, + bodyStr: JSON.stringify(response) + }; + callback(null, res, res.bodyStr); +}; +var handleError = (error, callback) => { + callback(error, null, error); +}; +function fetchWithTimeout(_x, _x2) { + return _fetchWithTimeout.apply(this, arguments); +} +function _fetchWithTimeout() { + _fetchWithTimeout = _asyncToGenerator(function* (url, options) { + /** @type {any} */ + var fetch = (typeof window !== 'undefined' ? window : global).fetch || null; + if (!fetch) { + fetch = yield import(__transformExtension('node-fetch', { + ".mjs": "" + })).then(m => { + var _m$default; + return (_m$default = m.default) !== null && _m$default !== void 0 ? _m$default : m; + }); + } + return yield Promise.race([fetch(url, options), new Promise((_, reject) => setTimeout(() => reject({ + code: 408, + message: 'Timeout' + }), options.timeout))]); + }); + return _fetchWithTimeout.apply(this, arguments); +} +export class FetchRequestWrapper extends RequestWrapper { + request(options, callback) { + switch (options.method) { + case 'POST': + fetchWithTimeout(options.url, { + method: options.method, + headers: options.headers, + body: options.body, + timeout: options.timeout + }).then(response => response.json()).then(data => handleResponse(data, callback)).catch(error => handleError(error, callback)); + break; + case 'PUT': + fetchWithTimeout(options.url, { + method: options.method, + headers: options.headers, + body: options.body, + timeout: options.timeout + }).then(response => response.json()).then(data => handleResponse(data, callback)).catch(error => handleError(error, callback)); + break; + case 'GET': + fetchWithTimeout(options.url, { + method: options.method, + headers: options.headers, + timeout: options.timeout + }).then(response => response.json()).then(data => handleResponse(data, callback)).catch(error => handleError(error, callback)); + break; + default: + console.error('Method: ' + options.method + ' not supported!'); + } + } +} \ No newline at end of file diff --git a/dist/esm/RestClient.js b/dist/esm/RestClient.js new file mode 100644 index 0000000..31d5c90 --- /dev/null +++ b/dist/esm/RestClient.js @@ -0,0 +1,172 @@ +import crypto from 'crypto'; +import { AuthMethodNames } from "./Constants"; +import { getInstalledVersion } from "./Util"; + +/*** + * The TeleSign RestClient is a generic HTTP REST client that can be extended to make + * requests against any of TeleSign's REST API endpoints. + * + * See https://developer.telesign.com for detailed API documentation. + */ +export default class RestClient { + constructor(requestWrapper, customerId, apiKey) { + var restEndpoint = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "https://rest-api.telesign.com"; + var timeout = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 15000; + var userAgent = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; + var source = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : "node_telesign"; + var sdkVersionOrigin = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : null; + var sdkVersionDependency = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : null; + var contentType = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : "application/x-www-form-urlencoded"; + this.requestWrapper = requestWrapper; + this.customerId = customerId; + this.apiKey = apiKey; + this.restEndpoint = restEndpoint === null ? "https://rest-api.telesign.com" : restEndpoint; + this.timeout = timeout; + this.contentType = contentType; + var currentVersionSdk = sdkVersionOrigin || getInstalledVersion(); + this.userAgent = "TeleSignSDK/ECMAScript-Node" + " ".concat(process.arch) + "/".concat(process.platform) + " ".concat(process.release.name) + "/".concat(process.version) // Generates a Node useragent - helpful in diagnosing errors + + " OriginatingSDK/".concat(source) + " SDKVersion/".concat(currentVersionSdk) + (source !== "node_telesign" ? " DependencySDKVersion/".concat(sdkVersionDependency) : ""); + } + + /*** + * Generates the TeleSign REST API headers used to authenticate requests. + * + * Creates the canonicalized stringToSign and generates the HMAC signature. This is used to + * authenticate requests against the TeleSign REST API. + * + * See https://developer.telesign.com/docs/authentication for detailed API documentation. + * + * @param customerId: Your account customerId. + * @param apiKey: Your account apiKey. + * @param methodName: The HTTP method name of the request as a upper case string, should be one + * of 'POST', 'GET', 'PUT' or 'DELETE'. + * @param resource: The partial resource URI to perform the request against, as a string. + * @param urlEncodedFields: HTTP body parameters to perform the HTTP request with, must be a + * urlencoded string. + * @param date: The date and time of the request formatted in rfc 2616, as a string. + * @param nonce: A unique cryptographic nonce for the request, as a string. + * @param userAgent: (optional) User Agent associated with the request, as a string. + * @param authMethod : (optional) Authentication type. For ex: Basic, HMAC etc + * @returns headers: {{Authorization: string, Date: *, Content-Type: string, + * x-ts-auth-method: string, x-ts-nonce: *}} + */ + static generateTeleSignHeaders(customerId, apiKey, methodName, resource, contentType, encodedFields) { + var date = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null; + var nonce = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : null; + var userAgent = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : null; + var authMethod = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : null; + return function (contentType, authMethod) { + if (date == null) { + date = new Date().toUTCString(); + } + if (nonce == null) { + nonce = crypto.randomUUID(); // generates a Random NONCE (Number Used Only Once) + } + var contentType = methodName == "POST" || methodName == "PUT" ? contentType : ""; + var authMethod = authMethod != null ? authMethod : AuthMethodNames.HMAC_SHA256; + var urlencoded = ""; + if (encodedFields != null && encodedFields.length > 0) { + urlencoded = "\n" + encodedFields; + } + /** @type {any} */ + var stringToSignBuilder = methodName + "\n" + contentType + "\n" + date + "\n" + "x-ts-auth-method:" + authMethod + "\n" + "x-ts-nonce:" + nonce + urlencoded + "\n" + resource; + if (authMethod === AuthMethodNames.BASIC) { + var authorization = "Basic " + Buffer.from(customerId + ":" + apiKey).toString('base64'); + } else { + var signedStrUTF8 = stringToSignBuilder.toString('utf8'); + var decodedAPIKey = Buffer.from(apiKey, 'base64'); + + /** @type {any} */ + var jsSignature = crypto.createHmac("sha256", decodedAPIKey).update(signedStrUTF8).digest("base64"); + jsSignature = jsSignature.toString('utf8'); + // console.log("js Signature: " + jsSignature); + + var authorization = "TSA " + customerId + ":" + jsSignature; + } + var headers = { + "Authorization": authorization, + "Date": date, + "Content-Type": contentType, + "x-ts-auth-method": authMethod, + "x-ts-nonce": nonce + }; + if (userAgent != null) headers["User-Agent"] = userAgent; + return headers; + }(contentType, authMethod); + } // method generateTeleSignHeaders + + /*** + * Generic TeleSign REST API request handler. + * + * @param callback: Callback method to handle response. + * @param methodName: The HTTP method name, as an upper case string. + * @param resource: The partial resource URI to perform the request against, as a string. + * @param authMethod: (optional) Authentication type. For ex: Basic, HMAC etc + * @param params: Body params to perform the HTTP request with, as a dictionary. + */ + execute(callback, methodName, resource) { + var params = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + var authMethod = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null; + var nonce = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; + var date = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null; + var telesignURL = this.restEndpoint + resource; + var bodyData = this.contentType == "application/json" ? "{}" : null; + if (methodName == "POST" || methodName == "PUT") { + if (params != null && Object.keys(params).length > 0) { + if (this.contentType == "application/x-www-form-urlencoded") { + var urlSearchParams = new URLSearchParams(params); + bodyData = urlSearchParams.toString(); + } else { + bodyData = JSON.stringify(params); + } + } + } else { + // GET method + if (params != null) { + var url = new URL(this.restEndpoint + resource); + Object.keys(params).forEach(key => url.searchParams.append(key, params[key])); + telesignURL = url.toString(); + } else { + telesignURL = new URL(this.restEndpoint + resource).toString(); + } + } + var headers = RestClient.generateTeleSignHeaders(this.customerId, this.apiKey, methodName, resource, this.contentType, bodyData, date !== null ? date : null, nonce, this.userAgent, authMethod); + var requestParams = { + headers: headers, + url: telesignURL, + method: methodName, + timeout: this.timeout + }; + if (bodyData != null) { + requestParams.body = bodyData; + } + this.requestWrapper.request(requestParams, function (err, res, bodyStr) { + if (err) { + console.error("FATAL ERROR: ".concat(date !== null ? date : new Date()) + " Problems contacting Telesign Servers. Check your internet connection."); + if (callback) { + callback(err, bodyStr); + } + } + if (res) { + var body = JSON.parse(bodyStr); + if (callback) { + callback(err, body); + } + } + }); + } + + /** + * @param {string} restEndpoint + */ + setRestEndpoint(restEndpoint) { + this.restEndpoint = restEndpoint; + } + + /** + * @param {string} contentType + */ + setContentType(contentType) { + this.contentType = contentType; + } +} \ No newline at end of file diff --git a/dist/esm/ScoreClient.js b/dist/esm/ScoreClient.js new file mode 100644 index 0000000..b05570d --- /dev/null +++ b/dist/esm/ScoreClient.js @@ -0,0 +1,58 @@ +import RestClient from "./RestClient"; + +/*** + * Score provides risk information about a specified phone number. + */ +export default class ScoreClient extends RestClient { + constructor(requestWrapper, customerId, apiKey) { + var restEndpoint = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + var timeout = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 15000; + var userAgent = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; + super(requestWrapper, customerId, apiKey, restEndpoint, timeout, userAgent); + this.scoreResource = "/v1/score/"; + } + + /*** + * Score is an API that delivers reputation scoring based on phone number intelligence, + * traffic patterns, machine learning, and a global data consortium. + * + * See https://developer.telesign.com/docs/score-api for detailed API documentation. + * + * @param callback: Callback method to handle response. + * @param phoneNumber: Phone number for which to check score + * @param accountLifecycleEvent: Indicate what phase of the lifecycle you are in when you + * send a transaction. + * @param originatingIP: (Optional) End user's IP address. + * @param deviceId: (Optional) End user’s device identifier. + * @param accountId: (Optional) End user’s account id + * @param emailAddress: (Optional) End user’s email address + * @param requestRiskInsights: (Optional) Boolean value of true, false or null for reason codes + * ONLY SET IF Score 2.0 requests is enabled, confirm with your Telesign representative + */ + score(callback, phoneNumber, accountLifecycleEvent) { + var originatingIP = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + var deviceId = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null; + var accountId = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; + var emailAddress = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null; + var requestRiskInsights = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : null; + var params = { + account_lifecycle_event: accountLifecycleEvent + }; + if (originatingIP != null) { + params.originating_ip = originatingIP; + } + if (deviceId != null) { + params.device_id = deviceId; + } + if (accountId != null) { + params.account_id = accountId; + } + if (emailAddress != null) { + params.email_address = emailAddress; + } + if (requestRiskInsights != null) { + params.request_risk_insights = requestRiskInsights; + } + this.execute(callback, "POST", this.scoreResource + encodeURI(phoneNumber), params); + } +} \ No newline at end of file diff --git a/dist/esm/TeleSign.js b/dist/esm/TeleSign.js new file mode 100644 index 0000000..2546b78 --- /dev/null +++ b/dist/esm/TeleSign.js @@ -0,0 +1,27 @@ +import RestClient from "./RestClient"; +import MessagingClient from "./MessagingClient"; +import ScoreClient from "./ScoreClient"; +import PhoneIDClient from "./PhoneIDClient"; +import VoiceClient from "./VoiceClient"; +import AppVerifyClient from "./AppVerifyClient"; +import IntelligenceClient from "./IntelligenceClient"; +import { FetchRequestWrapper } from "./RequestWrapper"; +export default class TeleSign { + constructor(customerId, apiKey) { + var restEndpoint = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "https://rest-api.telesign.com"; + var timeout = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 15000; + var useragent = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null; + var source = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : "node_telesign"; + var sdkVersionOrigin = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null; + var sdkVersionDependency = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : null; + var requestWrapper = new FetchRequestWrapper(); + this.rest = new RestClient(requestWrapper, customerId, apiKey, restEndpoint, timeout, useragent, source, sdkVersionOrigin, sdkVersionDependency); + this.sms = new MessagingClient(requestWrapper, customerId, apiKey, restEndpoint, timeout, useragent); + this.voice = new VoiceClient(requestWrapper, customerId, apiKey, restEndpoint, timeout, useragent); + this.score = new ScoreClient(requestWrapper, customerId, apiKey, restEndpoint, timeout, useragent); + this.phoneid = new PhoneIDClient(requestWrapper, customerId, apiKey, restEndpoint, timeout, useragent); + this.appverify = new AppVerifyClient(requestWrapper, customerId, apiKey, restEndpoint, timeout, useragent); + this.intelligence = new IntelligenceClient(requestWrapper, customerId, apiKey, restEndpoint, timeout, useragent); + } +} +; \ No newline at end of file diff --git a/dist/esm/Util.js b/dist/esm/Util.js new file mode 100644 index 0000000..b654e94 --- /dev/null +++ b/dist/esm/Util.js @@ -0,0 +1,4 @@ +import packageData from "../../package.json" assert { type: 'json' }; +export function getInstalledVersion() { + return packageData.version; +} \ No newline at end of file diff --git a/dist/esm/VoiceClient.js b/dist/esm/VoiceClient.js new file mode 100644 index 0000000..c026d7b --- /dev/null +++ b/dist/esm/VoiceClient.js @@ -0,0 +1,71 @@ +import RestClient from "./RestClient"; + +/*** + * TeleSign's Voice API allows you to easily send voice messages. You can send alerts, + * reminders, and notifications, or you can send verification messages containing time-based, + * one-time passcodes (TOTP). + */ +export default class VoiceClient extends RestClient { + constructor(requestWrapper, customerId, apiKey) { + var restEndpoint = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + var timeout = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 15000; + var useragent = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; + super(requestWrapper, customerId, apiKey, restEndpoint, timeout, useragent); + this.voice_resource = "/v1/voice"; + this.voice_status_resource = "/v1/voice/"; + } + + /*** + * Send a voice callto the target phoneNumber. + * + * See https://developer.telesign.com/docs/voice-api for detailed API documentation. + * + * @param callback: Callback method to handle response. + * @param phoneNumber: Phone number to call + * @param message: Text of the message to be converted to voice on call to the end + * user. [max 2000 code points] + * @param messageType: This parameter specifies the traffic type being sent in the message. + * @param voice: The voice parameter allows you to specify a voice to be used to speak your + * text to speech message. + * @param callbackURL: (Optional) URL of the callback server you would like to receive updates + * on. + * @param accountLifecycleEvent: (Optional) Indicates the phase in lifecycle for the + * transaction. + * @param originatingIP: (Optional) End user's IP address. + */ + call(callback, phoneNumber, message, messageType) { + var voice = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null; + var callbackURL = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; + var accountLifecycleEvent = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null; + var originatingIP = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : null; + var params = { + phone_number: phoneNumber, + message: message, + message_type: messageType + }; + if (voice != null) { + params.voice = voice; + } + if (callbackURL != null) { + params.callbackURL = callbackURL; + } + if (accountLifecycleEvent != null) { + params.account_lifecycle_event = accountLifecycleEvent; + } + if (originatingIP != null) { + params.originating_ip = originatingIP; + } + this.execute(callback, "POST", this.voice_resource, params); + } + + /*** + * Get status of voice call transaction. + * + * @param callback: Callback method to handle the response. + * @param referenceId: Reference ID received in the response of call. + */ + status(callback, referenceId) { + var status_resource = this.voice_status_resource + referenceId; + this.execute(callback, "GET", status_resource); + } +} \ No newline at end of file diff --git a/dist/types/AppVerifyClient.d.ts b/dist/types/AppVerifyClient.d.ts new file mode 100644 index 0000000..427f191 --- /dev/null +++ b/dist/types/AppVerifyClient.d.ts @@ -0,0 +1,16 @@ +/*** + * App Verify is a secure, lightweight SDK that integrates a frictionless user verification + * process into existing native mobile applications. + */ +export default class AppVerifyClient extends RestClient { + constructor(requestWrapper: any, customerId: any, apiKey: any, restEndpoint?: any, timeout?: number, userAgent?: any); + appverify_resource: string; + /*** + * Get status of app verification transaction. + * + * @param callback: Callback method to handle the response. + * @param externalId: External ID (xid) used in the JWT token during verification. + */ + status(callback: any, externalId: any): void; +} +import RestClient from './RestClient'; diff --git a/dist/types/Constants.d.ts b/dist/types/Constants.d.ts new file mode 100644 index 0000000..a6aebca --- /dev/null +++ b/dist/types/Constants.d.ts @@ -0,0 +1,4 @@ +export namespace AuthMethodNames { + let BASIC: string; + let HMAC_SHA256: string; +} diff --git a/dist/types/IntelligenceClient.d.ts b/dist/types/IntelligenceClient.d.ts new file mode 100644 index 0000000..261ef55 --- /dev/null +++ b/dist/types/IntelligenceClient.d.ts @@ -0,0 +1,27 @@ +/*** + * It is critical today to evaluate fraud risk throughout the entire customer journey. + * + * Telesign Intelligence makes it easy to understand the risk and the reason behind it with tailored scoring models + *and comprehensive reason codes. + */ +export default class IntelligenceClient extends RestClient { + constructor(requestWrapper: any, customerId: any, apiKey: any, restEndpoint?: any, timeout?: number, userAgent?: any); + intelligenceResource: string; + /*** + * Telesign Intelligence is like a credit check for digital profiles. + * + * You submit a phone number, IP, and email to the service, the individual + *identifiers are each evaluated, and then a score is returned telling you how risky + *that user is. + * + * You decide whether to proceed based on the score. + * + * See https://developer.telesign.com/enterprise/docs/intelligence-overview + *for detailed API documentation. + * + * @param callback: Callback method to handle response. + * @param requestBody: requestBody to be passed to Intelligence API + */ + intelligence(callback: any, requestBody: any): void; +} +import RestClient from './RestClient'; diff --git a/dist/types/MessagingClient.d.ts b/dist/types/MessagingClient.d.ts new file mode 100644 index 0000000..cd943c3 --- /dev/null +++ b/dist/types/MessagingClient.d.ts @@ -0,0 +1,30 @@ +/*** + * TeleSign's Messaging API allows you to easily send SMS messages. You can send alerts, + * reminders, and notifications, or you can send verification messages containing + * one-time passcodes ( OTP ). + */ +export default class MessagingClient extends RestClient { + constructor(requestWrapper: any, customerId: any, apiKey: any, restEndpoint?: any, timeout?: number, userAgent?: any); + messaging_resource: string; + messaging_status_resource: string; + /*** + * Send a message to the target phoneNumber. + * + * See https://developer.telesign.com/docs/messaging-api for detailed API documentation. + * + * @param callback: Callback method to handle response. + * @param phoneNumber: Phone number to call + * @param message: Text of the message to be sent to the end user. + * @param messageType: This parameter specifies the traffic type being sent in the message. + * transaction. + */ + message(callback: any, phoneNumber: any, message: any, messageType: any): void; + /*** + * Get status of message transaction. + * + * @param callback: Callback method to handle the response. + * @param referenceId: Reference ID received in the response of message. + */ + status(callback: any, referenceId: any): void; +} +import RestClient from './RestClient'; diff --git a/dist/types/PhoneIDClient.d.ts b/dist/types/PhoneIDClient.d.ts new file mode 100644 index 0000000..435fb28 --- /dev/null +++ b/dist/types/PhoneIDClient.d.ts @@ -0,0 +1,22 @@ +/*** + * A set of APIs that deliver deep phone number data attributes that help optimize the end user + * verification process and evaluate risk. + */ +export default class PhoneIDClient extends RestClient { + constructor(requestWrapper: any, customerId: any, apiKey: any, restEndpoint?: any, timeout?: number, useragent?: any); + phoneid_resource: string; + /*** + * The PhoneID API provides a cleansed phone number, phone type, and telecom carrier + * information to determine the best communication method - SMS or voice. + * + * See https://developer.telesign.com/docs/phoneid-api for detailed API documentation. + * + * @param callback: Callback method to handle response. + * @param phoneNumber: Phone number to call + * @param accountLifecycleEvent: (Optional) Indicates the phase in lifecycle for the + * transaction. + * @param originatingIP: IP address of request origination host + */ + phoneID(callback: any, phoneNumber: any, params?: any): void; +} +import RestClient from './RestClient'; diff --git a/dist/types/RequestWrapper.d.ts b/dist/types/RequestWrapper.d.ts new file mode 100644 index 0000000..aa482e5 --- /dev/null +++ b/dist/types/RequestWrapper.d.ts @@ -0,0 +1,5 @@ +export class RequestWrapper { + request(options: any, callback: any): void; +} +export class FetchRequestWrapper extends RequestWrapper { +} diff --git a/dist/types/RestClient.d.ts b/dist/types/RestClient.d.ts new file mode 100644 index 0000000..dc7e13e --- /dev/null +++ b/dist/types/RestClient.d.ts @@ -0,0 +1,63 @@ +/*** + * The TeleSign RestClient is a generic HTTP REST client that can be extended to make + * requests against any of TeleSign's REST API endpoints. + * + * See https://developer.telesign.com for detailed API documentation. + */ +export default class RestClient { + /*** + * Generates the TeleSign REST API headers used to authenticate requests. + * + * Creates the canonicalized stringToSign and generates the HMAC signature. This is used to + * authenticate requests against the TeleSign REST API. + * + * See https://developer.telesign.com/docs/authentication for detailed API documentation. + * + * @param customerId: Your account customerId. + * @param apiKey: Your account apiKey. + * @param methodName: The HTTP method name of the request as a upper case string, should be one + * of 'POST', 'GET', 'PUT' or 'DELETE'. + * @param resource: The partial resource URI to perform the request against, as a string. + * @param urlEncodedFields: HTTP body parameters to perform the HTTP request with, must be a + * urlencoded string. + * @param date: The date and time of the request formatted in rfc 2616, as a string. + * @param nonce: A unique cryptographic nonce for the request, as a string. + * @param userAgent: (optional) User Agent associated with the request, as a string. + * @param authMethod : (optional) Authentication type. For ex: Basic, HMAC etc + * @returns headers: {{Authorization: string, Date: *, Content-Type: string, + * x-ts-auth-method: string, x-ts-nonce: *}} + */ + static generateTeleSignHeaders(customerId: any, apiKey: any, methodName: any, resource: any, contentType: any, encodedFields: any, date?: any, nonce?: any, userAgent?: any, authMethod?: any): { + Authorization: string; + Date: any; + "Content-Type": any; + "x-ts-auth-method": any; + "x-ts-nonce": any; + }; + constructor(requestWrapper: any, customerId: any, apiKey: any, restEndpoint?: string, timeout?: number, userAgent?: any, source?: string, sdkVersionOrigin?: any, sdkVersionDependency?: any, contentType?: string); + requestWrapper: any; + customerId: any; + apiKey: any; + restEndpoint: string; + timeout: number; + contentType: string; + userAgent: string; + /*** + * Generic TeleSign REST API request handler. + * + * @param callback: Callback method to handle response. + * @param methodName: The HTTP method name, as an upper case string. + * @param resource: The partial resource URI to perform the request against, as a string. + * @param authMethod: (optional) Authentication type. For ex: Basic, HMAC etc + * @param params: Body params to perform the HTTP request with, as a dictionary. + */ + execute(callback: any, methodName: any, resource: any, params?: any, authMethod?: any, nonce?: any, date?: any): void; + /** + * @param {string} restEndpoint + */ + setRestEndpoint(restEndpoint: string): void; + /** + * @param {string} contentType + */ + setContentType(contentType: string): void; +} diff --git a/dist/types/ScoreClient.d.ts b/dist/types/ScoreClient.d.ts new file mode 100644 index 0000000..55a2103 --- /dev/null +++ b/dist/types/ScoreClient.d.ts @@ -0,0 +1,26 @@ +/*** + * Score provides risk information about a specified phone number. + */ +export default class ScoreClient extends RestClient { + constructor(requestWrapper: any, customerId: any, apiKey: any, restEndpoint?: any, timeout?: number, userAgent?: any); + scoreResource: string; + /*** + * Score is an API that delivers reputation scoring based on phone number intelligence, + * traffic patterns, machine learning, and a global data consortium. + * + * See https://developer.telesign.com/docs/score-api for detailed API documentation. + * + * @param callback: Callback method to handle response. + * @param phoneNumber: Phone number for which to check score + * @param accountLifecycleEvent: Indicate what phase of the lifecycle you are in when you + * send a transaction. + * @param originatingIP: (Optional) End user's IP address. + * @param deviceId: (Optional) End user’s device identifier. + * @param accountId: (Optional) End user’s account id + * @param emailAddress: (Optional) End user’s email address + * @param requestRiskInsights: (Optional) Boolean value of true, false or null for reason codes + * ONLY SET IF Score 2.0 requests is enabled, confirm with your Telesign representative + */ + score(callback: any, phoneNumber: any, accountLifecycleEvent: any, originatingIP?: any, deviceId?: any, accountId?: any, emailAddress?: any, requestRiskInsights?: any): void; +} +import RestClient from './RestClient'; diff --git a/dist/types/TeleSign.d.ts b/dist/types/TeleSign.d.ts new file mode 100644 index 0000000..72bcb79 --- /dev/null +++ b/dist/types/TeleSign.d.ts @@ -0,0 +1,17 @@ +export default class TeleSign { + constructor(customerId: any, apiKey: any, restEndpoint?: string, timeout?: number, useragent?: any, source?: string, sdkVersionOrigin?: any, sdkVersionDependency?: any); + rest: RestClient; + sms: MessagingClient; + voice: VoiceClient; + score: ScoreClient; + phoneid: PhoneIDClient; + appverify: AppVerifyClient; + intelligence: IntelligenceClient; +} +import RestClient from './RestClient'; +import MessagingClient from './MessagingClient'; +import VoiceClient from './VoiceClient'; +import ScoreClient from './ScoreClient'; +import PhoneIDClient from './PhoneIDClient'; +import AppVerifyClient from './AppVerifyClient'; +import IntelligenceClient from './IntelligenceClient'; diff --git a/dist/types/Util.d.ts b/dist/types/Util.d.ts new file mode 100644 index 0000000..efece09 --- /dev/null +++ b/dist/types/Util.d.ts @@ -0,0 +1 @@ +export function getInstalledVersion(): string; diff --git a/dist/types/VoiceClient.d.ts b/dist/types/VoiceClient.d.ts new file mode 100644 index 0000000..6c86bbd --- /dev/null +++ b/dist/types/VoiceClient.d.ts @@ -0,0 +1,37 @@ +/*** + * TeleSign's Voice API allows you to easily send voice messages. You can send alerts, + * reminders, and notifications, or you can send verification messages containing time-based, + * one-time passcodes (TOTP). + */ +export default class VoiceClient extends RestClient { + constructor(requestWrapper: any, customerId: any, apiKey: any, restEndpoint?: any, timeout?: number, useragent?: any); + voice_resource: string; + voice_status_resource: string; + /*** + * Send a voice callto the target phoneNumber. + * + * See https://developer.telesign.com/docs/voice-api for detailed API documentation. + * + * @param callback: Callback method to handle response. + * @param phoneNumber: Phone number to call + * @param message: Text of the message to be converted to voice on call to the end + * user. [max 2000 code points] + * @param messageType: This parameter specifies the traffic type being sent in the message. + * @param voice: The voice parameter allows you to specify a voice to be used to speak your + * text to speech message. + * @param callbackURL: (Optional) URL of the callback server you would like to receive updates + * on. + * @param accountLifecycleEvent: (Optional) Indicates the phase in lifecycle for the + * transaction. + * @param originatingIP: (Optional) End user's IP address. + */ + call(callback: any, phoneNumber: any, message: any, messageType: any, voice?: any, callbackURL?: any, accountLifecycleEvent?: any, originatingIP?: any): void; + /*** + * Get status of voice call transaction. + * + * @param callback: Callback method to handle the response. + * @param referenceId: Reference ID received in the response of call. + */ + status(callback: any, referenceId: any): void; +} +import RestClient from './RestClient'; diff --git a/examples/appverify/1_get_status_by_xid.js b/examples/appverify/1_get_status_by_xid.js index d65de3a..a59c41a 100644 --- a/examples/appverify/1_get_status_by_xid.js +++ b/examples/appverify/1_get_status_by_xid.js @@ -1,5 +1,5 @@ // note change this to the following if using npm package: require('telesignsdk); -const TeleSignSDK = require('../../src/TeleSign'); +const TeleSignSDK = require('../../dist/cjs/TeleSign'); //var TeleSignSDK = require('telesignsdk'); const customerId = "customer_id"; // Todo: find in portal.telesign.com diff --git a/examples/intelligence/1_get_risk_score_and_related_insights.js b/examples/intelligence/1_get_risk_score_and_related_insights.js index 2aa8cd6..7c9123e 100644 --- a/examples/intelligence/1_get_risk_score_and_related_insights.js +++ b/examples/intelligence/1_get_risk_score_and_related_insights.js @@ -1,4 +1,4 @@ -const TeleSignSDK = require('../../src/TeleSign'); +const TeleSignSDK = require('../../dist/cjs/TeleSign'); const customerId = "your_customer_id_2XT08ZA8-CA-4892-8888-ABXCAA8"; // Your customer id. Ensure your account has access to Intelligence product. const apiKey = "your_api_key"; // Your API key. diff --git a/examples/messaging/1_send_message.js b/examples/messaging/1_send_message.js index d5fecfc..b6fd968 100644 --- a/examples/messaging/1_send_message.js +++ b/examples/messaging/1_send_message.js @@ -1,6 +1,6 @@ // note change this to the following if using npm package: require('telesignsdk); -const TeleSignSDK = require('../../src/TeleSign'); -//var TeleSignSDK = require('telesignsdk'); +const TeleSignSDK = require('../../dist/cjs/TeleSign'); +//const TeleSignSDK = require('telesignsdk'); const customerId = "customer_id"; // Todo: find in portal.telesign.com const apiKey = "dGVzdCBhcGkga2V5IGZvciBzZGsgZXhhbXBsZXM="; // Todo: find in portal.telesign.com diff --git a/examples/messaging/2_send_message_with_verification_code.js b/examples/messaging/2_send_message_with_verification_code.js index d5cb5e6..c570b77 100644 --- a/examples/messaging/2_send_message_with_verification_code.js +++ b/examples/messaging/2_send_message_with_verification_code.js @@ -1,6 +1,6 @@ const readline = require('readline'); // note change this to the following if using npm package: require('telesignsdk); -const TeleSignSDK = require('../../src/TeleSign'); +const TeleSignSDK = require('../../dist/cjs/TeleSign'); //var TeleSignSDK = require('telesignsdk'); const customerId = "customer_id"; // Todo: find in portal.telesign.com @@ -54,4 +54,4 @@ function prompt(question, callback) { stdin.once('data', function (data) { callback(data.toString().trim()); }); -} \ No newline at end of file +} diff --git a/examples/phoneid/1_check_phone_type_to_block_voip.js b/examples/phoneid/1_check_phone_type_to_block_voip.js index 532e7d0..67a4155 100644 --- a/examples/phoneid/1_check_phone_type_to_block_voip.js +++ b/examples/phoneid/1_check_phone_type_to_block_voip.js @@ -1,5 +1,5 @@ // note change this to the following if using npm package: require('telesignsdk); -const TeleSignSDK = require('../../src/TeleSign'); +const TeleSignSDK = require('../../dist/cjs/TeleSign'); //var TeleSignSDK = require('telesignsdk'); const customerId = "customer_id"; // Todo: find in portal.telesign.com diff --git a/examples/phoneid/2_cleansing_updated_number.js b/examples/phoneid/2_cleansing_updated_number.js index 5116ab4..a7c4a81 100644 --- a/examples/phoneid/2_cleansing_updated_number.js +++ b/examples/phoneid/2_cleansing_updated_number.js @@ -1,5 +1,5 @@ // note change this to the following if using npm package: require('telesignsdk); -const TeleSignSDK = require('../../src/TeleSign'); +const TeleSignSDK = require('../../dist/cjs/TeleSign'); //var TeleSignSDK = require('telesignsdk'); const customerId = "customer_id"; // Todo: find in portal.telesign.com diff --git a/examples/score/1_check_phone_risk_level.js b/examples/score/1_check_phone_risk_level.js index 62eb1ef..71a0c3b 100644 --- a/examples/score/1_check_phone_risk_level.js +++ b/examples/score/1_check_phone_risk_level.js @@ -1,5 +1,5 @@ // note change this to the following if using npm package: require('telesignsdk); -const TeleSignSDK = require('../../src/TeleSign'); +const TeleSignSDK = require('../../dist/cjs/TeleSign'); //var TeleSignSDK = require('telesignsdk'); const customerId = "customer_id"; // Todo: find in portal.telesign.com diff --git a/examples/voice/1_send_voice_call.js b/examples/voice/1_send_voice_call.js index 7d24bf4..a238ff0 100644 --- a/examples/voice/1_send_voice_call.js +++ b/examples/voice/1_send_voice_call.js @@ -1,5 +1,5 @@ // note change this to the following if using npm package: require('telesignsdk); -const TeleSignSDK = require('../../src/TeleSign'); +const TeleSignSDK = require('../../dist/cjs/TeleSign'); //var TeleSignSDK = require('telesignsdk'); const customerId = "customer_id"; // Todo: find in portal.telesign.com diff --git a/examples/voice/2_send_voice_call_with_verification_code.js b/examples/voice/2_send_voice_call_with_verification_code.js index 6151b2a..2728247 100644 --- a/examples/voice/2_send_voice_call_with_verification_code.js +++ b/examples/voice/2_send_voice_call_with_verification_code.js @@ -1,5 +1,5 @@ // note change this to the following if using npm package: require('telesignsdk); -const TeleSignSDK = require('../../src/TeleSign'); +const TeleSignSDK = require('../../dist/cjs/TeleSign'); //var TeleSignSDK = require('telesignsdk'); const customerId = "customer_id"; // Todo: find in portal.telesign.com diff --git a/examples/voice/3_send_voice_call_french.js b/examples/voice/3_send_voice_call_french.js index 951b99a..be95fc4 100644 --- a/examples/voice/3_send_voice_call_french.js +++ b/examples/voice/3_send_voice_call_french.js @@ -1,5 +1,5 @@ // note change this to the following if using npm package: require('telesignsdk); -const TeleSignSDK = require('../../src/TeleSign'); +const TeleSignSDK = require('../../dist/cjs/TeleSign'); //var TeleSignSDK = require('telesignsdk'); const customerId = "customer_id"; // Todo: find in portal.telesign.com diff --git a/package.json b/package.json index f9798bd..fff61b0 100644 --- a/package.json +++ b/package.json @@ -1,17 +1,30 @@ { "name": "telesignsdk", - "version": "3.0.3", + "version": "4.0.0", "description": "Official TeleSign SDK for Rest APIs including Messaging (SMS), Score, PhoneID, Voice, and AppVerify", "repository": { "type": "git", "url": "https://github.com/TeleSign/node_telesign" }, - "main": "src/TeleSign.js", + "main": "dist/cjs/TeleSign.js", + "module": "dist/esm/TeleSign.js", + "types": "dist/types/TeleSign.d.ts", + "exports": { + ".": { + "require": "./dist/cjs/TeleSign.js", + "import": "./dist/esm/TeleSign.js" + } + }, "scripts": { - "test": "node ./test/test.suite.js" + "test": "node test/test.suite.mjs", + "build:cjs": "babel src --out-dir dist/cjs --extensions \".js,.mjs\" --config-file ./babel.config.cjs.json ", + "build:esm": "babel src --out-dir dist/esm --extensions \".js,.mjs\" --config-file ./babel.config.esm.json", + "build:types": "tsc", + "build:fix-file": "mv -f dist/src dist/types && find dist/types -name \"*.d.mts\" -exec sh -c 'mv \"$0\" \"${0%.d.mts}.d.ts\"' {} \\; && find dist/types -name \"*.d.ts\" -exec sed -i 's/\\.mjs//g' {} \\;", + "build": "rm -rf dist && npm run build:cjs && npm run build:esm && npm run build:types && npm run build:fix-file" }, - "dependencies": { - "node-fetch": "^2.7.0" + "peerDependencies": { + "node-fetch": "^2.6.0 || ^3.0.0" }, "keywords": [ "Telesign", @@ -31,5 +44,16 @@ ], "author": "TeleSign Corp.", "email": "sdk@telesign.com", - "license": "MIT" + "license": "MIT", + "devDependencies": { + "@babel/cli": "^7.26.4", + "@babel/core": "^7.26.0", + "@babel/plugin-syntax-import-assertions": "^7.26.0", + "@babel/preset-env": "^7.26.0", + "@types/node": "^22.10.7", + "@types/node-fetch": "^2.6.12", + "babel-plugin-add-module-exports": "^1.0.4", + "babel-plugin-replace-import-extension": "^1.1.4", + "typescript": "^5.7.3" + } } diff --git a/src/AppVerifyClient.js b/src/AppVerifyClient.mjs similarity index 87% rename from src/AppVerifyClient.js rename to src/AppVerifyClient.mjs index d1524c3..6a32b1d 100644 --- a/src/AppVerifyClient.js +++ b/src/AppVerifyClient.mjs @@ -1,10 +1,10 @@ -const RestClient = require("./RestClient.js"); +import RestClient from './RestClient.mjs'; /*** * App Verify is a secure, lightweight SDK that integrates a frictionless user verification * process into existing native mobile applications. */ -class AppVerifyClient extends RestClient { +export default class AppVerifyClient extends RestClient { constructor(requestWrapper, customerId, @@ -27,5 +27,3 @@ class AppVerifyClient extends RestClient { this.execute(callback, "GET", this.appverify_resource + externalId); } } - -module.exports = AppVerifyClient; diff --git a/src/Constants.js b/src/Constants.js deleted file mode 100644 index 5aff4ec..0000000 --- a/src/Constants.js +++ /dev/null @@ -1,8 +0,0 @@ -const AuthMethodNames = { - BASIC: "Basic", - HMAC_SHA256: "HMAC-SHA256" -}; - -module.exports = { - AuthMethodNames, -} \ No newline at end of file diff --git a/src/Constants.mjs b/src/Constants.mjs new file mode 100644 index 0000000..35f939b --- /dev/null +++ b/src/Constants.mjs @@ -0,0 +1,4 @@ +export const AuthMethodNames = { + BASIC: "Basic", + HMAC_SHA256: "HMAC-SHA256" +}; diff --git a/src/IntelligenceClient.js b/src/IntelligenceClient.mjs similarity index 85% rename from src/IntelligenceClient.js rename to src/IntelligenceClient.mjs index 7353960..632901a 100644 --- a/src/IntelligenceClient.js +++ b/src/IntelligenceClient.mjs @@ -1,5 +1,5 @@ -const RestClient = require('./RestClient.js'); -const Constants = require('./Constants.js'); +import RestClient from './RestClient.mjs'; +import { AuthMethodNames } from './Constants.mjs'; const INTELLIGENCE_ENDPOINT_PATH = "/intelligence"; const contentType = "application/json"; @@ -10,7 +10,7 @@ const contentType = "application/json"; * Telesign Intelligence makes it easy to understand the risk and the reason behind it with tailored scoring models *and comprehensive reason codes. */ -class IntelligenceClient extends RestClient { +export default class IntelligenceClient extends RestClient { constructor(requestWrapper, customerId, apiKey, @@ -39,9 +39,6 @@ class IntelligenceClient extends RestClient { * @param requestBody: requestBody to be passed to Intelligence API */ intelligence(callback, requestBody) { - this.execute(callback, "POST", this.intelligenceResource, requestBody, - Constants.AuthMethodNames.BASIC); + this.execute(callback, "POST", this.intelligenceResource, requestBody, AuthMethodNames.BASIC); } } - -module.exports = IntelligenceClient; diff --git a/src/MessagingClient.js b/src/MessagingClient.mjs similarity index 93% rename from src/MessagingClient.js rename to src/MessagingClient.mjs index 972b6c4..cb4fbc9 100644 --- a/src/MessagingClient.js +++ b/src/MessagingClient.mjs @@ -1,11 +1,11 @@ -const RestClient = require("./RestClient.js"); +import RestClient from './RestClient.mjs'; /*** * TeleSign's Messaging API allows you to easily send SMS messages. You can send alerts, * reminders, and notifications, or you can send verification messages containing * one-time passcodes ( OTP ). */ -class MessagingClient extends RestClient { +export default class MessagingClient extends RestClient { constructor(requestWrapper, customerId, @@ -52,5 +52,3 @@ class MessagingClient extends RestClient { null); } } - -module.exports = MessagingClient; diff --git a/src/PhoneIDClient.js b/src/PhoneIDClient.mjs similarity index 91% rename from src/PhoneIDClient.js rename to src/PhoneIDClient.mjs index 0ea110c..a1d0cdf 100644 --- a/src/PhoneIDClient.js +++ b/src/PhoneIDClient.mjs @@ -1,10 +1,10 @@ -const RestClient = require("./RestClient.js"); +import RestClient from './RestClient.mjs'; /*** * A set of APIs that deliver deep phone number data attributes that help optimize the end user * verification process and evaluate risk. */ -class PhoneIDClient extends RestClient { +export default class PhoneIDClient extends RestClient { constructor(requestWrapper, customerId, @@ -34,5 +34,3 @@ class PhoneIDClient extends RestClient { this.execute(callback, "POST", this.phoneid_resource + encodeURI(phoneNumber), params); } } - -module.exports = PhoneIDClient; diff --git a/src/RequestWrapper.js b/src/RequestWrapper.mjs similarity index 83% rename from src/RequestWrapper.js rename to src/RequestWrapper.mjs index a40f253..28941c3 100644 --- a/src/RequestWrapper.js +++ b/src/RequestWrapper.mjs @@ -1,4 +1,4 @@ -class RequestWrapper { +export class RequestWrapper { request(options, callback) { throw new Error('makeRequest method must be implemented.'); } @@ -17,15 +17,19 @@ const handleError = (error, callback) => { callback(error, null, error) }; -function fetchWithTimeout(url, options) { - const fetch = require('node-fetch'); - return Promise.race([ +async function fetchWithTimeout(url, options) { + /** @type {any} */ + let fetch = (typeof window !== 'undefined' ? window : global).fetch || null; + if (!fetch) { + fetch = await import('node-fetch').then(m => m.default ?? m); + } + return await Promise.race([ fetch(url, options), new Promise((_, reject) => setTimeout(() => reject({ code: 408, message: 'Timeout' }), options.timeout)) ]); } -class FetchRequestWrapper extends RequestWrapper { +export class FetchRequestWrapper extends RequestWrapper { request(options, callback) { switch (options.method) { @@ -66,8 +70,3 @@ class FetchRequestWrapper extends RequestWrapper { } } } - -module.exports = { - RequestWrapper, - FetchRequestWrapper -}; diff --git a/src/RestClient.js b/src/RestClient.mjs similarity index 86% rename from src/RestClient.js rename to src/RestClient.mjs index db2305b..f176674 100644 --- a/src/RestClient.js +++ b/src/RestClient.mjs @@ -1,6 +1,6 @@ -const crypto = require("crypto"); -const Constants = require('./Constants.js'); -const { getInstalledVersion } = require('./Util.js'); +import crypto from 'crypto'; +import { AuthMethodNames } from './Constants.mjs'; +import { getInstalledVersion } from './Util.mjs'; /*** * The TeleSign RestClient is a generic HTTP REST client that can be extended to make @@ -8,7 +8,7 @@ const { getInstalledVersion } = require('./Util.js'); * * See https://developer.telesign.com for detailed API documentation. */ -class RestClient { +export default class RestClient { constructor(requestWrapper, customerId, @@ -28,23 +28,14 @@ class RestClient { this.contentType = contentType ; const currentVersionSdk = sdkVersionOrigin || getInstalledVersion() - try { - if (userAgent === null) { - this.userAgent = `TeleSignSDK/ECMAScript-Node` - + ` ${process.arch}` - + `/${process.platform}` - + ` ${process.release.name}` - + `/${process.version}` // Generates a Node useragent - helpful in diagnosing errors - + ` OriginatingSDK/${source}` - + ` SDKVersion/${currentVersionSdk}` - + (source !== "node_telesign" ? ` DependencySDKVersion/${sdkVersionDependency}` : ``); - } - } - catch (err) { - this.userAgent = "TeleSignSDK/ECMAScript-Node v-UNKNOWN"; - console.error("WARNING: Trouble determining OS Specific information for user agent"); - } - + this.userAgent = `TeleSignSDK/ECMAScript-Node` + + ` ${process.arch}` + + `/${process.platform}` + + ` ${process.release.name}` + + `/${process.version}` // Generates a Node useragent - helpful in diagnosing errors + + ` OriginatingSDK/${source}` + + ` SDKVersion/${currentVersionSdk}` + + (source !== "node_telesign" ? ` DependencySDKVersion/${sdkVersionDependency}` : ``); } @@ -91,12 +82,13 @@ class RestClient { var contentType = (methodName == "POST" || methodName == "PUT") ? contentType : ""; - var authMethod = authMethod!=null ? authMethod: Constants.AuthMethodNames.HMAC_SHA256; + var authMethod = authMethod!=null ? authMethod: AuthMethodNames.HMAC_SHA256; var urlencoded = ""; if (encodedFields != null && encodedFields.length > 0) { urlencoded = "\n" + encodedFields; } + /** @type {any} */ var stringToSignBuilder = methodName + "\n" + contentType + "\n" + date + @@ -104,16 +96,18 @@ class RestClient { "\n" + "x-ts-nonce:" + nonce + urlencoded + "\n" + resource; - if(authMethod === Constants.AuthMethodNames.BASIC){ + if(authMethod === AuthMethodNames.BASIC){ var authorization = "Basic " + Buffer.from(customerId + ":" + apiKey).toString('base64'); }else{ var signedStrUTF8 = stringToSignBuilder.toString('utf8'); var decodedAPIKey = Buffer.from(apiKey, 'base64'); + /** @type {any} */ var jsSignature = crypto.createHmac("sha256", decodedAPIKey) .update(signedStrUTF8) .digest("base64") - .toString('utf8'); + ; + jsSignature = jsSignature.toString('utf8'); // console.log("js Signature: " + jsSignature); var authorization = "TSA " + customerId + ":" + jsSignature; @@ -175,7 +169,7 @@ class RestClient { nonce, this.userAgent, authMethod); - + var requestParams = { headers: headers, url: telesignURL, @@ -208,13 +202,17 @@ class RestClient { } + /** + * @param {string} restEndpoint + */ setRestEndpoint(restEndpoint) { this.restEndpoint = restEndpoint } + /** + * @param {string} contentType + */ setContentType(contentType) { this.contentType = contentType } } - -module.exports = RestClient; diff --git a/src/ScoreClient.js b/src/ScoreClient.mjs similarity index 95% rename from src/ScoreClient.js rename to src/ScoreClient.mjs index 1037c87..90e1492 100644 --- a/src/ScoreClient.js +++ b/src/ScoreClient.mjs @@ -1,9 +1,9 @@ -const RestClient = require('./RestClient.js'); +import RestClient from './RestClient.mjs'; /*** * Score provides risk information about a specified phone number. */ -class ScoreClient extends RestClient { +export default class ScoreClient extends RestClient { constructor(requestWrapper, customerId, apiKey, @@ -64,5 +64,3 @@ class ScoreClient extends RestClient { this.execute(callback, "POST", this.scoreResource + encodeURI(phoneNumber), params); } } - -module.exports = ScoreClient; diff --git a/src/TeleSign.js b/src/TeleSign.mjs similarity index 71% rename from src/TeleSign.js rename to src/TeleSign.mjs index 76515aa..7de2742 100644 --- a/src/TeleSign.js +++ b/src/TeleSign.mjs @@ -1,13 +1,13 @@ -const RestClient = require('./RestClient.js'); -const MessagingClient = require('./MessagingClient.js'); -const ScoreClient = require('./ScoreClient.js'); -const PhoneIDClient = require('./PhoneIDClient.js'); -const VoiceClient = require('./VoiceClient.js'); -const AppVerifyClient = require('./AppVerifyClient.js'); -const IntelligenceClient = require('./IntelligenceClient.js'); -const { FetchRequestWrapper } = require('./RequestWrapper') +import RestClient from './RestClient.mjs'; +import MessagingClient from './MessagingClient.mjs'; +import ScoreClient from './ScoreClient.mjs'; +import PhoneIDClient from './PhoneIDClient.mjs'; +import VoiceClient from './VoiceClient.mjs'; +import AppVerifyClient from './AppVerifyClient.mjs'; +import IntelligenceClient from './IntelligenceClient.mjs'; +import { FetchRequestWrapper } from './RequestWrapper.mjs'; -module.exports = class TeleSign { +export default class TeleSign { constructor(customerId, apiKey, restEndpoint = "https://rest-api.telesign.com", @@ -26,4 +26,4 @@ module.exports = class TeleSign { this.appverify = new AppVerifyClient(requestWrapper, customerId, apiKey, restEndpoint, timeout, useragent); this.intelligence = new IntelligenceClient(requestWrapper, customerId, apiKey, restEndpoint, timeout, useragent); } -}; \ No newline at end of file +}; diff --git a/src/Util.js b/src/Util.js deleted file mode 100644 index 46ce151..0000000 --- a/src/Util.js +++ /dev/null @@ -1,18 +0,0 @@ -const fs = require('fs'); -const path = require('path'); - -function getInstalledVersion() { - try { - const packageJsonPath = path.join(__dirname, '..', 'package.json') - const packageJson = fs.readFileSync(packageJsonPath, 'utf8'); - const packageData = JSON.parse(packageJson); - const version = packageData.version; - return version; - } catch (err) { - return null; - } -} - -module.exports = { - getInstalledVersion, -} \ No newline at end of file diff --git a/src/Util.mjs b/src/Util.mjs new file mode 100644 index 0000000..bc32bd1 --- /dev/null +++ b/src/Util.mjs @@ -0,0 +1,5 @@ +import packageData from '../package.json' assert { type: 'json' }; + +export function getInstalledVersion() { + return packageData.version; +} diff --git a/src/VoiceClient.js b/src/VoiceClient.mjs similarity index 95% rename from src/VoiceClient.js rename to src/VoiceClient.mjs index 5f30f3e..909a150 100644 --- a/src/VoiceClient.js +++ b/src/VoiceClient.mjs @@ -1,11 +1,11 @@ -const RestClient = require('./RestClient.js'); +import RestClient from './RestClient.mjs'; /*** * TeleSign's Voice API allows you to easily send voice messages. You can send alerts, * reminders, and notifications, or you can send verification messages containing time-based, * one-time passcodes (TOTP). */ -class VoiceClient extends RestClient { +export default class VoiceClient extends RestClient { constructor(requestWrapper, customerId, @@ -79,5 +79,3 @@ class VoiceClient extends RestClient { this.execute(callback, "GET", status_resource); } } - -module.exports = VoiceClient; diff --git a/test/RequestWrapper.test.js b/test/RequestWrapper.test.mjs similarity index 95% rename from test/RequestWrapper.test.js rename to test/RequestWrapper.test.mjs index 7f27c54..0d3d6c5 100644 --- a/test/RequestWrapper.test.js +++ b/test/RequestWrapper.test.mjs @@ -1,10 +1,8 @@ -const RestClient = require('../src/RestClient'); -const { FetchRequestWrapperMock } = require('./RequestWrapperMock'); -const { RequestWrapper, FetchRequestWrapper } = require('../src/RequestWrapper'); -const { test, it, expect, mockFunction, runTests } = require('./TestFramework'); +import {FetchRequestWrapper, RequestWrapper} from '../src/RequestWrapper.mjs'; +import {expect, it, mockFunction} from './TestFramework.mjs'; // RequestWrapper Client Tests ----------------------------- -async function requestWrapper() { +export async function requestWrapper() { const customerId = 'FFFFFFFF-EEEE-DDDD-1234-AB1234567890'; const apiKey = 'VGVzdCBLZXk='; const restEndpoint = 'https://rest-api.telesign.com'; @@ -218,5 +216,3 @@ async function requestWrapper() { } }); } - -module.exports = { requestWrapper }; diff --git a/test/RequestWrapperMock.js b/test/RequestWrapperMock.mjs similarity index 75% rename from test/RequestWrapperMock.js rename to test/RequestWrapperMock.mjs index e18f213..cc7f86f 100644 --- a/test/RequestWrapperMock.js +++ b/test/RequestWrapperMock.mjs @@ -1,6 +1,6 @@ -const { RequestWrapper } = require('../src/RequestWrapper'); +import { RequestWrapper } from '../src/RequestWrapper.mjs'; -class FetchRequestWrapperMock extends RequestWrapper { +export class FetchRequestWrapperMock extends RequestWrapper { constructor(mockResponse, mockError, responseBody, optionsCallback) { super(); this.mockResponse = mockResponse || null; @@ -15,12 +15,10 @@ class FetchRequestWrapperMock extends RequestWrapper { callback(this.mockError, null, this.responseBody); } else { // Simulate a successful response - if (this.optionsCallback) { + if (this.optionsCallback) { this.optionsCallback(options) } callback(null, this.mockResponse, JSON.stringify(this.responseBody)); } } } - -module.exports = FetchRequestWrapperMock; diff --git a/test/RestClient.test.js b/test/RestClient.test.mjs similarity index 94% rename from test/RestClient.test.js rename to test/RestClient.test.mjs index 84cd5f9..dd2dc62 100644 --- a/test/RestClient.test.js +++ b/test/RestClient.test.mjs @@ -1,19 +1,18 @@ -const RestClient = require('../src/RestClient'); -const Constants = require('../src/Constants'); -const querystring = require('querystring'); -const FetchRequestWrapperMock = require('./RequestWrapperMock'); -const TeleSignSDK = require('../src/TeleSign'); -const MessagingClient = require('../src/MessagingClient.js'); -const AppVerifyClient = require('../src/AppVerifyClient.js'); -const IntelligenceClient = require('../src/IntelligenceClient.js'); -const VoiceClient = require('../src/VoiceClient.js'); -const PhoneIDClient = require('../src/PhoneIDClient.js'); -const ScoreClient = require('../src/ScoreClient.js'); -const { test, it, expect, mockFunction, runTests } = require('./TestFramework'); +import RestClient from '../src/RestClient.mjs'; +import { AuthMethodNames } from '../src/Constants.mjs'; +import { FetchRequestWrapperMock } from './RequestWrapperMock.mjs'; +import TeleSignSDK from '../src/TeleSign.mjs'; +import MessagingClient from '../src/MessagingClient.mjs'; +import AppVerifyClient from '../src/AppVerifyClient.mjs'; +import IntelligenceClient from '../src/IntelligenceClient.mjs'; +import VoiceClient from '../src/VoiceClient.mjs'; +import PhoneIDClient from '../src/PhoneIDClient.mjs'; +import ScoreClient from '../src/ScoreClient.mjs'; +import { test, it, expect, mockFunction, runTests } from './TestFramework.mjs'; // REST Client Tests ----------------------------- -async function restClient() { +export async function restClient() { const customerId = 'FFFFFFFF-EEEE-DDDD-1234-AB1234567890'; const apiKey = 'VGVzdCBLZXk='; const restEndpoint = 'https://rest-api.telesign.com'; @@ -59,7 +58,7 @@ async function restClient() { it('should change the attribute restEndpoint', () => { const telesign = new RestClient(requestWrapper, customerId, apiKey); - + expect(telesign.restEndpoint).toEqual("https://rest-api.telesign.com"); const newRestEndpoint = "https://telesign.com"; @@ -93,18 +92,6 @@ async function restClient() { expect(rc.userAgent).toContain('OriginatingSDK/node_telesign'); }); - it('should return default userAgent on error', () => { - const originalJSONParse = JSON.parse; - JSON.parse = () => { - throw new Error('Test error'); - }; - - const rc = new RestClient(requestWrapper, customerId, apiKey); - - JSON.parse = originalJSONParse; - expect(rc.userAgent).toBe('TeleSignSDK/ECMAScript-Node v-UNKNOWN'); - }); - it('should generate headers for HMAC authentication', () => { const customerId = 'yourCustomerId'; const apiKey = 'yourApiKey'; @@ -134,7 +121,7 @@ async function restClient() { date, nonce, userAgent, - Constants.AuthMethodNames.HMAC_SHA256 + AuthMethodNames.HMAC_SHA256 ); expect(actualHeaders).toEqual(expectedHeaders); @@ -169,7 +156,7 @@ async function restClient() { date, nonce, userAgent, - Constants.AuthMethodNames.BASIC + AuthMethodNames.BASIC ); expect(actualHeaders).toEqual(expectedHeaders); @@ -212,8 +199,7 @@ async function restClient() { const resource = '/v1/resource'; const bodyParamsURLEncoded = 'test=param'; const contentType = "application/x-www-form-urlencoded"; - const expectedAuthorizationHeader = - 'TSA FFFFFFFF-EEEE-DDDD-1234-AB1234567890:vXw/XzywdhgfEG2/zWLaFp7oXmjLB8iJDMndvDbZMjk='; + const expectedAuthorizationHeader = 'TSA FFFFFFFF-EEEE-DDDD-1234-AB1234567890:vXw/XzywdhgfEG2/zWLaFp7oXmjLB8iJDMndvDbZMjk='; const actualHeaders = RestClient.generateTeleSignHeaders( customerId, @@ -239,8 +225,7 @@ async function restClient() { const resource = '/v1/resource'; const bodyParamsURLEncoded = 'test=param'; const contentType = "application/json"; - const expectedAuthorizationHeader = - 'Basic RkZGRkZGRkYtRUVFRS1ERERELTEyMzQtQUIxMjM0NTY3ODkwOlZHVnpkQ0JMWlhrPQ=='; + const expectedAuthorizationHeader = 'Basic RkZGRkZGRkYtRUVFRS1ERERELTEyMzQtQUIxMjM0NTY3ODkwOlZHVnpkQ0JMWlhrPQ=='; const actualHeaders = RestClient.generateTeleSignHeaders( customerId, @@ -252,7 +237,7 @@ async function restClient() { date, nonce, 'unit_test', - Constants.AuthMethodNames.BASIC + AuthMethodNames.BASIC ); expect(actualHeaders['Authorization']).toBe(expectedAuthorizationHeader); @@ -293,8 +278,7 @@ async function restClient() { const nonce = 'A1592C6F-E384-4CDB-BC42-C3AB970369E9'; const resource = '/v1/resource'; const contentType = "application/x-www-form-urlencoded"; - expectedAuthorizationHeader = - 'TSA FFFFFFFF-EEEE-DDDD-1234-AB1234567890:wscyrZZtA7kdXu0i4D5KXyDmBcwH52JF1feiEKp+ir0='; + const expectedAuthorizationHeader = 'TSA FFFFFFFF-EEEE-DDDD-1234-AB1234567890:wscyrZZtA7kdXu0i4D5KXyDmBcwH52JF1feiEKp+ir0='; const actualHeaders = RestClient.generateTeleSignHeaders( customerId, @@ -376,9 +360,9 @@ async function restClient() { const expectedResponse = { message: 'Successful response' } var optionsSent = null const requestWrapper = new FetchRequestWrapperMock(response, null, expectedResponse, (options) => optionsSent = options); - + const telesign = new RestClient(requestWrapper, 'customerId', 'apiKey'); - + const resource = '/test'; const params = { key1: 'value1', key2: 'value2' } const nonce = 'A1592C6F-E384-4CDB-BC42-C3AB970369E9'; @@ -480,7 +464,7 @@ async function restClient() { 'POST', '/v1/resource', jsonParams, - Constants.AuthMethodNames.HMAC_SHA256, + AuthMethodNames.HMAC_SHA256, nonce, date ); @@ -517,7 +501,7 @@ async function restClient() { 'PUT', '/v1/resource', jsonParams, - Constants.AuthMethodNames.HMAC_SHA256, + AuthMethodNames.HMAC_SHA256, nonce, date ); @@ -565,7 +549,7 @@ async function restClient() { 'PUT', '/v1/resource', jsonParams, - Constants.AuthMethodNames.HMAC_SHA256 + AuthMethodNames.HMAC_SHA256 ); }); @@ -598,7 +582,7 @@ async function restClient() { 'PUT', '/v1/resource', params, - Constants.AuthMethodNames.HMAC_SHA256 + AuthMethodNames.HMAC_SHA256 ); }); @@ -612,7 +596,7 @@ async function restClient() { telesign.rest.execute = mockFunction(); telesign.rest.execute(callback, "GET", "/resource/test"); - telesign.rest.execute(callback, "POST", "/resource/test", params = { 'mdr': 'beautiful' }); + telesign.rest.execute(callback, "POST", "/resource/test", { 'mdr': 'beautiful' }); }); // Product tests ------------------------- @@ -734,7 +718,7 @@ async function restClient() { telesign.intelligence.intelligence(callback, requestBody); - expect(telesign.intelligence.execute).toHaveBeenCalledWith(callback, "POST", "/intelligence", {}, Constants.AuthMethodNames.BASIC); + expect(telesign.intelligence.execute).toHaveBeenCalledWith(callback, "POST", "/intelligence", {}, AuthMethodNames.BASIC); expect(telesign.intelligence.execute).toHaveBeenCalledTimes(1); }); @@ -751,7 +735,7 @@ async function restClient() { expect(intelligenceClient.execute.mock.calls[0][1]).toBe("POST"); expect(intelligenceClient.execute.mock.calls[0][2]).toBe("/intelligence"); expect(intelligenceClient.execute.mock.calls[0][3]).toEqual({}); - expect(intelligenceClient.execute.mock.calls[0][4]).toEqual(Constants.AuthMethodNames.BASIC); + expect(intelligenceClient.execute.mock.calls[0][4]).toEqual(AuthMethodNames.BASIC); expect(intelligenceClient.execute).toHaveBeenCalledTimes(1); }); @@ -932,5 +916,3 @@ async function restClient() { console.error = originalConsoleError; } - -module.exports = { restClient }; diff --git a/test/TestFramework.js b/test/TestFramework.mjs similarity index 94% rename from test/TestFramework.js rename to test/TestFramework.mjs index a7b6d2f..354cc00 100644 --- a/test/TestFramework.js +++ b/test/TestFramework.mjs @@ -13,7 +13,7 @@ let failedCount = 0; let allTestsCompleted = false; -async function test(testDescription, testFunction) { +export async function test(testDescription, testFunction) { try { const result = testFunction(); if (result instanceof Promise) { @@ -40,11 +40,11 @@ async function test(testDescription, testFunction) { } } -async function it(testDescription, testFunction) { +export async function it(testDescription, testFunction) { await test(testDescription, testFunction); } -function mockFunction() { +export function mockFunction() { let callCount = 0; const mockFn = function (...args) { callCount++; @@ -62,7 +62,7 @@ function mockFunction() { return mockFn; } -function expect(value) { +export function expect(value) { const calledArgs = []; return { @@ -160,14 +160,13 @@ function printResult() { console.log(`${colors.bold}Tests: ${colors.green}${passedCount} passed${colors.reset}, ${colors.bold}${colors.red}${failedCount} failed${colors.reset}, ${colors.bold}${colors.white}${passedCount + failedCount} total${colors.reset}`); } -async function waitForTests() { +export async function waitForTests() { await new Promise(resolve => setTimeout(resolve, 0)); allTestsCompleted = true; } -async function runTests() { +export async function runTests() { await waitForTests(); printResult(); } -module.exports = { test, it, expect, mockFunction, waitForTests, runTests }; diff --git a/test/test.suite.js b/test/test.suite.js deleted file mode 100644 index 0b15d18..0000000 --- a/test/test.suite.js +++ /dev/null @@ -1,7 +0,0 @@ -const { restClient } = require('./RestClient.test.js'); -const { requestWrapper } = require('./RequestWrapper.test.js'); -const { runTests } = require('./TestFramework'); - -restClient(); -requestWrapper(); -runTests(); diff --git a/test/test.suite.mjs b/test/test.suite.mjs new file mode 100644 index 0000000..3640e74 --- /dev/null +++ b/test/test.suite.mjs @@ -0,0 +1,7 @@ +import { restClient } from './RestClient.test.mjs'; +import { requestWrapper } from './RequestWrapper.test.mjs'; +import { runTests } from './TestFramework.mjs'; + +restClient(); +requestWrapper(); +runTests(); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..fb4c5b7 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "moduleResolution": "node", + "lib": ["dom", "esnext"], + "declaration": true, + "declarationDir": "./dist", + "emitDeclarationOnly": true, + "allowJs": true, + "checkJs": true, + "outDir": "./dist", + "skipLibCheck": true, + "esModuleInterop": true, + "resolveJsonModule": true + }, + "include": ["src/**/*.mjs"], + "exclude": ["node_modules", "dist"] +}