UNPKG

ordercloud-javascript-sdk

Version:

The offical Javascript SDK for the Ordercloud ecommerce API

1,050 lines (1,028 loc) 1.33 MB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var axios = require('axios'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __awaiter(thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var Configuration = /** @class */ (function () { /** * @ignore * not part of public api, don't include in generated docs */ function Configuration() { this.defaultConfig = { baseApiUrl: 'https://api.ordercloud.io', apiVersion: 'v1', timeoutInMilliseconds: 60 * 1000, clientID: null, cookieOptions: { samesite: 'lax', secure: false, domain: null, prefix: 'ordercloud', path: '/', // accessible on any path in the domain }, }; this.config = cloneDeep(this.defaultConfig); this.Set = this.Set.bind(this); this.Get = this.Get.bind(this); } Configuration.prototype.Set = function (config) { this.config = __assign(__assign(__assign({}, this.defaultConfig), this.config), (config || {})); this.config.cookieOptions = __assign(__assign(__assign({}, this.defaultConfig.cookieOptions), this.config.cookieOptions), ((config === null || config === void 0 ? void 0 : config.cookieOptions) || {})); }; Configuration.prototype.Get = function () { return this.config; }; return Configuration; }()); // takes an object and creates a new one with same properties/values // useful so we don't mutate original object function cloneDeep(obj) { return JSON.parse(JSON.stringify(obj)); } var Configuration$1 = new Configuration(); var OrderCloudError = /** @class */ (function (_super) { __extends(OrderCloudError, _super); function OrderCloudError(ex) { var _this = this; var errors = safeParseErrors(ex); // extract ordercloud errors from response var firstError = errors === null || errors === void 0 ? void 0 : errors[0]; // most of the time there is just one error _this = _super.call(this, getMessage(ex, firstError)) || this; _this.isOrderCloudError = true; _this.errors = errors; _this.name = 'OrderCloudError'; _this.errorCode = getErrorCode(firstError); _this.status = ex.response.status; _this.statusText = ex.response.statusText; _this.response = ex.response; _this.request = ex.request; return _this; } return OrderCloudError; }(Error)); /** * @ignore * not part of public api, don't include in generated docs */ function safeParseErrors(ex) { var _a; try { var value = (_a = ex === null || ex === void 0 ? void 0 : ex.response) === null || _a === void 0 ? void 0 : _a.data; if (!value) { return []; } if (typeof value === 'object') { return value.Errors; } if (typeof value === 'string') { // axios sometimes returns a string, so we must deserialize it ourselves if (value && value.charCodeAt(0) === 65279) { // there seems to be a BOM character at the beginning // of this string that causes json parsing to fail value = value.substring(1); } var data = JSON.parse(value); return data.Errors; } return value; } catch (e) { return []; } } /** * @ignore * not part of public api, don't include in generated docs */ function getMessage(ex, error) { if (!error) { return ex.response.statusText; } switch (error.ErrorCode) { case 'NotFound': return "".concat(error.Data.ObjectType, " ").concat(error.Data.ObjectID, " not found"); default: return error.Message; } } /** * @ignore * not part of public api, don't include in generated docs */ function getErrorCode(error) { if (!error) { return 'OrderCloudError'; } return error.ErrorCode; } /** * @ignore * not part of public api, don't include in generated docs */ var CookieApi = /** @class */ (function () { function CookieApi() { } CookieApi.prototype.write = function (name, value, options) { if (value === void 0) { value = undefined; } document.cookie = this.buildCookieString(name, value, options); }; CookieApi.prototype.read = function (name) { var rows = document.cookie.split(';'); for (var _i = 0, rows_1 = rows; _i < rows_1.length; _i++) { var row = rows_1[_i]; var _a = row.split('='), key = _a[0], val = _a[1]; var cookieKey = decodeURIComponent(key.trim().toLowerCase()); if (cookieKey === name.toLowerCase()) { return decodeURIComponent(val); } } return ''; }; // dont use this method - only making public so I can test the cookie string // document.cookie only returns name=value pairs, not expiration or any other options set on create CookieApi.prototype.buildCookieString = function (name, value, options) { if (value === void 0) { value = undefined; } var expires; if (!value) { expires = new Date('Thu, 01 Jan 1970 00:00:00 GMT'); value = ''; } else { // set expiration of cookie longer than token // so we can parse clientid from token to perform refresh when token has expired expires = new Date(); expires.setFullYear(expires.getFullYear() + 1); } var str = encodeURIComponent(name) + '=' + encodeURIComponent(value); str += options.domain ? ';domain=' + options.domain : ''; str += expires ? ';expires=' + expires.toUTCString() : ''; str += options.secure ? ';secure' : ''; str += options.samesite ? ';samesite=' + options.samesite : ''; str += options.path ? ';path=' + options.path : ''; // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum 4096 bytes per cookie var cookieLength = str.length + 1; if (cookieLength > 4096) { console.warn("Cookie ".concat(name, " possibly not set or overflowed because it was too large! (").concat(cookieLength, " > 4096 bytes)")); } return str; }; return CookieApi; }()); var cookie = new CookieApi(); /** * @ignore * not part of public api, don't include in generated docs */ var CookieService = /** @class */ (function () { function CookieService() { this.get = this.get.bind(this); this.set = this.set.bind(this); this.remove = this.remove.bind(this); } CookieService.prototype.get = function (name) { var configuration = Configuration$1.Get(); var cookieName = configuration.cookieOptions.prefix + name; return cookie.read(cookieName); }; CookieService.prototype.set = function (name, cookieVal) { var configuration = Configuration$1.Get(); var cookieName = configuration.cookieOptions.prefix + name; cookie.write(cookieName, cookieVal, configuration.cookieOptions); }; CookieService.prototype.remove = function (name) { var configuration = Configuration$1.Get(); var cookieName = configuration.cookieOptions.prefix + name; cookie.write(cookieName, undefined, configuration.cookieOptions); }; return CookieService; }()); var cookies = new CookieService(); /** * @ignore * not part of public api, don't include in generated docs */ function decodeBase64(str) { // atob is defined on the browser, in node we must use buffer if (typeof atob !== 'undefined') { return atob(str); } return Buffer.from(str, 'base64').toString('binary'); } /** * @ignore * not part of public api, don't include in generated docs */ function parseJwt(token) { try { var base64Url = token.split('.')[1]; var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/'); var jsonPayload = decodeURIComponent(decodeBase64(base64) .split('') .map(function (c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }) .join('')); return JSON.parse(jsonPayload); } catch (e) { throw new Error('Invalid token'); } } /** * @ignore * not part of public api, don't include in generated docs */ var paramsSerializer = { serialize: customSerializer, }; /** * @ignore * not part of public api, don't include in generated docs */ function customSerializer(originalParams) { var params = JSON.parse(JSON.stringify(originalParams)); // don't mutate original object var valuesArray = []; // serialize filters first, they are handled specially if (params.filters) { var filters = flattenFiltersObject(params.filters); var _loop_1 = function (key) { var filterVal = filters[key]; if (Array.isArray(filterVal)) { filterVal.forEach(function (val) { return valuesArray.push("".concat(key, "=").concat(encodeURIComponent(val))); }); } // exclude null, undefined, or empty string but permit boolean false, and 0 to be serialized else if (typeof filterVal === 'boolean' || filterVal === 0 || filterVal) { valuesArray.push("".concat(key, "=").concat(encodeURIComponent(filterVal))); } }; for (var key in filters) { _loop_1(key); } delete params.filters; } // serialize the rest of the params for (var key in params) { var val = params[key]; if (val) { valuesArray.push("".concat(key, "=").concat(encodeURIComponent(val))); } } return valuesArray.length ? "".concat(valuesArray.join('&')) : ''; } /** * @ignore * not part of public api, don't include in generated docs * * build a flattened filters object where each key is the dot-referenced property * to filter and the value is the value to filter by * this ultimately gets sent to ordercloud as a query param */ function flattenFiltersObject(filters) { var result = {}; for (var key in filters) { inspectProp(filters[key], key, result); } return result; } /** * @ignore * not part of public api, don't include in generated docs */ function inspectProp(propVal, propName, result) { var isObject = Object.prototype.toString.call(propVal) === '[object Object]'; if (isObject) { for (var key in propVal) { inspectProp(propVal[key], "".concat(propName, ".").concat(key), result); } } else { if (propVal === null) { throw new Error("Null is not a valid filter prop. Use negative filter \"!\" combined with wildcard filter \"*\" to define a filter for the absence of a value. \nex: an order list call with { xp: { hasPaid: '!*' } } would return a list of orders where xp.hasPaid is null or undefined\nhttps://ordercloud.io/features/advanced-querying#filtering"); } result[propName] = propVal; } } var Auth = /** @class */ (function () { function Auth() { if (typeof axios__default["default"] === 'undefined') { throw new Error('Ordercloud is missing required peer dependency axios. This must be installed and loaded before the OrderCloud SDK'); } /** * @ignore * not part of public api, don't include in generated docs */ this.Anonymous = this.Anonymous.bind(this); this.ClientCredentials = this.ClientCredentials.bind(this); this.ElevatedLogin = this.ElevatedLogin.bind(this); this.Login = this.Login.bind(this); this.RefreshToken = this.RefreshToken.bind(this); } /** * @description this workflow is most appropriate for client apps where user is a human, ie a registered user * * @param username of the user logging in * @param password of the user logging in * @param client_id of the application the user is logging into * @param scope optional roles being requested, if omitted will return all assigned roles * @param customRoles optional custom roles being requested - string array * @param requestOptions.cancelToken Provide an [axios cancelToken](https://github.com/axios/axios#cancellation) that can be used to cancel the request. * @param requestOptions.requestType Provide a value that can be used to identify the type of request. Useful for error logs. */ Auth.prototype.Login = function (username, password, clientID, scope, customRoles, requestOptions) { if (requestOptions === void 0) { requestOptions = {}; } return __awaiter(this, void 0, void 0, function () { var _scope, body, configuration, response; return __generator(this, function (_a) { switch (_a.label) { case 0: if (scope && !Array.isArray(scope)) { throw new Error('scope must be a string array'); } if (customRoles != null && !Array.isArray(customRoles)) { throw new Error('custom roles must be defined as a string array'); } if ((scope === null || scope === void 0 ? void 0 : scope.length) && !(customRoles === null || customRoles === void 0 ? void 0 : customRoles.length)) { _scope = scope.join(' '); } else if (!(scope === null || scope === void 0 ? void 0 : scope.length) && (customRoles === null || customRoles === void 0 ? void 0 : customRoles.length)) { _scope += " ".concat(customRoles.join(' ')); } else if ((scope === null || scope === void 0 ? void 0 : scope.length) && (customRoles === null || customRoles === void 0 ? void 0 : customRoles.length)) { _scope = "".concat(scope.join(' '), " ").concat(customRoles.join(' ')); } body = { grant_type: 'password', username: username, password: password, client_id: clientID, scope: _scope, }; configuration = Configuration$1.Get(); return [4 /*yield*/, axios__default["default"] .post("".concat(configuration.baseApiUrl, "/oauth/token"), paramsSerializer.serialize(body), __assign({ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json', }, adapter: configuration.axiosAdapter }, requestOptions)) .catch(function (e) { if (e.response) { throw new OrderCloudError(e); } throw e; })]; case 1: response = _a.sent(); return [2 /*return*/, response.data]; } }); }); }; /** * @description similar to login except client secret is also required, adding another level of security * * @param clientSecret of the application * @param username of the user logging in * @param password of the user logging in * @param clientID of the application the user is logging into * @param scope roles being requested - space delimited string or array * @param customRoles optional custom roles being requested - string array * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. * @param requestOptions.cancelToken Provide an [axios cancelToken](https://github.com/axios/axios#cancellation) that can be used to cancel the request. * @param requestOptions.requestType Provide a value that can be used to identify the type of request. Useful for error logs. */ Auth.prototype.ElevatedLogin = function (clientSecret, username, password, clientID, scope, customRoles, requestOptions) { if (requestOptions === void 0) { requestOptions = {}; } return __awaiter(this, void 0, void 0, function () { var _scope, body, configuration, response; return __generator(this, function (_a) { switch (_a.label) { case 0: if (scope && !Array.isArray(scope)) { throw new Error('scope must be a string array'); } if (customRoles != null && !Array.isArray(customRoles)) { throw new Error('custom roles must be defined as a string array'); } if ((scope === null || scope === void 0 ? void 0 : scope.length) && !(customRoles === null || customRoles === void 0 ? void 0 : customRoles.length)) { _scope = scope.join(' '); } else if (!(scope === null || scope === void 0 ? void 0 : scope.length) && (customRoles === null || customRoles === void 0 ? void 0 : customRoles.length)) { _scope += " ".concat(customRoles.join(' ')); } else if ((scope === null || scope === void 0 ? void 0 : scope.length) && (customRoles === null || customRoles === void 0 ? void 0 : customRoles.length)) { _scope = "".concat(scope.join(' '), " ").concat(customRoles.join(' ')); } body = { grant_type: 'password', scope: _scope, client_id: clientID, username: username, password: password, client_secret: clientSecret, }; configuration = Configuration$1.Get(); return [4 /*yield*/, axios__default["default"] .post("".concat(configuration.baseApiUrl, "/oauth/token"), paramsSerializer.serialize(body), __assign({ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json', }, adapter: configuration.axiosAdapter }, requestOptions)) .catch(function (e) { if (e.response) { throw new OrderCloudError(e); } throw e; })]; case 1: response = _a.sent(); return [2 /*return*/, response.data]; } }); }); }; /** * @description this workflow is best suited for a backend system * * @param clientSecret of the application * @param clientID of the application the user is logging into * @param scope roles being requested - space delimited string or array * @param customRoles optional custom roles being requested - string array * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. * @param requestOptions.cancelToken Provide an [axios cancelToken](https://github.com/axios/axios#cancellation) that can be used to cancel the request. * @param requestOptions.requestType Provide a value that can be used to identify the type of request. Useful for error logs. */ Auth.prototype.ClientCredentials = function (clientSecret, clientID, scope, customRoles, requestOptions) { if (requestOptions === void 0) { requestOptions = {}; } return __awaiter(this, void 0, void 0, function () { var _scope, body, configuration, response; return __generator(this, function (_a) { switch (_a.label) { case 0: if (scope && !Array.isArray(scope)) { throw new Error('scope must be a string array'); } if (customRoles != null && !Array.isArray(customRoles)) { throw new Error('custom roles must be defined as a string array'); } if ((scope === null || scope === void 0 ? void 0 : scope.length) && !(customRoles === null || customRoles === void 0 ? void 0 : customRoles.length)) { _scope = scope.join(' '); } else if (!(scope === null || scope === void 0 ? void 0 : scope.length) && (customRoles === null || customRoles === void 0 ? void 0 : customRoles.length)) { _scope += " ".concat(customRoles.join(' ')); } else if ((scope === null || scope === void 0 ? void 0 : scope.length) && (customRoles === null || customRoles === void 0 ? void 0 : customRoles.length)) { _scope = "".concat(scope.join(' '), " ").concat(customRoles.join(' ')); } body = { grant_type: 'client_credentials', scope: _scope, client_id: clientID, client_secret: clientSecret, }; configuration = Configuration$1.Get(); return [4 /*yield*/, axios__default["default"] .post("".concat(configuration.baseApiUrl, "/oauth/token"), paramsSerializer.serialize(body), __assign({ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json', }, adapter: configuration.axiosAdapter }, requestOptions)) .catch(function (e) { if (e.response) { throw new OrderCloudError(e); } throw e; })]; case 1: response = _a.sent(); return [2 /*return*/, response.data]; } }); }); }; /** * @description extend your users' session by getting a new access token with a refresh token. refresh tokens must be enabled in the dashboard * * @param refreshToken of the application * @param clientID of the application the user is logging into * @param requestOptions.cancelToken Provide an [axios cancelToken](https://github.com/axios/axios#cancellation) that can be used to cancel the request. * @param requestOptions.requestType Provide a value that can be used to identify the type of request. Useful for error logs. */ Auth.prototype.RefreshToken = function (refreshToken, clientID, requestOptions) { if (requestOptions === void 0) { requestOptions = {}; } return __awaiter(this, void 0, void 0, function () { var body, configuration, response; return __generator(this, function (_a) { switch (_a.label) { case 0: body = { grant_type: 'refresh_token', client_id: clientID, refresh_token: refreshToken, }; configuration = Configuration$1.Get(); return [4 /*yield*/, axios__default["default"] .post("".concat(configuration.baseApiUrl, "/oauth/token"), paramsSerializer.serialize(body), __assign({ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json', }, adapter: configuration.axiosAdapter }, requestOptions)) .catch(function (e) { if (e.response) { throw new OrderCloudError(e); } throw e; })]; case 1: response = _a.sent(); return [2 /*return*/, response.data]; } }); }); }; /** * @description allow users to browse your catalog without signing in - must have anonymous template user set in dashboard * * @param clientID of the application the user is logging into * @param scope roles being requested - space delimited string or array * @param customRoles optional custom roles being requested - string array * @param requestOptions.anonuserid Provide an externally generated id to track this user session, used specifically for the tracking events feature for integrating with Send and Discover * @param requestOptions.cancelToken Provide an [axios cancelToken](https://github.com/axios/axios#cancellation) that can be used to cancel the request. * @param requestOptions.requestType Provide a value that can be used to identify the type of request. Useful for error logs. */ Auth.prototype.Anonymous = function (clientID, scope, customRoles, requestOptions) { if (requestOptions === void 0) { requestOptions = {}; } return __awaiter(this, void 0, void 0, function () { var _scope, body, configuration, response; return __generator(this, function (_a) { switch (_a.label) { case 0: if (scope && !Array.isArray(scope)) { throw new Error('scope must be a string array'); } if (customRoles != null && !Array.isArray(customRoles)) { throw new Error('custom roles must be defined as a string array'); } if ((scope === null || scope === void 0 ? void 0 : scope.length) && !(customRoles === null || customRoles === void 0 ? void 0 : customRoles.length)) { _scope = scope.join(' '); } else if (!(scope === null || scope === void 0 ? void 0 : scope.length) && (customRoles === null || customRoles === void 0 ? void 0 : customRoles.length)) { _scope += " ".concat(customRoles.join(' ')); } else if ((scope === null || scope === void 0 ? void 0 : scope.length) && (customRoles === null || customRoles === void 0 ? void 0 : customRoles.length)) { _scope = "".concat(scope.join(' '), " ").concat(customRoles.join(' ')); } body = { grant_type: 'client_credentials', client_id: clientID, scope: _scope, }; if (requestOptions.anonuserid) { body['anonuserid'] = requestOptions.anonuserid; delete requestOptions['anonuserid']; } configuration = Configuration$1.Get(); return [4 /*yield*/, axios__default["default"] .post("".concat(configuration.baseApiUrl, "/oauth/token"), paramsSerializer.serialize(body), __assign({ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json', }, adapter: configuration.axiosAdapter }, requestOptions)) .catch(function (e) { if (e.response) { throw new OrderCloudError(e); } throw e; })]; case 1: response = _a.sent(); return [2 /*return*/, response.data]; } }); }); }; return Auth; }()); var Auth$1 = new Auth(); var _a, _b; /** * @ignore * not part of public api, don't include in generated docs */ var isNode = typeof process !== 'undefined' && Boolean((_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node); // https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation#importing-runtime-specific-code /** * @ignore * not part of public api, don't include in generated docs */ var isEdgeRuntime = typeof process !== 'undefined' && ((_b = process === null || process === void 0 ? void 0 : process.env) === null || _b === void 0 ? void 0 : _b.NEXT_RUNTIME) && process.env.NEXT_RUNTIME !== 'edge'; /** * @ignore * not part of public api, don't include in generated docs */ var isServer = isNode || isEdgeRuntime; var Tokens = /** @class */ (function () { /** * @ignore * not part of public api, don't include in generated docs */ function Tokens() { this.accessTokenCookieName = ".access-token"; this.impersonationTokenCookieName = '.impersonation-token'; this.refreshTokenCookieName = '.refresh-token'; this.identityTokenCookieName = '.identity-token'; this.identityProviderAccessTokenCookieName = '.idp-access-token'; this.accessToken = null; this.impersonationToken = null; this.refreshToken = null; this.identityToken = null; this.identityProviderAccessToken = null; this.GetAccessToken = this.GetAccessToken.bind(this); this.GetImpersonationToken = this.GetImpersonationToken.bind(this); this.GetRefreshToken = this.GetRefreshToken.bind(this); this.RemoveAccessToken = this.RemoveAccessToken.bind(this); this.RemoveImpersonationToken = this.RemoveImpersonationToken.bind(this); this.SetAccessToken = this.SetAccessToken.bind(this); this.RemoveRefreshToken = this.RemoveRefreshToken.bind(this); this.SetImpersonationToken = this.SetImpersonationToken.bind(this); this.SetRefreshToken = this.SetRefreshToken.bind(this); this.RemoveIdentityToken = this.RemoveIdentityToken.bind(this); this.GetIdentityToken = this.GetIdentityToken.bind(this); this.SetIdentityToken = this.SetIdentityToken.bind(this); this._isTokenExpired = this._isTokenExpired.bind(this); this._tryRefreshToken = this._tryRefreshToken.bind(this); } /** * Manage Access Tokens */ Tokens.prototype.GetAccessToken = function () { return isServer ? this.accessToken : cookies.get(this.accessTokenCookieName); }; Tokens.prototype.SetAccessToken = function (token) { parseJwt(token); // check if token is valid isServer ? (this.accessToken = token) : cookies.set(this.accessTokenCookieName, token); }; Tokens.prototype.RemoveAccessToken = function () { isServer ? (this.accessToken = '') : cookies.remove(this.accessTokenCookieName); }; /** * Manage Impersonation Tokens */ Tokens.prototype.GetImpersonationToken = function () { return isServer ? this.impersonationToken : cookies.get(this.impersonationTokenCookieName); }; Tokens.prototype.SetImpersonationToken = function (token) { parseJwt(token); // check if token is valid isServer ? (this.impersonationToken = token) : cookies.set(this.impersonationTokenCookieName, token); }; Tokens.prototype.RemoveImpersonationToken = function () { isServer ? (this.impersonationToken = null) : cookies.remove(this.impersonationTokenCookieName); }; /** * Manage Refresh Tokens */ Tokens.prototype.GetRefreshToken = function () { return isServer ? this.refreshToken : cookies.get(this.refreshTokenCookieName); }; Tokens.prototype.SetRefreshToken = function (token) { isServer ? (this.refreshToken = token) : cookies.set(this.refreshTokenCookieName, token); }; Tokens.prototype.RemoveRefreshToken = function () { isServer ? (this.refreshToken = null) : cookies.remove(this.refreshTokenCookieName); }; /** * Manage Identity Tokens */ Tokens.prototype.GetIdentityToken = function () { return isServer ? this.identityToken : cookies.get(this.identityTokenCookieName); }; Tokens.prototype.SetIdentityToken = function (token) { isServer ? (this.identityToken = token) : cookies.set(this.identityTokenCookieName, token); }; Tokens.prototype.RemoveIdentityToken = function () { isServer ? (this.identityToken = null) : cookies.remove(this.identityTokenCookieName); }; /** * Manage Identity Provider Tokens */ Tokens.prototype.GetIdpAccessToken = function () { return isServer ? this.identityProviderAccessToken : cookies.get(this.identityProviderAccessTokenCookieName); }; Tokens.prototype.SetIdpAccessToken = function (token) { isServer ? (this.identityProviderAccessToken = token) : cookies.set(this.identityProviderAccessTokenCookieName, token); }; Tokens.prototype.RemoveIdpAccessToken = function () { isServer ? (this.identityProviderAccessToken = null) : cookies.remove(this.identityProviderAccessTokenCookieName); }; /** * If no token is provided will attempt to get and validate token * stored in sdk. If token is invalid or missing it will also attempt * to refresh the token if possible */ Tokens.prototype.GetValidToken = function (tokenToValidate) { return __awaiter(this, void 0, void 0, function () { var token; return __generator(this, function (_a) { switch (_a.label) { case 0: token = tokenToValidate || this.GetAccessToken(); if (!this._isTokenExpired(token)) return [3 /*break*/, 2]; return [4 /*yield*/, this._tryRefreshToken(token)]; case 1: token = _a.sent(); _a.label = 2; case 2: return [2 /*return*/, Promise.resolve(token || '')]; } }); }); }; Tokens.prototype._isTokenExpired = function (token) { if (!token) { return true; } var decodedToken = parseJwt(token); var currentSeconds = Date.now() / 1000; var currentSecondsWithBuffer = currentSeconds - 10; return decodedToken.exp < currentSecondsWithBuffer; }; Tokens.prototype._tryRefreshToken = function (accessToken) { return __awaiter(this, void 0, void 0, function () { var refreshToken, sdkConfig, clientID, decodedToken, refreshRequest, accessToken_1; return __generator(this, function (_a) { switch (_a.label) { case 0: refreshToken = this.GetRefreshToken(); if (!refreshToken) { return [2 /*return*/, accessToken || '']; } sdkConfig = Configuration$1.Get(); if (!accessToken && !sdkConfig.clientID) { return [2 /*return*/, accessToken || '']; } if (accessToken) { decodedToken = parseJwt(accessToken); clientID = decodedToken.cid; } if (sdkConfig.clientID) { clientID = sdkConfig.clientID; } if (!clientID) { return [2 /*return*/, '']; } if (!clientID) return [3 /*break*/, 4]; _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, Auth$1.RefreshToken(refreshToken, clientID)]; case 2: refreshRequest = _a.sent(); accessToken_1 = refreshRequest.access_token; this.SetAccessToken(accessToken_1); return [2 /*return*/, accessToken_1]; case 3: _a.sent(); return [2 /*return*/, '']; case 4: return [2 /*return*/]; } }); }); }; return Tokens; }()); var tokenService = new Tokens(); var HttpClient = /** @class */ (function () { function HttpClient() { var _this = this; this.get = function (path, config) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.makeApiCall('get', path, config)]; case 1: return [2 /*return*/, _a.sent()]; } }); }); }; this.post = function (path, config) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.makeApiCall('post', path, config)]; case 1: return [2 /*return*/, _a.sent()]; } }); }); }; this.put = function (path, config) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.makeApiCall('put', path, config)]; case 1: return [2 /*return*/, _a.sent()]; } }); }); }; this.patch = function (path, config) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.makeApiCall('patch', path, config)]; case 1: return [2 /*return*/, _a.sent()]; } }); }); }; this.delete = function (path, config) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.makeApiCall('delete', path, config)]; case 1: return [2 /*return*/, _a.sent()]; } }); }); }; if (typeof axios__default["default"] === 'undefined') { throw new Error('Missing required peer dependency axios. This must be installed and loaded before the OrderCloud SDK'); } this.get = this.get.bind(this); this.put = this.put.bind(this); this.post = this.post.bind(this); this.patch = this.patch.bind(this); this.delete = this.delete.bind(this); this._resolveToken = this._resolveToken.bind(this); this._buildRequestConfig = this._buildRequestConfig.bind(this); this._addTokenToConfig = this._addTokenToConfig.bind(this); } HttpClient.prototype.makeApiCall = function (verb, path, config) { return __awaiter(this, void 0, void 0, function () { var requestConfig, baseApiUrl, requestBody, response, response; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this._buildRequestConfig(config) // oauth endpoints unlike the rest don't have /{apiVersion}/ appended to them ]; case 1: requestConfig = _a.sent(); baseApiUrl = path.includes('oauth/') ? "".concat(Configuration$1.Get().baseApiUrl, "/").concat(path) : "".concat(Configuration$1.Get().baseApiUrl, "/").concat(Configuration$1.Get().apiVersion).concat(path); if (!(verb === 'put' || verb === 'post' || verb === 'patch')) return [3 /*break*/, 3]; requestBody = requestConfig.data; delete requestConfig.data; return [4 /*yield*/, axios__default["default"][verb](baseApiUrl, requestBody, requestConfig)]; case 2: response = _a.sent(); return [2 /*return*/, response.data]; case 3: return [4 /*yield*/, axios__default["default"][verb](baseApiUrl, requestConfig)]; case 4: response = _a.sent(); return [2 /*return*/, response.data]; } }); }); }; // sets the token on every outgoing request, will attempt to // refresh the token if the token is expired and there is a refresh token set HttpClient.prototype._addTokenToConfig = function (config) { return __awaiter(this, void 0, void 0, function () { var token, validToken; return __generator(this, function (_a) { switch (_a.label) { case 0: token = this._resolveToken(config); return [4 /*yield*/, tokenService.GetValidToken(token)]; case 1: validToken = _a.sent(); if (!config.headers) { config.headers = {}; } config.headers.Authorization = "Bearer ".concat(validToken); return [2 /*return*/, config]; } }); }); }; HttpClient.prototype._resolveToken = function (config) { var token; if (config['accessToken']) { token = config['accessToken']; } else if (config['impersonating']) { token = tokenService.GetImpersonationToken(); } else { token = tokenService.GetAccessToken(); } // remove these custom parameters that axios doesn't understand // we were storing on the axios config for simplicity delete config['accessToken']; delete config['impersonating']; return token; }; HttpClient.prototype._buildRequestConfig = function (config) { var sdkConfig = Configuration$1.Get(); var requestConfig = __assign(__assign({}, config), { paramsSerializer: paramsSerializer, adapter: sdkConfig.axiosAdapter, timeout: sdkConfig.timeoutInMilliseconds, headers: { 'Content-Type': 'application/json', } }); return this._addTokenToConfig(requestConfig); }; return HttpClient; }()); var http = new HttpClient(); var ApiClients = /** @class */ (function () { /** * @ignore * not part of public api, don't include in generated docs */ function ApiClients() { this.impersonating = false; this.List = this.List.bind(this); this.Create = this.Create.bind(this); this.Get = this.Get.bind(th