diff --git a/docs/changelog.md b/docs/changelog.md index c78e679f..b4556f49 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -1,5 +1,7 @@ ## Changelog +__3.10.0_ +Aggregate functions __3.9.1_ Bugfix: Crashing on many relations if foreign key column is omitted in strategy. See [#83](https://github.com/alfateam/rdb/issues/83) __3.9.0__ diff --git a/package.json b/package.json index 9b3ce620..57d99bdd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "rdb", - "version": "3.9.1", + "version": "3.10.0", "main": "./src/index.js", "browser": "./src/client/index.mjs", "bin": { diff --git a/src/client/index.mjs b/src/client/index.mjs index b101af56..ff6efc0e 100644 --- a/src/client/index.mjs +++ b/src/client/index.mjs @@ -6,11 +6,11 @@ void !function() { function getAugmentedNamespace(n) { if (n.__esModule) return n; var a = Object.defineProperty({}, '__esModule', {value: true}); - Object.keys(n).forEach(function(k) { + Object.keys(n).forEach(function (k) { var d = Object.getOwnPropertyDescriptor(n, k); Object.defineProperty(a, k, d.get ? d : { enumerable: true, - get: function() { + get: function () { return n[k]; } }); @@ -23,41 +23,41 @@ function getAugmentedNamespace(n) { * (c) 2017-2022 Joachim Wester * MIT licensed */ -var __extends = (undefined && undefined.__extends) || (function() { - 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); - }; - return function(d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; +var __extends = (undefined && undefined.__extends) || (function () { + 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); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; })(); var _hasOwnProperty = Object.prototype.hasOwnProperty; function hasOwnProperty$1(obj, key) { - return _hasOwnProperty.call(obj, key); + return _hasOwnProperty.call(obj, key); } function _objectKeys(obj) { - if (Array.isArray(obj)) { - var keys_1 = new Array(obj.length); - for (var k = 0; k < keys_1.length; k++) { - keys_1[k] = '' + k; - } - return keys_1; - } - if (Object.keys) { - return Object.keys(obj); - } - var keys = []; - for (var i in obj) { - if (hasOwnProperty$1(obj, i)) { - keys.push(i); - } - } - return keys; + if (Array.isArray(obj)) { + var keys_1 = new Array(obj.length); + for (var k = 0; k < keys_1.length; k++) { + keys_1[k] = "" + k; + } + return keys_1; + } + if (Object.keys) { + return Object.keys(obj); + } + var keys = []; + for (var i in obj) { + if (hasOwnProperty$1(obj, i)) { + keys.push(i); + } + } + return keys; } /** * Deeply clone the object. @@ -66,29 +66,29 @@ function _objectKeys(obj) { * @return {any} cloned obj */ function _deepClone(obj) { - switch (typeof obj) { - case 'object': - return JSON.parse(JSON.stringify(obj)); //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5 - case 'undefined': - return null; //this is how JSON.stringify behaves for array items - default: - return obj; //no need to clone primitives - } + switch (typeof obj) { + case "object": + return JSON.parse(JSON.stringify(obj)); //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5 + case "undefined": + return null; //this is how JSON.stringify behaves for array items + default: + return obj; //no need to clone primitives + } } //3x faster than cached /^\d+$/.test(str) function isInteger(str) { - var i = 0; - var len = str.length; - var charCode; - while (i < len) { - charCode = str.charCodeAt(i); - if (charCode >= 48 && charCode <= 57) { - i++; - continue; - } - return false; - } - return true; + var i = 0; + var len = str.length; + var charCode; + while (i < len) { + charCode = str.charCodeAt(i); + if (charCode >= 48 && charCode <= 57) { + i++; + continue; + } + return false; + } + return true; } /** * Escapes a json pointer path @@ -96,9 +96,9 @@ function isInteger(str) { * @return the Escaped path */ function escapePathComponent(path) { - if (path.indexOf('/') === -1 && path.indexOf('~') === -1) - return path; - return path.replace(/~/g, '~0').replace(/\//g, '~1'); + if (path.indexOf('/') === -1 && path.indexOf('~') === -1) + return path; + return path.replace(/~/g, '~0').replace(/\//g, '~1'); } /** * Unescapes a json pointer path @@ -106,59 +106,59 @@ function escapePathComponent(path) { * @return The unescaped path */ function unescapePathComponent(path) { - return path.replace(/~1/g, '/').replace(/~0/g, '~'); + return path.replace(/~1/g, '/').replace(/~0/g, '~'); } /** * Recursively checks whether an object has any undefined values inside. */ function hasUndefined(obj) { - if (obj === undefined) { - return true; - } - if (obj) { - if (Array.isArray(obj)) { - for (var i_1 = 0, len = obj.length; i_1 < len; i_1++) { - if (hasUndefined(obj[i_1])) { - return true; - } - } - } - else if (typeof obj === 'object') { - var objKeys = _objectKeys(obj); - var objKeysLength = objKeys.length; - for (var i = 0; i < objKeysLength; i++) { - if (hasUndefined(obj[objKeys[i]])) { - return true; - } - } - } - } - return false; + if (obj === undefined) { + return true; + } + if (obj) { + if (Array.isArray(obj)) { + for (var i_1 = 0, len = obj.length; i_1 < len; i_1++) { + if (hasUndefined(obj[i_1])) { + return true; + } + } + } + else if (typeof obj === "object") { + var objKeys = _objectKeys(obj); + var objKeysLength = objKeys.length; + for (var i = 0; i < objKeysLength; i++) { + if (hasUndefined(obj[objKeys[i]])) { + return true; + } + } + } + } + return false; } function patchErrorMessageFormatter(message, args) { - var messageParts = [message]; - for (var key in args) { - var value = typeof args[key] === 'object' ? JSON.stringify(args[key], null, 2) : args[key]; // pretty print - if (typeof value !== 'undefined') { - messageParts.push(key + ': ' + value); - } - } - return messageParts.join('\n'); + var messageParts = [message]; + for (var key in args) { + var value = typeof args[key] === 'object' ? JSON.stringify(args[key], null, 2) : args[key]; // pretty print + if (typeof value !== 'undefined') { + messageParts.push(key + ": " + value); + } + } + return messageParts.join('\n'); } -var PatchError = /** @class */ (function(_super) { - __extends(PatchError, _super); - function PatchError(message, name, index, operation, tree) { - var _newTarget = this.constructor; - var _this = _super.call(this, patchErrorMessageFormatter(message, { name: name, index: index, operation: operation, tree: tree })) || this; - _this.name = name; - _this.index = index; - _this.operation = operation; - _this.tree = tree; - Object.setPrototypeOf(_this, _newTarget.prototype); // restore prototype chain, see https://stackoverflow.com/a/48342359 - _this.message = patchErrorMessageFormatter(message, { name: name, index: index, operation: operation, tree: tree }); - return _this; - } - return PatchError; +var PatchError = /** @class */ (function (_super) { + __extends(PatchError, _super); + function PatchError(message, name, index, operation, tree) { + var _newTarget = this.constructor; + var _this = _super.call(this, patchErrorMessageFormatter(message, { name: name, index: index, operation: operation, tree: tree })) || this; + _this.name = name; + _this.index = index; + _this.operation = operation; + _this.tree = tree; + Object.setPrototypeOf(_this, _newTarget.prototype); // restore prototype chain, see https://stackoverflow.com/a/48342359 + _this.message = patchErrorMessageFormatter(message, { name: name, index: index, operation: operation, tree: tree }); + return _this; + } + return PatchError; }(Error)); var JsonPatchError = PatchError; @@ -171,71 +171,71 @@ var deepClone = _deepClone; */ /* The operations applicable to an object */ var objOps = { - add: function(obj, key, document) { - obj[key] = this.value; - return { newDocument: document }; - }, - remove: function(obj, key, document) { - var removed = obj[key]; - delete obj[key]; - return { newDocument: document, removed: removed }; - }, - replace: function(obj, key, document) { - var removed = obj[key]; - obj[key] = this.value; - return { newDocument: document, removed: removed }; - }, - move: function(obj, key, document) { - /* in case move target overwrites an existing value, + add: function (obj, key, document) { + obj[key] = this.value; + return { newDocument: document }; + }, + remove: function (obj, key, document) { + var removed = obj[key]; + delete obj[key]; + return { newDocument: document, removed: removed }; + }, + replace: function (obj, key, document) { + var removed = obj[key]; + obj[key] = this.value; + return { newDocument: document, removed: removed }; + }, + move: function (obj, key, document) { + /* in case move target overwrites an existing value, return the removed value, this can be taxing performance-wise, and is potentially unneeded */ - var removed = getValueByPointer(document, this.path); - if (removed) { - removed = _deepClone(removed); - } - var originalValue = applyOperation(document, { op: 'remove', path: this.from }).removed; - applyOperation(document, { op: 'add', path: this.path, value: originalValue }); - return { newDocument: document, removed: removed }; - }, - copy: function(obj, key, document) { - var valueToCopy = getValueByPointer(document, this.from); - // enforce copy by value so further operations don't affect source (see issue #177) - applyOperation(document, { op: 'add', path: this.path, value: _deepClone(valueToCopy) }); - return { newDocument: document }; - }, - test: function(obj, key, document) { - return { newDocument: document, test: _areEquals(obj[key], this.value) }; - }, - _get: function(obj, key, document) { - this.value = obj[key]; - return { newDocument: document }; - } + var removed = getValueByPointer(document, this.path); + if (removed) { + removed = _deepClone(removed); + } + var originalValue = applyOperation(document, { op: "remove", path: this.from }).removed; + applyOperation(document, { op: "add", path: this.path, value: originalValue }); + return { newDocument: document, removed: removed }; + }, + copy: function (obj, key, document) { + var valueToCopy = getValueByPointer(document, this.from); + // enforce copy by value so further operations don't affect source (see issue #177) + applyOperation(document, { op: "add", path: this.path, value: _deepClone(valueToCopy) }); + return { newDocument: document }; + }, + test: function (obj, key, document) { + return { newDocument: document, test: _areEquals(obj[key], this.value) }; + }, + _get: function (obj, key, document) { + this.value = obj[key]; + return { newDocument: document }; + } }; /* The operations applicable to an array. Many are the same as for the object */ var arrOps = { - add: function(arr, i, document) { - if (isInteger(i)) { - arr.splice(i, 0, this.value); - } - else { // array props - arr[i] = this.value; - } - // this may be needed when using '-' in an array - return { newDocument: document, index: i }; - }, - remove: function(arr, i, document) { - var removedList = arr.splice(i, 1); - return { newDocument: document, removed: removedList[0] }; - }, - replace: function(arr, i, document) { - var removed = arr[i]; - arr[i] = this.value; - return { newDocument: document, removed: removed }; - }, - move: objOps.move, - copy: objOps.copy, - test: objOps.test, - _get: objOps._get + add: function (arr, i, document) { + if (isInteger(i)) { + arr.splice(i, 0, this.value); + } + else { // array props + arr[i] = this.value; + } + // this may be needed when using '-' in an array + return { newDocument: document, index: i }; + }, + remove: function (arr, i, document) { + var removedList = arr.splice(i, 1); + return { newDocument: document, removed: removedList[0] }; + }, + replace: function (arr, i, document) { + var removed = arr[i]; + arr[i] = this.value; + return { newDocument: document, removed: removed }; + }, + move: objOps.move, + copy: objOps.copy, + test: objOps.test, + _get: objOps._get }; /** * Retrieves a value from a JSON document by a JSON pointer. @@ -246,12 +246,12 @@ var arrOps = { * @return The retrieved value */ function getValueByPointer(document, pointer) { - if (pointer == '') { - return document; - } - var getOriginalDestination = { op: '_get', path: pointer }; - applyOperation(document, getOriginalDestination); - return getOriginalDestination.value; + if (pointer == '') { + return document; + } + var getOriginalDestination = { op: "_get", path: pointer }; + applyOperation(document, getOriginalDestination); + return getOriginalDestination.value; } /** * Apply a single JSON Patch Operation on a JSON document. @@ -268,145 +268,145 @@ function getValueByPointer(document, pointer) { * @return `{newDocument, result}` after the operation */ function applyOperation(document, operation, validateOperation, mutateDocument, banPrototypeModifications, index) { - if (validateOperation === void 0) { validateOperation = false; } - if (mutateDocument === void 0) { mutateDocument = true; } - if (banPrototypeModifications === void 0) { banPrototypeModifications = true; } - if (index === void 0) { index = 0; } - if (validateOperation) { - if (typeof validateOperation == 'function') { - validateOperation(operation, 0, document, operation.path); - } - else { - validator$1(operation, 0); - } - } - /* ROOT OPERATIONS */ - if (operation.path === '') { - var returnValue = { newDocument: document }; - if (operation.op === 'add') { - returnValue.newDocument = operation.value; - return returnValue; - } - else if (operation.op === 'replace') { - returnValue.newDocument = operation.value; - returnValue.removed = document; //document we removed - return returnValue; - } - else if (operation.op === 'move' || operation.op === 'copy') { // it's a move or copy to root - returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field - if (operation.op === 'move') { // report removed item - returnValue.removed = document; - } - return returnValue; - } - else if (operation.op === 'test') { - returnValue.test = _areEquals(document, operation.value); - if (returnValue.test === false) { - throw new JsonPatchError('Test operation failed', 'TEST_OPERATION_FAILED', index, operation, document); - } - returnValue.newDocument = document; - return returnValue; - } - else if (operation.op === 'remove') { // a remove on root - returnValue.removed = document; - returnValue.newDocument = null; - return returnValue; - } - else if (operation.op === '_get') { - operation.value = document; - return returnValue; - } - else { /* bad operation */ - if (validateOperation) { - throw new JsonPatchError('Operation `op` property is not one of operations defined in RFC-6902', 'OPERATION_OP_INVALID', index, operation, document); - } - else { - return returnValue; - } - } - } /* END ROOT OPERATIONS */ - else { - if (!mutateDocument) { - document = _deepClone(document); - } - var path = operation.path || ''; - var keys = path.split('/'); - var obj = document; - var t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift - var len = keys.length; - var existingPathFragment = undefined; - var key = void 0; - var validateFunction = void 0; - if (typeof validateOperation == 'function') { - validateFunction = validateOperation; - } - else { - validateFunction = validator$1; - } - while (true) { - key = keys[t]; - if (key && key.indexOf('~') != -1) { - key = unescapePathComponent(key); - } - if (banPrototypeModifications && + if (validateOperation === void 0) { validateOperation = false; } + if (mutateDocument === void 0) { mutateDocument = true; } + if (banPrototypeModifications === void 0) { banPrototypeModifications = true; } + if (index === void 0) { index = 0; } + if (validateOperation) { + if (typeof validateOperation == 'function') { + validateOperation(operation, 0, document, operation.path); + } + else { + validator$1(operation, 0); + } + } + /* ROOT OPERATIONS */ + if (operation.path === "") { + var returnValue = { newDocument: document }; + if (operation.op === 'add') { + returnValue.newDocument = operation.value; + return returnValue; + } + else if (operation.op === 'replace') { + returnValue.newDocument = operation.value; + returnValue.removed = document; //document we removed + return returnValue; + } + else if (operation.op === 'move' || operation.op === 'copy') { // it's a move or copy to root + returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field + if (operation.op === 'move') { // report removed item + returnValue.removed = document; + } + return returnValue; + } + else if (operation.op === 'test') { + returnValue.test = _areEquals(document, operation.value); + if (returnValue.test === false) { + throw new JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', index, operation, document); + } + returnValue.newDocument = document; + return returnValue; + } + else if (operation.op === 'remove') { // a remove on root + returnValue.removed = document; + returnValue.newDocument = null; + return returnValue; + } + else if (operation.op === '_get') { + operation.value = document; + return returnValue; + } + else { /* bad operation */ + if (validateOperation) { + throw new JsonPatchError('Operation `op` property is not one of operations defined in RFC-6902', 'OPERATION_OP_INVALID', index, operation, document); + } + else { + return returnValue; + } + } + } /* END ROOT OPERATIONS */ + else { + if (!mutateDocument) { + document = _deepClone(document); + } + var path = operation.path || ""; + var keys = path.split('/'); + var obj = document; + var t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift + var len = keys.length; + var existingPathFragment = undefined; + var key = void 0; + var validateFunction = void 0; + if (typeof validateOperation == 'function') { + validateFunction = validateOperation; + } + else { + validateFunction = validator$1; + } + while (true) { + key = keys[t]; + if (key && key.indexOf('~') != -1) { + key = unescapePathComponent(key); + } + if (banPrototypeModifications && (key == '__proto__' || (key == 'prototype' && t > 0 && keys[t - 1] == 'constructor'))) { - throw new TypeError('JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README'); - } - if (validateOperation) { - if (existingPathFragment === undefined) { - if (obj[key] === undefined) { - existingPathFragment = keys.slice(0, t).join('/'); - } - else if (t == len - 1) { - existingPathFragment = operation.path; - } - if (existingPathFragment !== undefined) { - validateFunction(operation, 0, document, existingPathFragment); - } - } - } - t++; - if (Array.isArray(obj)) { - if (key === '-') { - key = obj.length; - } - else { - if (validateOperation && !isInteger(key)) { - throw new JsonPatchError('Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index', 'OPERATION_PATH_ILLEGAL_ARRAY_INDEX', index, operation, document); - } // only parse key when it's an integer for `arr.prop` to work - else if (isInteger(key)) { - key = ~~key; - } - } - if (t >= len) { - if (validateOperation && operation.op === 'add' && key > obj.length) { - throw new JsonPatchError('The specified index MUST NOT be greater than the number of elements in the array', 'OPERATION_VALUE_OUT_OF_BOUNDS', index, operation, document); - } - var returnValue = arrOps[operation.op].call(operation, obj, key, document); // Apply patch - if (returnValue.test === false) { - throw new JsonPatchError('Test operation failed', 'TEST_OPERATION_FAILED', index, operation, document); - } - return returnValue; - } - } - else { - if (t >= len) { - var returnValue = objOps[operation.op].call(operation, obj, key, document); // Apply patch - if (returnValue.test === false) { - throw new JsonPatchError('Test operation failed', 'TEST_OPERATION_FAILED', index, operation, document); - } - return returnValue; - } - } - obj = obj[key]; - // If we have more keys in the path, but the next value isn't a non-null object, - // throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again. - if (validateOperation && t < len && (!obj || typeof obj !== 'object')) { - throw new JsonPatchError('Cannot perform operation at the desired path', 'OPERATION_PATH_UNRESOLVABLE', index, operation, document); - } - } - } + throw new TypeError('JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README'); + } + if (validateOperation) { + if (existingPathFragment === undefined) { + if (obj[key] === undefined) { + existingPathFragment = keys.slice(0, t).join('/'); + } + else if (t == len - 1) { + existingPathFragment = operation.path; + } + if (existingPathFragment !== undefined) { + validateFunction(operation, 0, document, existingPathFragment); + } + } + } + t++; + if (Array.isArray(obj)) { + if (key === '-') { + key = obj.length; + } + else { + if (validateOperation && !isInteger(key)) { + throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index, operation, document); + } // only parse key when it's an integer for `arr.prop` to work + else if (isInteger(key)) { + key = ~~key; + } + } + if (t >= len) { + if (validateOperation && operation.op === "add" && key > obj.length) { + throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index, operation, document); + } + var returnValue = arrOps[operation.op].call(operation, obj, key, document); // Apply patch + if (returnValue.test === false) { + throw new JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', index, operation, document); + } + return returnValue; + } + } + else { + if (t >= len) { + var returnValue = objOps[operation.op].call(operation, obj, key, document); // Apply patch + if (returnValue.test === false) { + throw new JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', index, operation, document); + } + return returnValue; + } + } + obj = obj[key]; + // If we have more keys in the path, but the next value isn't a non-null object, + // throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again. + if (validateOperation && t < len && (!obj || typeof obj !== "object")) { + throw new JsonPatchError('Cannot perform operation at the desired path', 'OPERATION_PATH_UNRESOLVABLE', index, operation, document); + } + } + } } /** * Apply a full JSON Patch array on a JSON document. @@ -423,24 +423,24 @@ function applyOperation(document, operation, validateOperation, mutateDocument, * @return An array of `{newDocument, result}` after the patch */ function applyPatch(document, patch, validateOperation, mutateDocument, banPrototypeModifications) { - if (mutateDocument === void 0) { mutateDocument = true; } - if (banPrototypeModifications === void 0) { banPrototypeModifications = true; } - if (validateOperation) { - if (!Array.isArray(patch)) { - throw new JsonPatchError('Patch sequence must be an array', 'SEQUENCE_NOT_AN_ARRAY'); - } - } - if (!mutateDocument) { - document = _deepClone(document); - } - var results = new Array(patch.length); - for (var i = 0, length_1 = patch.length; i < length_1; i++) { - // we don't need to pass mutateDocument argument because if it was true, we already deep cloned the object, we'll just pass `true` - results[i] = applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i); - document = results[i].newDocument; // in case root was replaced - } - results.newDocument = document; - return results; + if (mutateDocument === void 0) { mutateDocument = true; } + if (banPrototypeModifications === void 0) { banPrototypeModifications = true; } + if (validateOperation) { + if (!Array.isArray(patch)) { + throw new JsonPatchError('Patch sequence must be an array', 'SEQUENCE_NOT_AN_ARRAY'); + } + } + if (!mutateDocument) { + document = _deepClone(document); + } + var results = new Array(patch.length); + for (var i = 0, length_1 = patch.length; i < length_1; i++) { + // we don't need to pass mutateDocument argument because if it was true, we already deep cloned the object, we'll just pass `true` + results[i] = applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i); + document = results[i].newDocument; // in case root was replaced + } + results.newDocument = document; + return results; } /** * Apply a single JSON Patch Operation on a JSON document. @@ -452,11 +452,11 @@ function applyPatch(document, patch, validateOperation, mutateDocument, banProto * @return The updated document */ function applyReducer(document, operation, index) { - var operationResult = applyOperation(document, operation); - if (operationResult.test === false) { // failed test - throw new JsonPatchError('Test operation failed', 'TEST_OPERATION_FAILED', index, operation, document); - } - return operationResult.newDocument; + var operationResult = applyOperation(document, operation); + if (operationResult.test === false) { // failed test + throw new JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', index, operation, document); + } + return operationResult.newDocument; } /** * Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error. @@ -466,49 +466,49 @@ function applyReducer(document, operation, index) { * @param {string} [existingPathFragment] - comes along with `document` */ function validator$1(operation, index, document, existingPathFragment) { - if (typeof operation !== 'object' || operation === null || Array.isArray(operation)) { - throw new JsonPatchError('Operation is not an object', 'OPERATION_NOT_AN_OBJECT', index, operation, document); - } - else if (!objOps[operation.op]) { - throw new JsonPatchError('Operation `op` property is not one of operations defined in RFC-6902', 'OPERATION_OP_INVALID', index, operation, document); - } - else if (typeof operation.path !== 'string') { - throw new JsonPatchError('Operation `path` property is not a string', 'OPERATION_PATH_INVALID', index, operation, document); - } - else if (operation.path.indexOf('/') !== 0 && operation.path.length > 0) { - // paths that aren't empty string should start with "/" - throw new JsonPatchError('Operation `path` property must start with "/"', 'OPERATION_PATH_INVALID', index, operation, document); - } - else if ((operation.op === 'move' || operation.op === 'copy') && typeof operation.from !== 'string') { - throw new JsonPatchError('Operation `from` property is not present (applicable in `move` and `copy` operations)', 'OPERATION_FROM_REQUIRED', index, operation, document); - } - else if ((operation.op === 'add' || operation.op === 'replace' || operation.op === 'test') && operation.value === undefined) { - throw new JsonPatchError('Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)', 'OPERATION_VALUE_REQUIRED', index, operation, document); - } - else if ((operation.op === 'add' || operation.op === 'replace' || operation.op === 'test') && hasUndefined(operation.value)) { - throw new JsonPatchError('Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)', 'OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED', index, operation, document); - } - else if (document) { - if (operation.op == 'add') { - var pathLen = operation.path.split('/').length; - var existingPathLen = existingPathFragment.split('/').length; - if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) { - throw new JsonPatchError('Cannot perform an `add` operation at the desired path', 'OPERATION_PATH_CANNOT_ADD', index, operation, document); - } - } - else if (operation.op === 'replace' || operation.op === 'remove' || operation.op === '_get') { - if (operation.path !== existingPathFragment) { - throw new JsonPatchError('Cannot perform the operation at a path that does not exist', 'OPERATION_PATH_UNRESOLVABLE', index, operation, document); - } - } - else if (operation.op === 'move' || operation.op === 'copy') { - var existingValue = { op: '_get', path: operation.from, value: undefined }; - var error = validate$1([existingValue], document); - if (error && error.name === 'OPERATION_PATH_UNRESOLVABLE') { - throw new JsonPatchError('Cannot perform the operation from a path that does not exist', 'OPERATION_FROM_UNRESOLVABLE', index, operation, document); - } - } - } + if (typeof operation !== 'object' || operation === null || Array.isArray(operation)) { + throw new JsonPatchError('Operation is not an object', 'OPERATION_NOT_AN_OBJECT', index, operation, document); + } + else if (!objOps[operation.op]) { + throw new JsonPatchError('Operation `op` property is not one of operations defined in RFC-6902', 'OPERATION_OP_INVALID', index, operation, document); + } + else if (typeof operation.path !== 'string') { + throw new JsonPatchError('Operation `path` property is not a string', 'OPERATION_PATH_INVALID', index, operation, document); + } + else if (operation.path.indexOf('/') !== 0 && operation.path.length > 0) { + // paths that aren't empty string should start with "/" + throw new JsonPatchError('Operation `path` property must start with "/"', 'OPERATION_PATH_INVALID', index, operation, document); + } + else if ((operation.op === 'move' || operation.op === 'copy') && typeof operation.from !== 'string') { + throw new JsonPatchError('Operation `from` property is not present (applicable in `move` and `copy` operations)', 'OPERATION_FROM_REQUIRED', index, operation, document); + } + else if ((operation.op === 'add' || operation.op === 'replace' || operation.op === 'test') && operation.value === undefined) { + throw new JsonPatchError('Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)', 'OPERATION_VALUE_REQUIRED', index, operation, document); + } + else if ((operation.op === 'add' || operation.op === 'replace' || operation.op === 'test') && hasUndefined(operation.value)) { + throw new JsonPatchError('Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)', 'OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED', index, operation, document); + } + else if (document) { + if (operation.op == "add") { + var pathLen = operation.path.split("/").length; + var existingPathLen = existingPathFragment.split("/").length; + if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) { + throw new JsonPatchError('Cannot perform an `add` operation at the desired path', 'OPERATION_PATH_CANNOT_ADD', index, operation, document); + } + } + else if (operation.op === 'replace' || operation.op === 'remove' || operation.op === '_get') { + if (operation.path !== existingPathFragment) { + throw new JsonPatchError('Cannot perform the operation at a path that does not exist', 'OPERATION_PATH_UNRESOLVABLE', index, operation, document); + } + } + else if (operation.op === 'move' || operation.op === 'copy') { + var existingValue = { op: "_get", path: operation.from, value: undefined }; + var error = validate$1([existingValue], document); + if (error && error.name === 'OPERATION_PATH_UNRESOLVABLE') { + throw new JsonPatchError('Cannot perform the operation from a path that does not exist', 'OPERATION_FROM_UNRESOLVABLE', index, operation, document); + } + } + } } /** * Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document. @@ -518,29 +518,29 @@ function validator$1(operation, index, document, existingPathFragment) { * @returns {JsonPatchError|undefined} */ function validate$1(sequence, document, externalValidator) { - try { - if (!Array.isArray(sequence)) { - throw new JsonPatchError('Patch sequence must be an array', 'SEQUENCE_NOT_AN_ARRAY'); - } - if (document) { - //clone document and sequence so that we can safely try applying operations - applyPatch(_deepClone(document), _deepClone(sequence), externalValidator || true); - } - else { - externalValidator = externalValidator || validator$1; - for (var i = 0; i < sequence.length; i++) { - externalValidator(sequence[i], i, document, undefined); - } - } - } - catch (e) { - if (e instanceof JsonPatchError) { - return e; - } - else { - throw e; - } - } + try { + if (!Array.isArray(sequence)) { + throw new JsonPatchError('Patch sequence must be an array', 'SEQUENCE_NOT_AN_ARRAY'); + } + if (document) { + //clone document and sequence so that we can safely try applying operations + applyPatch(_deepClone(document), _deepClone(sequence), externalValidator || true); + } + else { + externalValidator = externalValidator || validator$1; + for (var i = 0; i < sequence.length; i++) { + externalValidator(sequence[i], i, document, undefined); + } + } + } + catch (e) { + if (e instanceof JsonPatchError) { + return e; + } + else { + throw e; + } + } } // based on https://github.com/epoberezkin/fast-deep-equal // MIT License @@ -561,36 +561,36 @@ function validate$1(sequence, document, externalValidator) { // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. function _areEquals(a, b) { - if (a === b) - return true; - if (a && b && typeof a == 'object' && typeof b == 'object') { - var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key; - if (arrA && arrB) { - length = a.length; - if (length != b.length) - return false; - for (i = length; i-- !== 0;) - if (!_areEquals(a[i], b[i])) - return false; - return true; - } - if (arrA != arrB) - return false; - var keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) - return false; - for (i = length; i-- !== 0;) - if (!b.hasOwnProperty(keys[i])) - return false; - for (i = length; i-- !== 0;) { - key = keys[i]; - if (!_areEquals(a[key], b[key])) - return false; - } - return true; - } - return a !== a && b !== b; + if (a === b) + return true; + if (a && b && typeof a == 'object' && typeof b == 'object') { + var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key; + if (arrA && arrB) { + length = a.length; + if (length != b.length) + return false; + for (i = length; i-- !== 0;) + if (!_areEquals(a[i], b[i])) + return false; + return true; + } + if (arrA != arrB) + return false; + var keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) + return false; + for (i = length; i-- !== 0;) + if (!b.hasOwnProperty(keys[i])) + return false; + for (i = length; i-- !== 0;) { + key = keys[i]; + if (!_areEquals(a[key], b[key])) + return false; + } + return true; + } + return a !== a && b !== b; } var core = /*#__PURE__*/Object.freeze({ @@ -612,170 +612,170 @@ var core = /*#__PURE__*/Object.freeze({ * MIT license */ var beforeDict = new WeakMap(); -var Mirror = /** @class */ (function() { - function Mirror(obj) { - this.observers = new Map(); - this.obj = obj; - } - return Mirror; +var Mirror = /** @class */ (function () { + function Mirror(obj) { + this.observers = new Map(); + this.obj = obj; + } + return Mirror; }()); -var ObserverInfo = /** @class */ (function() { - function ObserverInfo(callback, observer) { - this.callback = callback; - this.observer = observer; - } - return ObserverInfo; +var ObserverInfo = /** @class */ (function () { + function ObserverInfo(callback, observer) { + this.callback = callback; + this.observer = observer; + } + return ObserverInfo; }()); function getMirror(obj) { - return beforeDict.get(obj); + return beforeDict.get(obj); } function getObserverFromMirror(mirror, callback) { - return mirror.observers.get(callback); + return mirror.observers.get(callback); } function removeObserverFromMirror(mirror, observer) { - mirror.observers.delete(observer.callback); + mirror.observers.delete(observer.callback); } /** * Detach an observer from an object */ function unobserve(root, observer) { - observer.unobserve(); + observer.unobserve(); } /** * Observes changes made to an object, which can then be retrieved using generate */ function observe(obj, callback) { - var patches = []; - var observer; - var mirror = getMirror(obj); - if (!mirror) { - mirror = new Mirror(obj); - beforeDict.set(obj, mirror); - } - else { - var observerInfo = getObserverFromMirror(mirror, callback); - observer = observerInfo && observerInfo.observer; - } - if (observer) { - return observer; - } - observer = {}; - mirror.value = _deepClone(obj); - if (callback) { - observer.callback = callback; - observer.next = null; - var dirtyCheck = function() { - generate(observer); - }; - var fastCheck = function() { - clearTimeout(observer.next); - observer.next = setTimeout(dirtyCheck); - }; - if (typeof window !== 'undefined') { //not Node - window.addEventListener('mouseup', fastCheck); - window.addEventListener('keyup', fastCheck); - window.addEventListener('mousedown', fastCheck); - window.addEventListener('keydown', fastCheck); - window.addEventListener('change', fastCheck); - } - } - observer.patches = patches; - observer.object = obj; - observer.unobserve = function() { - generate(observer); - clearTimeout(observer.next); - removeObserverFromMirror(mirror, observer); - if (typeof window !== 'undefined') { - window.removeEventListener('mouseup', fastCheck); - window.removeEventListener('keyup', fastCheck); - window.removeEventListener('mousedown', fastCheck); - window.removeEventListener('keydown', fastCheck); - window.removeEventListener('change', fastCheck); - } - }; - mirror.observers.set(callback, new ObserverInfo(callback, observer)); - return observer; + var patches = []; + var observer; + var mirror = getMirror(obj); + if (!mirror) { + mirror = new Mirror(obj); + beforeDict.set(obj, mirror); + } + else { + var observerInfo = getObserverFromMirror(mirror, callback); + observer = observerInfo && observerInfo.observer; + } + if (observer) { + return observer; + } + observer = {}; + mirror.value = _deepClone(obj); + if (callback) { + observer.callback = callback; + observer.next = null; + var dirtyCheck = function () { + generate(observer); + }; + var fastCheck = function () { + clearTimeout(observer.next); + observer.next = setTimeout(dirtyCheck); + }; + if (typeof window !== 'undefined') { //not Node + window.addEventListener('mouseup', fastCheck); + window.addEventListener('keyup', fastCheck); + window.addEventListener('mousedown', fastCheck); + window.addEventListener('keydown', fastCheck); + window.addEventListener('change', fastCheck); + } + } + observer.patches = patches; + observer.object = obj; + observer.unobserve = function () { + generate(observer); + clearTimeout(observer.next); + removeObserverFromMirror(mirror, observer); + if (typeof window !== 'undefined') { + window.removeEventListener('mouseup', fastCheck); + window.removeEventListener('keyup', fastCheck); + window.removeEventListener('mousedown', fastCheck); + window.removeEventListener('keydown', fastCheck); + window.removeEventListener('change', fastCheck); + } + }; + mirror.observers.set(callback, new ObserverInfo(callback, observer)); + return observer; } /** * Generate an array of patches from an observer */ function generate(observer, invertible) { - if (invertible === void 0) { invertible = false; } - var mirror = beforeDict.get(observer.object); - _generate(mirror.value, observer.object, observer.patches, '', invertible); - if (observer.patches.length) { - applyPatch(mirror.value, observer.patches); - } - var temp = observer.patches; - if (temp.length > 0) { - observer.patches = []; - if (observer.callback) { - observer.callback(temp); - } - } - return temp; + if (invertible === void 0) { invertible = false; } + var mirror = beforeDict.get(observer.object); + _generate(mirror.value, observer.object, observer.patches, "", invertible); + if (observer.patches.length) { + applyPatch(mirror.value, observer.patches); + } + var temp = observer.patches; + if (temp.length > 0) { + observer.patches = []; + if (observer.callback) { + observer.callback(temp); + } + } + return temp; } // Dirty check if obj is different from mirror, generate patches and update mirror function _generate(mirror, obj, patches, path, invertible) { - if (obj === mirror) { - return; - } - if (typeof obj.toJSON === 'function') { - obj = obj.toJSON(); - } - var newKeys = _objectKeys(obj); - var oldKeys = _objectKeys(mirror); - var deleted = false; - //if ever "move" operation is implemented here, make sure this test runs OK: "should not generate the same patch twice (move)" - for (var t = oldKeys.length - 1; t >= 0; t--) { - var key = oldKeys[t]; - var oldVal = mirror[key]; - if (hasOwnProperty$1(obj, key) && !(obj[key] === undefined && oldVal !== undefined && Array.isArray(obj) === false)) { - var newVal = obj[key]; - if (typeof oldVal == 'object' && oldVal != null && typeof newVal == 'object' && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) { - _generate(oldVal, newVal, patches, path + '/' + escapePathComponent(key), invertible); - } - else { - if (oldVal !== newVal) { - if (invertible) { - patches.push({ op: 'test', path: path + '/' + escapePathComponent(key), value: _deepClone(oldVal) }); - } - patches.push({ op: 'replace', path: path + '/' + escapePathComponent(key), value: _deepClone(newVal) }); - } - } - } - else if (Array.isArray(mirror) === Array.isArray(obj)) { - if (invertible) { - patches.push({ op: 'test', path: path + '/' + escapePathComponent(key), value: _deepClone(oldVal) }); - } - patches.push({ op: 'remove', path: path + '/' + escapePathComponent(key) }); - deleted = true; // property has been deleted - } - else { - if (invertible) { - patches.push({ op: 'test', path: path, value: mirror }); - } - patches.push({ op: 'replace', path: path, value: obj }); - } - } - if (!deleted && newKeys.length == oldKeys.length) { - return; - } - for (var t = 0; t < newKeys.length; t++) { - var key = newKeys[t]; - if (!hasOwnProperty$1(mirror, key) && obj[key] !== undefined) { - patches.push({ op: 'add', path: path + '/' + escapePathComponent(key), value: _deepClone(obj[key]) }); - } - } + if (obj === mirror) { + return; + } + if (typeof obj.toJSON === "function") { + obj = obj.toJSON(); + } + var newKeys = _objectKeys(obj); + var oldKeys = _objectKeys(mirror); + var deleted = false; + //if ever "move" operation is implemented here, make sure this test runs OK: "should not generate the same patch twice (move)" + for (var t = oldKeys.length - 1; t >= 0; t--) { + var key = oldKeys[t]; + var oldVal = mirror[key]; + if (hasOwnProperty$1(obj, key) && !(obj[key] === undefined && oldVal !== undefined && Array.isArray(obj) === false)) { + var newVal = obj[key]; + if (typeof oldVal == "object" && oldVal != null && typeof newVal == "object" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) { + _generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key), invertible); + } + else { + if (oldVal !== newVal) { + if (invertible) { + patches.push({ op: "test", path: path + "/" + escapePathComponent(key), value: _deepClone(oldVal) }); + } + patches.push({ op: "replace", path: path + "/" + escapePathComponent(key), value: _deepClone(newVal) }); + } + } + } + else if (Array.isArray(mirror) === Array.isArray(obj)) { + if (invertible) { + patches.push({ op: "test", path: path + "/" + escapePathComponent(key), value: _deepClone(oldVal) }); + } + patches.push({ op: "remove", path: path + "/" + escapePathComponent(key) }); + deleted = true; // property has been deleted + } + else { + if (invertible) { + patches.push({ op: "test", path: path, value: mirror }); + } + patches.push({ op: "replace", path: path, value: obj }); + } + } + if (!deleted && newKeys.length == oldKeys.length) { + return; + } + for (var t = 0; t < newKeys.length; t++) { + var key = newKeys[t]; + if (!hasOwnProperty$1(mirror, key) && obj[key] !== undefined) { + patches.push({ op: "add", path: path + "/" + escapePathComponent(key), value: _deepClone(obj[key]) }); + } + } } /** * Create an array of patches from the differences in two objects */ function compare(tree1, tree2, invertible) { - if (invertible === void 0) { invertible = false; } - var patches = []; - _generate(tree1, tree2, patches, '', invertible); - return patches; + if (invertible === void 0) { invertible = false; } + var patches = []; + _generate(tree1, tree2, patches, '', invertible); + return patches; } var duplex = /*#__PURE__*/Object.freeze({ @@ -787,10 +787,10 @@ var duplex = /*#__PURE__*/Object.freeze({ }); var index = Object.assign({}, core, duplex, { - JsonPatchError: PatchError, - deepClone: _deepClone, - escapePathComponent, - unescapePathComponent + JsonPatchError: PatchError, + deepClone: _deepClone, + escapePathComponent, + unescapePathComponent }); var fastJsonPatch = /*#__PURE__*/Object.freeze({ @@ -870,24 +870,24 @@ var stringify_1 = stringify$4; var getRandomValues; var rnds8 = new Uint8Array(16); function rng() { - // lazy load so that environments that need to polyfill have a chance to do so - if (!getRandomValues) { - // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also, - // find the complete implementation of crypto (msCrypto) on IE11. - getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto); - - if (!getRandomValues) { - throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); - } - } - - return getRandomValues(rnds8); + // lazy load so that environments that need to polyfill have a chance to do so + if (!getRandomValues) { + // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also, + // find the complete implementation of crypto (msCrypto) on IE11. + getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto); + + if (!getRandomValues) { + throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); + } + } + + return getRandomValues(rnds8); } var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; function validate(uuid) { - return typeof uuid === 'string' && REGEX.test(uuid); + return typeof uuid === 'string' && REGEX.test(uuid); } /** @@ -898,24 +898,24 @@ function validate(uuid) { var byteToHex = []; for (var i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).substr(1)); + byteToHex.push((i + 0x100).toString(16).substr(1)); } function stringify$3(arr) { - var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; - // Note: Be careful editing this code! It's been tuned for performance - // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one - // of the following: - // - One or more input array values don't map to a hex octet (leading to - // "undefined" in the uuid) - // - Invalid input values for the RFC `version` or `variant` fields - - if (!validate(uuid)) { - throw TypeError('Stringified UUID is invalid'); - } - - return uuid; + var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!validate(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; } // @@ -931,177 +931,177 @@ var _lastMSecs = 0; var _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details function v1(options, buf, offset) { - var i = buf && offset || 0; - var b = buf || new Array(16); - options = options || {}; - var node = options.node || _nodeId; - var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not - // specified. We do this lazily to minimize issues related to insufficient - // system entropy. See #189 - - if (node == null || clockseq == null) { - var seedBytes = options.random || (options.rng || rng)(); - - if (node == null) { - // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) - node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; - } - - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; - } - } // UUID timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so - // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + var i = buf && offset || 0; + var b = buf || new Array(16); + options = options || {}; + var node = options.node || _nodeId; + var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + if (node == null || clockseq == null) { + var seedBytes = options.random || (options.rng || rng)(); - var msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } - var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. - var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 0x3fff; - } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval + var msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; - } // Per 4.2.1.2 Throw error if too many uuids are requested - - - if (nsecs >= 10000) { - throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); - } - - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression - msecs += 12219292800000; // `time_low` + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval - var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; // `time_mid` - var tmh = msecs / 0x100000000 * 10000 & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; // `time_high_and_version` + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version - b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } - b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - b[i++] = clockseq & 0xff; // `node` + msecs += 12219292800000; // `time_low` - for (var n = 0; n < 6; ++n) { - b[i + n] = node[n]; - } + var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` - return buf || stringify$3(b); -} + var tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` -function parse(uuid) { - if (!validate(uuid)) { - throw TypeError('Invalid UUID'); - } + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version - var v; - var arr = new Uint8Array(16); // Parse ########-....-....-....-............ + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) - arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; - arr[1] = v >>> 16 & 0xff; - arr[2] = v >>> 8 & 0xff; - arr[3] = v & 0xff; // Parse ........-####-....-....-............ + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` - arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; - arr[5] = v & 0xff; // Parse ........-....-####-....-............ + b[i++] = clockseq & 0xff; // `node` - arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; - arr[7] = v & 0xff; // Parse ........-....-....-####-............ + for (var n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } - arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; - arr[9] = v & 0xff; // Parse ........-....-....-....-############ - // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + return buf || stringify$3(b); +} - arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; - arr[11] = v / 0x100000000 & 0xff; - arr[12] = v >>> 24 & 0xff; - arr[13] = v >>> 16 & 0xff; - arr[14] = v >>> 8 & 0xff; - arr[15] = v & 0xff; - return arr; +function parse(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + var v; + var arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; } function stringToBytes(str) { - str = unescape(encodeURIComponent(str)); // UTF8 escape + str = unescape(encodeURIComponent(str)); // UTF8 escape - var bytes = []; + var bytes = []; - for (var i = 0; i < str.length; ++i) { - bytes.push(str.charCodeAt(i)); - } + for (var i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } - return bytes; + return bytes; } var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; var URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; -function v35(name, version, hashfunc) { - function generateUUID(value, namespace, buf, offset) { - if (typeof value === 'string') { - value = stringToBytes(value); - } +function v35 (name, version, hashfunc) { + function generateUUID(value, namespace, buf, offset) { + if (typeof value === 'string') { + value = stringToBytes(value); + } - if (typeof namespace === 'string') { - namespace = parse(namespace); - } + if (typeof namespace === 'string') { + namespace = parse(namespace); + } - if (namespace.length !== 16) { - throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); - } // Compute hash of namespace and value, Per 4.3 - // Future: Use spread syntax when supported on all platforms, e.g. `bytes = - // hashfunc([...namespace, ... value])` + if (namespace.length !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` - var bytes = new Uint8Array(16 + value.length); - bytes.set(namespace); - bytes.set(value, namespace.length); - bytes = hashfunc(bytes); - bytes[6] = bytes[6] & 0x0f | version; - bytes[8] = bytes[8] & 0x3f | 0x80; + var bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; - if (buf) { - offset = offset || 0; + if (buf) { + offset = offset || 0; - for (var i = 0; i < 16; ++i) { - buf[offset + i] = bytes[i]; - } + for (var i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } - return buf; - } + return buf; + } - return stringify$3(bytes); - } // Function#name is not settable on some platforms (#270) + return stringify$3(bytes); + } // Function#name is not settable on some platforms (#270) - try { - generateUUID.name = name; // eslint-disable-next-line no-empty - } catch (err) {} // For CommonJS default export support + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support - generateUUID.DNS = DNS; - generateUUID.URL = URL; - return generateUUID; + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; } /* @@ -1125,17 +1125,17 @@ function v35(name, version, hashfunc) { * See http://pajhome.org.uk/crypt/md5 for more info. */ function md5(bytes) { - if (typeof bytes === 'string') { - var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + if (typeof bytes === 'string') { + var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape - bytes = new Uint8Array(msg.length); + bytes = new Uint8Array(msg.length); - for (var i = 0; i < msg.length; ++i) { - bytes[i] = msg.charCodeAt(i); - } - } + for (var i = 0; i < msg.length; ++i) { + bytes[i] = msg.charCodeAt(i); + } + } - return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); + return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); } /* * Convert an array of little-endian words to an array of bytes @@ -1143,17 +1143,17 @@ function md5(bytes) { function md5ToHexEncodedArray(input) { - var output = []; - var length32 = input.length * 32; - var hexTab = '0123456789abcdef'; - - for (var i = 0; i < length32; i += 8) { - var x = input[i >> 5] >>> i % 32 & 0xff; - var hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); - output.push(hex); - } + var output = []; + var length32 = input.length * 32; + var hexTab = '0123456789abcdef'; - return output; + for (var i = 0; i < length32; i += 8) { + var x = input[i >> 5] >>> i % 32 & 0xff; + var hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); + output.push(hex); + } + + return output; } /** * Calculate output length with padding and bit length @@ -1161,7 +1161,7 @@ function md5ToHexEncodedArray(input) { function getOutputLength(inputLength8) { - return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; + return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; } /* * Calculate the MD5 of an array of little-endian words, and a bit length. @@ -1169,90 +1169,90 @@ function getOutputLength(inputLength8) { function wordsToMd5(x, len) { - /* append padding */ - x[len >> 5] |= 0x80 << len % 32; - x[getOutputLength(len) - 1] = len; - var a = 1732584193; - var b = -271733879; - var c = -1732584194; - var d = 271733878; - - for (var i = 0; i < x.length; i += 16) { - var olda = a; - var oldb = b; - var oldc = c; - var oldd = d; - a = md5ff(a, b, c, d, x[i], 7, -680876936); - d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); - c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); - b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); - a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); - d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); - c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); - b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); - a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); - d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); - c = md5ff(c, d, a, b, x[i + 10], 17, -42063); - b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); - a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); - d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); - c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); - b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); - a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); - d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); - c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); - b = md5gg(b, c, d, a, x[i], 20, -373897302); - a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); - d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); - c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); - b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); - a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); - d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); - c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); - b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); - a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); - d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); - c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); - b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); - a = md5hh(a, b, c, d, x[i + 5], 4, -378558); - d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); - c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); - b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); - a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); - d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); - c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); - b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); - a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); - d = md5hh(d, a, b, c, x[i], 11, -358537222); - c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); - b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); - a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); - d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); - c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); - b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); - a = md5ii(a, b, c, d, x[i], 6, -198630844); - d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); - c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); - b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); - a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); - d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); - c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); - b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); - a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); - d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); - c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); - b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); - a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); - d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); - c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); - b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); - a = safeAdd(a, olda); - b = safeAdd(b, oldb); - c = safeAdd(c, oldc); - d = safeAdd(d, oldd); - } - - return [a, b, c, d]; + /* append padding */ + x[len >> 5] |= 0x80 << len % 32; + x[getOutputLength(len) - 1] = len; + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + var d = 271733878; + + for (var i = 0; i < x.length; i += 16) { + var olda = a; + var oldb = b; + var oldc = c; + var oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + + return [a, b, c, d]; } /* * Convert an array bytes to an array of little-endian words @@ -1261,18 +1261,18 @@ function wordsToMd5(x, len) { function bytesToWords(input) { - if (input.length === 0) { - return []; - } + if (input.length === 0) { + return []; + } - var length8 = input.length * 8; - var output = new Uint32Array(getOutputLength(length8)); + var length8 = input.length * 8; + var output = new Uint32Array(getOutputLength(length8)); - for (var i = 0; i < length8; i += 8) { - output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; - } + for (var i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; + } - return output; + return output; } /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally @@ -1281,9 +1281,9 @@ function bytesToWords(input) { function safeAdd(x, y) { - var lsw = (x & 0xffff) + (y & 0xffff); - var msw = (x >> 16) + (y >> 16) + (lsw >> 16); - return msw << 16 | lsw & 0xffff; + var lsw = (x & 0xffff) + (y & 0xffff); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 0xffff; } /* * Bitwise rotate a 32-bit number to the left. @@ -1291,7 +1291,7 @@ function safeAdd(x, y) { function bitRotateLeft(num, cnt) { - return num << cnt | num >>> 32 - cnt; + return num << cnt | num >>> 32 - cnt; } /* * These functions implement the four basic operations the algorithm uses. @@ -1299,141 +1299,141 @@ function bitRotateLeft(num, cnt) { function md5cmn(q, a, b, x, s, t) { - return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); } function md5ff(a, b, c, d, x, s, t) { - return md5cmn(b & c | ~b & d, a, b, x, s, t); + return md5cmn(b & c | ~b & d, a, b, x, s, t); } function md5gg(a, b, c, d, x, s, t) { - return md5cmn(b & d | c & ~d, a, b, x, s, t); + return md5cmn(b & d | c & ~d, a, b, x, s, t); } function md5hh(a, b, c, d, x, s, t) { - return md5cmn(b ^ c ^ d, a, b, x, s, t); + return md5cmn(b ^ c ^ d, a, b, x, s, t); } function md5ii(a, b, c, d, x, s, t) { - return md5cmn(c ^ (b | ~d), a, b, x, s, t); + return md5cmn(c ^ (b | ~d), a, b, x, s, t); } var v3 = v35('v3', 0x30, md5); var v3$1 = v3; function v4(options, buf, offset) { - options = options || {}; - var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + options = options || {}; + var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - rnds[6] = rnds[6] & 0x0f | 0x40; - rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided - if (buf) { - offset = offset || 0; + if (buf) { + offset = offset || 0; - for (var i = 0; i < 16; ++i) { - buf[offset + i] = rnds[i]; - } + for (var i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } - return buf; - } + return buf; + } - return stringify$3(rnds); + return stringify$3(rnds); } // Adapted from Chris Veness' SHA1 code at // http://www.movable-type.co.uk/scripts/sha1.html function f(s, x, y, z) { - switch (s) { - case 0: - return x & y ^ ~x & z; + switch (s) { + case 0: + return x & y ^ ~x & z; - case 1: - return x ^ y ^ z; + case 1: + return x ^ y ^ z; - case 2: - return x & y ^ x & z ^ y & z; + case 2: + return x & y ^ x & z ^ y & z; - case 3: - return x ^ y ^ z; - } + case 3: + return x ^ y ^ z; + } } function ROTL(x, n) { - return x << n | x >>> 32 - n; + return x << n | x >>> 32 - n; } function sha1(bytes) { - var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; - var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; - - if (typeof bytes === 'string') { - var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape - - bytes = []; - - for (var i = 0; i < msg.length; ++i) { - bytes.push(msg.charCodeAt(i)); - } - } else if (!Array.isArray(bytes)) { - // Convert Array-like to Array - bytes = Array.prototype.slice.call(bytes); - } - - bytes.push(0x80); - var l = bytes.length / 4 + 2; - var N = Math.ceil(l / 16); - var M = new Array(N); - - for (var _i = 0; _i < N; ++_i) { - var arr = new Uint32Array(16); - - for (var j = 0; j < 16; ++j) { - arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3]; - } - - M[_i] = arr; - } - - M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); - M[N - 1][14] = Math.floor(M[N - 1][14]); - M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; - - for (var _i2 = 0; _i2 < N; ++_i2) { - var W = new Uint32Array(80); - - for (var t = 0; t < 16; ++t) { - W[t] = M[_i2][t]; - } - - for (var _t = 16; _t < 80; ++_t) { - W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1); - } - - var a = H[0]; - var b = H[1]; - var c = H[2]; - var d = H[3]; - var e = H[4]; - - for (var _t2 = 0; _t2 < 80; ++_t2) { - var s = Math.floor(_t2 / 20); - var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[_t2] >>> 0; - e = d; - d = c; - c = ROTL(b, 30) >>> 0; - b = a; - a = T; - } - - H[0] = H[0] + a >>> 0; - H[1] = H[1] + b >>> 0; - H[2] = H[2] + c >>> 0; - H[3] = H[3] + d >>> 0; - H[4] = H[4] + e >>> 0; - } - - return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; + var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + + if (typeof bytes === 'string') { + var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = []; + + for (var i = 0; i < msg.length; ++i) { + bytes.push(msg.charCodeAt(i)); + } + } else if (!Array.isArray(bytes)) { + // Convert Array-like to Array + bytes = Array.prototype.slice.call(bytes); + } + + bytes.push(0x80); + var l = bytes.length / 4 + 2; + var N = Math.ceil(l / 16); + var M = new Array(N); + + for (var _i = 0; _i < N; ++_i) { + var arr = new Uint32Array(16); + + for (var j = 0; j < 16; ++j) { + arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3]; + } + + M[_i] = arr; + } + + M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; + + for (var _i2 = 0; _i2 < N; ++_i2) { + var W = new Uint32Array(80); + + for (var t = 0; t < 16; ++t) { + W[t] = M[_i2][t]; + } + + for (var _t = 16; _t < 80; ++_t) { + W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1); + } + + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + var e = H[4]; + + for (var _t2 = 0; _t2 < 80; ++_t2) { + var s = Math.floor(_t2 / 20); + var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[_t2] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + + return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; } var v5 = v35('v5', 0x50, sha1); @@ -1442,11 +1442,11 @@ var v5$1 = v5; var nil = '00000000-0000-0000-0000-000000000000'; function version(uuid) { - if (!validate(uuid)) { - throw TypeError('Invalid UUID'); - } + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } - return parseInt(uuid.substr(14, 1), 16); + return parseInt(uuid.substr(14, 1), 16); } var esmBrowser = /*#__PURE__*/Object.freeze({ @@ -1588,9 +1588,9 @@ var createPatch$1 = function createPatch(original, dto, options) { }; function bind(fn, thisArg) { - return function wrap() { - return fn.apply(thisArg, arguments); - }; + return function wrap() { + return fn.apply(thisArg, arguments); + }; } // utils is a library of generic helper functions non-specific to axios @@ -1599,13 +1599,13 @@ const {toString} = Object.prototype; const {getPrototypeOf} = Object; const kindOf = (cache => thing => { - const str = toString.call(thing); - return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); + const str = toString.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); })(Object.create(null)); const kindOfTest = (type) => { - type = type.toLowerCase(); - return (thing) => kindOf(thing) === type; + type = type.toLowerCase(); + return (thing) => kindOf(thing) === type }; const typeOfTest = type => thing => typeof thing === type; @@ -1636,7 +1636,7 @@ const isUndefined = typeOfTest('undefined'); * @returns {boolean} True if value is a Buffer, otherwise false */ function isBuffer(val) { - return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val); } @@ -1658,13 +1658,13 @@ const isArrayBuffer = kindOfTest('ArrayBuffer'); * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false */ function isArrayBufferView(val) { - let result; - if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { - result = ArrayBuffer.isView(val); - } else { - result = (val) && (val.buffer) && (isArrayBuffer(val.buffer)); - } - return result; + let result; + if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { + result = ArrayBuffer.isView(val); + } else { + result = (val) && (val.buffer) && (isArrayBuffer(val.buffer)); + } + return result; } /** @@ -1718,12 +1718,12 @@ const isBoolean = thing => thing === true || thing === false; * @returns {boolean} True if value is a plain Object, otherwise false */ const isPlainObject = (val) => { - if (kindOf(val) !== 'object') { - return false; - } + if (kindOf(val) !== 'object') { + return false; + } - const prototype = getPrototypeOf(val); - return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val); + const prototype = getPrototypeOf(val); + return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val); }; /** @@ -1779,16 +1779,16 @@ const isStream = (val) => isObject(val) && isFunction(val.pipe); * @returns {boolean} True if value is an FormData, otherwise false */ const isFormData = (thing) => { - let kind; - return thing && ( - (typeof FormData === 'function' && thing instanceof FormData) || ( - isFunction(thing.append) && ( - (kind = kindOf(thing)) === 'formdata' || + let kind; + return thing && ( + (typeof FormData === 'function' && thing instanceof FormData) || ( + isFunction(thing.append) && ( + (kind = kindOf(thing)) === 'formdata' || // detect form-data instance (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]') - ) - ) - ); + ) + ) + ) }; /** @@ -1808,7 +1808,7 @@ const isURLSearchParams = kindOfTest('URLSearchParams'); * @returns {String} The String freed of excess whitespace */ const trim = (str) => str.trim ? - str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); + str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); /** * Iterate over an Array or an Object invoking a function for each item. @@ -1826,56 +1826,56 @@ const trim = (str) => str.trim ? * @returns {any} */ function forEach(obj, fn, {allOwnKeys = false} = {}) { - // Don't bother if no value provided - if (obj === null || typeof obj === 'undefined') { - return; - } - - let i; - let l; - - // Force an array if not already something iterable - if (typeof obj !== 'object') { - /*eslint no-param-reassign:0*/ - obj = [obj]; - } - - if (isArray(obj)) { - // Iterate over array values - for (i = 0, l = obj.length; i < l; i++) { - fn.call(null, obj[i], i, obj); - } - } else { - // Iterate over object keys - const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); - const len = keys.length; - let key; - - for (i = 0; i < len; i++) { - key = keys[i]; - fn.call(null, obj[key], key, obj); - } - } + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; + } + + let i; + let l; + + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; + } + + if (isArray(obj)) { + // Iterate over array values + for (i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } + } else { + // Iterate over object keys + const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); + const len = keys.length; + let key; + + for (i = 0; i < len; i++) { + key = keys[i]; + fn.call(null, obj[key], key, obj); + } + } } function findKey(obj, key) { - key = key.toLowerCase(); - const keys = Object.keys(obj); - let i = keys.length; - let _key; - while (i-- > 0) { - _key = keys[i]; - if (key === _key.toLowerCase()) { - return _key; - } - } - return null; + key = key.toLowerCase(); + const keys = Object.keys(obj); + let i = keys.length; + let _key; + while (i-- > 0) { + _key = keys[i]; + if (key === _key.toLowerCase()) { + return _key; + } + } + return null; } const _global = (() => { - /*eslint no-undef:0*/ - if (typeof globalThis !== 'undefined') return globalThis; - return typeof self !== 'undefined' ? self : (typeof window !== 'undefined' ? window : commonjsGlobal); + /*eslint no-undef:0*/ + if (typeof globalThis !== "undefined") return globalThis; + return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : commonjsGlobal) })(); const isContextDefined = (context) => !isUndefined(context) && context !== _global; @@ -1899,25 +1899,25 @@ const isContextDefined = (context) => !isUndefined(context) && context !== _glob * @returns {Object} Result of all merge properties */ function merge(/* obj1, obj2, obj3, ... */) { - const {caseless} = isContextDefined(this) && this || {}; - const result = {}; - const assignValue = (val, key) => { - const targetKey = caseless && findKey(result, key) || key; - if (isPlainObject(result[targetKey]) && isPlainObject(val)) { - result[targetKey] = merge(result[targetKey], val); - } else if (isPlainObject(val)) { - result[targetKey] = merge({}, val); - } else if (isArray(val)) { - result[targetKey] = val.slice(); - } else { - result[targetKey] = val; - } - }; - - for (let i = 0, l = arguments.length; i < l; i++) { - arguments[i] && forEach(arguments[i], assignValue); - } - return result; + const {caseless} = isContextDefined(this) && this || {}; + const result = {}; + const assignValue = (val, key) => { + const targetKey = caseless && findKey(result, key) || key; + if (isPlainObject(result[targetKey]) && isPlainObject(val)) { + result[targetKey] = merge(result[targetKey], val); + } else if (isPlainObject(val)) { + result[targetKey] = merge({}, val); + } else if (isArray(val)) { + result[targetKey] = val.slice(); + } else { + result[targetKey] = val; + } + }; + + for (let i = 0, l = arguments.length; i < l; i++) { + arguments[i] && forEach(arguments[i], assignValue); + } + return result; } /** @@ -1931,14 +1931,14 @@ function merge(/* obj1, obj2, obj3, ... */) { * @returns {Object} The resulting value of object a */ const extend = (a, b, thisArg, {allOwnKeys}= {}) => { - forEach(b, (val, key) => { - if (thisArg && isFunction(val)) { - a[key] = bind(val, thisArg); - } else { - a[key] = val; - } - }, {allOwnKeys}); - return a; + forEach(b, (val, key) => { + if (thisArg && isFunction(val)) { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }, {allOwnKeys}); + return a; }; /** @@ -1949,10 +1949,10 @@ const extend = (a, b, thisArg, {allOwnKeys}= {}) => { * @returns {string} content value without BOM */ const stripBOM = (content) => { - if (content.charCodeAt(0) === 0xFEFF) { - content = content.slice(1); - } - return content; + if (content.charCodeAt(0) === 0xFEFF) { + content = content.slice(1); + } + return content; }; /** @@ -1965,12 +1965,12 @@ const stripBOM = (content) => { * @returns {void} */ const inherits = (constructor, superConstructor, props, descriptors) => { - constructor.prototype = Object.create(superConstructor.prototype, descriptors); - constructor.prototype.constructor = constructor; - Object.defineProperty(constructor, 'super', { - value: superConstructor.prototype - }); - props && Object.assign(constructor.prototype, props); + constructor.prototype = Object.create(superConstructor.prototype, descriptors); + constructor.prototype.constructor = constructor; + Object.defineProperty(constructor, 'super', { + value: superConstructor.prototype + }); + props && Object.assign(constructor.prototype, props); }; /** @@ -1983,29 +1983,29 @@ const inherits = (constructor, superConstructor, props, descriptors) => { * @returns {Object} */ const toFlatObject = (sourceObj, destObj, filter, propFilter) => { - let props; - let i; - let prop; - const merged = {}; - - destObj = destObj || {}; - // eslint-disable-next-line no-eq-null,eqeqeq - if (sourceObj == null) return destObj; - - do { - props = Object.getOwnPropertyNames(sourceObj); - i = props.length; - while (i-- > 0) { - prop = props[i]; - if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { - destObj[prop] = sourceObj[prop]; - merged[prop] = true; - } - } - sourceObj = filter !== false && getPrototypeOf(sourceObj); - } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); - - return destObj; + let props; + let i; + let prop; + const merged = {}; + + destObj = destObj || {}; + // eslint-disable-next-line no-eq-null,eqeqeq + if (sourceObj == null) return destObj; + + do { + props = Object.getOwnPropertyNames(sourceObj); + i = props.length; + while (i-- > 0) { + prop = props[i]; + if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { + destObj[prop] = sourceObj[prop]; + merged[prop] = true; + } + } + sourceObj = filter !== false && getPrototypeOf(sourceObj); + } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); + + return destObj; }; /** @@ -2018,13 +2018,13 @@ const toFlatObject = (sourceObj, destObj, filter, propFilter) => { * @returns {boolean} */ const endsWith = (str, searchString, position) => { - str = String(str); - if (position === undefined || position > str.length) { - position = str.length; - } - position -= searchString.length; - const lastIndex = str.indexOf(searchString, position); - return lastIndex !== -1 && lastIndex === position; + str = String(str); + if (position === undefined || position > str.length) { + position = str.length; + } + position -= searchString.length; + const lastIndex = str.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; }; @@ -2036,15 +2036,15 @@ const endsWith = (str, searchString, position) => { * @returns {?Array} */ const toArray = (thing) => { - if (!thing) return null; - if (isArray(thing)) return thing; - let i = thing.length; - if (!isNumber(i)) return null; - const arr = new Array(i); - while (i-- > 0) { - arr[i] = thing[i]; - } - return arr; + if (!thing) return null; + if (isArray(thing)) return thing; + let i = thing.length; + if (!isNumber(i)) return null; + const arr = new Array(i); + while (i-- > 0) { + arr[i] = thing[i]; + } + return arr; }; /** @@ -2057,10 +2057,10 @@ const toArray = (thing) => { */ // eslint-disable-next-line func-names const isTypedArray = (TypedArray => { - // eslint-disable-next-line func-names - return thing => { - return TypedArray && thing instanceof TypedArray; - }; + // eslint-disable-next-line func-names + return thing => { + return TypedArray && thing instanceof TypedArray; + }; })(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array)); /** @@ -2072,16 +2072,16 @@ const isTypedArray = (TypedArray => { * @returns {void} */ const forEachEntry = (obj, fn) => { - const generator = obj && obj[Symbol.iterator]; + const generator = obj && obj[Symbol.iterator]; - const iterator = generator.call(obj); + const iterator = generator.call(obj); - let result; + let result; - while ((result = iterator.next()) && !result.done) { - const pair = result.value; - fn.call(obj, pair[0], pair[1]); - } + while ((result = iterator.next()) && !result.done) { + const pair = result.value; + fn.call(obj, pair[0], pair[1]); + } }; /** @@ -2093,25 +2093,25 @@ const forEachEntry = (obj, fn) => { * @returns {Array} */ const matchAll = (regExp, str) => { - let matches; - const arr = []; + let matches; + const arr = []; - while ((matches = regExp.exec(str)) !== null) { - arr.push(matches); - } + while ((matches = regExp.exec(str)) !== null) { + arr.push(matches); + } - return arr; + return arr; }; /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ const isHTMLForm = kindOfTest('HTMLFormElement'); const toCamelCase = str => { - return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, - function replacer(m, p1, p2) { - return p1.toUpperCase() + p2; - } - ); + return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, + function replacer(m, p1, p2) { + return p1.toUpperCase() + p2; + } + ); }; /* Creating a function that will check if an object has a property. */ @@ -2127,17 +2127,17 @@ const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call const isRegExp = kindOfTest('RegExp'); const reduceDescriptors = (obj, reducer) => { - const descriptors = Object.getOwnPropertyDescriptors(obj); - const reducedDescriptors = {}; + const descriptors = Object.getOwnPropertyDescriptors(obj); + const reducedDescriptors = {}; - forEach(descriptors, (descriptor, name) => { - let ret; - if ((ret = reducer(descriptor, name, obj)) !== false) { - reducedDescriptors[name] = ret || descriptor; - } - }); + forEach(descriptors, (descriptor, name) => { + let ret; + if ((ret = reducer(descriptor, name, obj)) !== false) { + reducedDescriptors[name] = ret || descriptor; + } + }); - Object.defineProperties(obj, reducedDescriptors); + Object.defineProperties(obj, reducedDescriptors); }; /** @@ -2146,50 +2146,50 @@ const reduceDescriptors = (obj, reducer) => { */ const freezeMethods = (obj) => { - reduceDescriptors(obj, (descriptor, name) => { - // skip restricted props in strict mode - if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) { - return false; - } + reduceDescriptors(obj, (descriptor, name) => { + // skip restricted props in strict mode + if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) { + return false; + } - const value = obj[name]; + const value = obj[name]; - if (!isFunction(value)) return; + if (!isFunction(value)) return; - descriptor.enumerable = false; + descriptor.enumerable = false; - if ('writable' in descriptor) { - descriptor.writable = false; - return; - } + if ('writable' in descriptor) { + descriptor.writable = false; + return; + } - if (!descriptor.set) { - descriptor.set = () => { - throw Error('Can not rewrite read-only method \'' + name + '\''); - }; - } - }); + if (!descriptor.set) { + descriptor.set = () => { + throw Error('Can not rewrite read-only method \'' + name + '\''); + }; + } + }); }; const toObjectSet = (arrayOrString, delimiter) => { - const obj = {}; + const obj = {}; - const define = (arr) => { - arr.forEach(value => { - obj[value] = true; - }); - }; + const define = (arr) => { + arr.forEach(value => { + obj[value] = true; + }); + }; - isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); + isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); - return obj; + return obj; }; const noop = () => {}; const toFiniteNumber = (value, defaultValue) => { - value = +value; - return Number.isFinite(value) ? value : defaultValue; + value = +value; + return Number.isFinite(value) ? value : defaultValue; }; const ALPHA = 'abcdefghijklmnopqrstuvwxyz'; @@ -2197,19 +2197,19 @@ const ALPHA = 'abcdefghijklmnopqrstuvwxyz'; const DIGIT = '0123456789'; const ALPHABET = { - DIGIT, - ALPHA, - ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT + DIGIT, + ALPHA, + ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT }; const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { - let str = ''; - const {length} = alphabet; - while (size--) { - str += alphabet[Math.random() * length|0]; - } + let str = ''; + const {length} = alphabet; + while (size--) { + str += alphabet[Math.random() * length|0]; + } - return str; + return str; }; /** @@ -2220,97 +2220,97 @@ const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { * @returns {boolean} */ function isSpecCompliantForm(thing) { - return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]); + return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]); } const toJSONObject = (obj) => { - const stack = new Array(10); + const stack = new Array(10); - const visit = (source, i) => { + const visit = (source, i) => { - if (isObject(source)) { - if (stack.indexOf(source) >= 0) { - return; - } + if (isObject(source)) { + if (stack.indexOf(source) >= 0) { + return; + } - if(!('toJSON' in source)) { - stack[i] = source; - const target = isArray(source) ? [] : {}; + if(!('toJSON' in source)) { + stack[i] = source; + const target = isArray(source) ? [] : {}; - forEach(source, (value, key) => { - const reducedValue = visit(value, i + 1); - !isUndefined(reducedValue) && (target[key] = reducedValue); - }); + forEach(source, (value, key) => { + const reducedValue = visit(value, i + 1); + !isUndefined(reducedValue) && (target[key] = reducedValue); + }); - stack[i] = undefined; + stack[i] = undefined; - return target; - } - } + return target; + } + } - return source; - }; + return source; + }; - return visit(obj, 0); + return visit(obj, 0); }; const isAsyncFn = kindOfTest('AsyncFunction'); const isThenable = (thing) => - thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); + thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); var utils$1 = { - isArray, - isArrayBuffer, - isBuffer, - isFormData, - isArrayBufferView, - isString, - isNumber, - isBoolean, - isObject, - isPlainObject, - isUndefined, - isDate, - isFile, - isBlob, - isRegExp, - isFunction, - isStream, - isURLSearchParams, - isTypedArray, - isFileList, - forEach, - merge, - extend, - trim, - stripBOM, - inherits, - toFlatObject, - kindOf, - kindOfTest, - endsWith, - toArray, - forEachEntry, - matchAll, - isHTMLForm, - hasOwnProperty, - hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection - reduceDescriptors, - freezeMethods, - toObjectSet, - toCamelCase, - noop, - toFiniteNumber, - findKey, - global: _global, - isContextDefined, - ALPHABET, - generateString, - isSpecCompliantForm, - toJSONObject, - isAsyncFn, - isThenable + isArray, + isArrayBuffer, + isBuffer, + isFormData, + isArrayBufferView, + isString, + isNumber, + isBoolean, + isObject, + isPlainObject, + isUndefined, + isDate, + isFile, + isBlob, + isRegExp, + isFunction, + isStream, + isURLSearchParams, + isTypedArray, + isFileList, + forEach, + merge, + extend, + trim, + stripBOM, + inherits, + toFlatObject, + kindOf, + kindOfTest, + endsWith, + toArray, + forEachEntry, + matchAll, + isHTMLForm, + hasOwnProperty, + hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection + reduceDescriptors, + freezeMethods, + toObjectSet, + toCamelCase, + noop, + toFiniteNumber, + findKey, + global: _global, + isContextDefined, + ALPHABET, + generateString, + isSpecCompliantForm, + toJSONObject, + isAsyncFn, + isThenable }; /** @@ -2325,63 +2325,63 @@ var utils$1 = { * @returns {Error} The created error. */ function AxiosError(message, code, config, request, response) { - Error.call(this); - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } else { - this.stack = (new Error()).stack; - } - - this.message = message; - this.name = 'AxiosError'; - code && (this.code = code); - config && (this.config = config); - request && (this.request = request); - response && (this.response = response); + Error.call(this); + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = (new Error()).stack; + } + + this.message = message; + this.name = 'AxiosError'; + code && (this.code = code); + config && (this.config = config); + request && (this.request = request); + response && (this.response = response); } utils$1.inherits(AxiosError, Error, { - toJSON: function toJSON() { - return { - // Standard - message: this.message, - name: this.name, - // Microsoft - description: this.description, - number: this.number, - // Mozilla - fileName: this.fileName, - lineNumber: this.lineNumber, - columnNumber: this.columnNumber, - stack: this.stack, - // Axios - config: utils$1.toJSONObject(this.config), - code: this.code, - status: this.response && this.response.status ? this.response.status : null - }; - } + toJSON: function toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: utils$1.toJSONObject(this.config), + code: this.code, + status: this.response && this.response.status ? this.response.status : null + }; + } }); const prototype$1 = AxiosError.prototype; const descriptors = {}; [ - 'ERR_BAD_OPTION_VALUE', - 'ERR_BAD_OPTION', - 'ECONNABORTED', - 'ETIMEDOUT', - 'ERR_NETWORK', - 'ERR_FR_TOO_MANY_REDIRECTS', - 'ERR_DEPRECATED', - 'ERR_BAD_RESPONSE', - 'ERR_BAD_REQUEST', - 'ERR_CANCELED', - 'ERR_NOT_SUPPORT', - 'ERR_INVALID_URL' + 'ERR_BAD_OPTION_VALUE', + 'ERR_BAD_OPTION', + 'ECONNABORTED', + 'ETIMEDOUT', + 'ERR_NETWORK', + 'ERR_FR_TOO_MANY_REDIRECTS', + 'ERR_DEPRECATED', + 'ERR_BAD_RESPONSE', + 'ERR_BAD_REQUEST', + 'ERR_CANCELED', + 'ERR_NOT_SUPPORT', + 'ERR_INVALID_URL' // eslint-disable-next-line func-names ].forEach(code => { - descriptors[code] = {value: code}; + descriptors[code] = {value: code}; }); Object.defineProperties(AxiosError, descriptors); @@ -2389,23 +2389,23 @@ Object.defineProperty(prototype$1, 'isAxiosError', {value: true}); // eslint-disable-next-line func-names AxiosError.from = (error, code, config, request, response, customProps) => { - const axiosError = Object.create(prototype$1); + const axiosError = Object.create(prototype$1); - utils$1.toFlatObject(error, axiosError, function filter(obj) { - return obj !== Error.prototype; - }, prop => { - return prop !== 'isAxiosError'; - }); + utils$1.toFlatObject(error, axiosError, function filter(obj) { + return obj !== Error.prototype; + }, prop => { + return prop !== 'isAxiosError'; + }); - AxiosError.call(axiosError, error.message, code, config, request, response); + AxiosError.call(axiosError, error.message, code, config, request, response); - axiosError.cause = error; + axiosError.cause = error; - axiosError.name = error.name; + axiosError.name = error.name; - customProps && Object.assign(axiosError, customProps); + customProps && Object.assign(axiosError, customProps); - return axiosError; + return axiosError; }; // eslint-disable-next-line strict @@ -2419,7 +2419,7 @@ var httpAdapter$1 = null; * @returns {boolean} */ function isVisitable(thing) { - return utils$1.isPlainObject(thing) || utils$1.isArray(thing); + return utils$1.isPlainObject(thing) || utils$1.isArray(thing); } /** @@ -2430,7 +2430,7 @@ function isVisitable(thing) { * @returns {string} the key without the brackets. */ function removeBrackets(key) { - return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key; + return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key; } /** @@ -2443,12 +2443,12 @@ function removeBrackets(key) { * @returns {string} The path to the current key. */ function renderKey(path, key, dots) { - if (!path) return key; - return path.concat(key).map(function each(token, i) { - // eslint-disable-next-line no-param-reassign - token = removeBrackets(token); - return !dots && i ? '[' + token + ']' : token; - }).join(dots ? '.' : ''); + if (!path) return key; + return path.concat(key).map(function each(token, i) { + // eslint-disable-next-line no-param-reassign + token = removeBrackets(token); + return !dots && i ? '[' + token + ']' : token; + }).join(dots ? '.' : ''); } /** @@ -2459,11 +2459,11 @@ function renderKey(path, key, dots) { * @returns {boolean} */ function isFlatArray(arr) { - return utils$1.isArray(arr) && !arr.some(isVisitable); + return utils$1.isArray(arr) && !arr.some(isVisitable); } const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) { - return /^is[A-Z]/.test(prop); + return /^is[A-Z]/.test(prop); }); /** @@ -2490,136 +2490,136 @@ const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) * @returns */ function toFormData(obj, formData, options) { - if (!utils$1.isObject(obj)) { - throw new TypeError('target must be an object'); - } + if (!utils$1.isObject(obj)) { + throw new TypeError('target must be an object'); + } + + // eslint-disable-next-line no-param-reassign + formData = formData || new (FormData)(); + + // eslint-disable-next-line no-param-reassign + options = utils$1.toFlatObject(options, { + metaTokens: true, + dots: false, + indexes: false + }, false, function defined(option, source) { + // eslint-disable-next-line no-eq-null,eqeqeq + return !utils$1.isUndefined(source[option]); + }); + + const metaTokens = options.metaTokens; + // eslint-disable-next-line no-use-before-define + const visitor = options.visitor || defaultVisitor; + const dots = options.dots; + const indexes = options.indexes; + const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob; + const useBlob = _Blob && utils$1.isSpecCompliantForm(formData); + + if (!utils$1.isFunction(visitor)) { + throw new TypeError('visitor must be a function'); + } + + function convertValue(value) { + if (value === null) return ''; + + if (utils$1.isDate(value)) { + return value.toISOString(); + } + + if (!useBlob && utils$1.isBlob(value)) { + throw new AxiosError('Blob is not supported. Use a Buffer instead.'); + } + + if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) { + return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); + } + + return value; + } + + /** + * Default visitor. + * + * @param {*} value + * @param {String|Number} key + * @param {Array} path + * @this {FormData} + * + * @returns {boolean} return true to visit the each prop of the value recursively + */ + function defaultVisitor(value, key, path) { + let arr = value; + + if (value && !path && typeof value === 'object') { + if (utils$1.endsWith(key, '{}')) { + // eslint-disable-next-line no-param-reassign + key = metaTokens ? key : key.slice(0, -2); + // eslint-disable-next-line no-param-reassign + value = JSON.stringify(value); + } else if ( + (utils$1.isArray(value) && isFlatArray(value)) || + ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value)) + )) { + // eslint-disable-next-line no-param-reassign + key = removeBrackets(key); - // eslint-disable-next-line no-param-reassign - formData = formData || new (FormData)(); - - // eslint-disable-next-line no-param-reassign - options = utils$1.toFlatObject(options, { - metaTokens: true, - dots: false, - indexes: false - }, false, function defined(option, source) { - // eslint-disable-next-line no-eq-null,eqeqeq - return !utils$1.isUndefined(source[option]); - }); + arr.forEach(function each(el, index) { + !(utils$1.isUndefined(el) || el === null) && formData.append( + // eslint-disable-next-line no-nested-ternary + indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'), + convertValue(el) + ); + }); + return false; + } + } - const metaTokens = options.metaTokens; - // eslint-disable-next-line no-use-before-define - const visitor = options.visitor || defaultVisitor; - const dots = options.dots; - const indexes = options.indexes; - const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob; - const useBlob = _Blob && utils$1.isSpecCompliantForm(formData); + if (isVisitable(value)) { + return true; + } - if (!utils$1.isFunction(visitor)) { - throw new TypeError('visitor must be a function'); - } + formData.append(renderKey(path, key, dots), convertValue(value)); - function convertValue(value) { - if (value === null) return ''; + return false; + } - if (utils$1.isDate(value)) { - return value.toISOString(); - } + const stack = []; - if (!useBlob && utils$1.isBlob(value)) { - throw new AxiosError('Blob is not supported. Use a Buffer instead.'); - } + const exposedHelpers = Object.assign(predicates, { + defaultVisitor, + convertValue, + isVisitable + }); - if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) { - return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); - } + function build(value, path) { + if (utils$1.isUndefined(value)) return; - return value; - } + if (stack.indexOf(value) !== -1) { + throw Error('Circular reference detected in ' + path.join('.')); + } - /** - * Default visitor. - * - * @param {*} value - * @param {String|Number} key - * @param {Array} path - * @this {FormData} - * - * @returns {boolean} return true to visit the each prop of the value recursively - */ - function defaultVisitor(value, key, path) { - let arr = value; - - if (value && !path && typeof value === 'object') { - if (utils$1.endsWith(key, '{}')) { - // eslint-disable-next-line no-param-reassign - key = metaTokens ? key : key.slice(0, -2); - // eslint-disable-next-line no-param-reassign - value = JSON.stringify(value); - } else if ( - (utils$1.isArray(value) && isFlatArray(value)) || - ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value)) - )) { - // eslint-disable-next-line no-param-reassign - key = removeBrackets(key); - - arr.forEach(function each(el, index) { - !(utils$1.isUndefined(el) || el === null) && formData.append( - // eslint-disable-next-line no-nested-ternary - indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'), - convertValue(el) - ); - }); - return false; - } - } + stack.push(value); - if (isVisitable(value)) { - return true; - } - - formData.append(renderKey(path, key, dots), convertValue(value)); - - return false; - } + utils$1.forEach(value, function each(el, key) { + const result = !(utils$1.isUndefined(el) || el === null) && visitor.call( + formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers + ); - const stack = []; + if (result === true) { + build(el, path ? path.concat(key) : [key]); + } + }); - const exposedHelpers = Object.assign(predicates, { - defaultVisitor, - convertValue, - isVisitable - }); - - function build(value, path) { - if (utils$1.isUndefined(value)) return; - - if (stack.indexOf(value) !== -1) { - throw Error('Circular reference detected in ' + path.join('.')); - } + stack.pop(); + } - stack.push(value); - - utils$1.forEach(value, function each(el, key) { - const result = !(utils$1.isUndefined(el) || el === null) && visitor.call( - formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers - ); - - if (result === true) { - build(el, path ? path.concat(key) : [key]); - } - }); - - stack.pop(); - } - - if (!utils$1.isObject(obj)) { - throw new TypeError('data must be an object'); - } + if (!utils$1.isObject(obj)) { + throw new TypeError('data must be an object'); + } - build(obj); + build(obj); - return formData; + return formData; } /** @@ -2631,18 +2631,18 @@ function toFormData(obj, formData, options) { * @returns {string} The encoded string. */ function encode$1(str) { - const charMap = { - '!': '%21', - '\'': '%27', - '(': '%28', - ')': '%29', - '~': '%7E', - '%20': '+', - '%00': '\x00' - }; - return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { - return charMap[match]; - }); + const charMap = { + '!': '%21', + "'": '%27', + '(': '%28', + ')': '%29', + '~': '%7E', + '%20': '+', + '%00': '\x00' + }; + return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { + return charMap[match]; + }); } /** @@ -2654,25 +2654,25 @@ function encode$1(str) { * @returns {void} */ function AxiosURLSearchParams(params, options) { - this._pairs = []; + this._pairs = []; - params && toFormData(params, this, options); + params && toFormData(params, this, options); } const prototype = AxiosURLSearchParams.prototype; prototype.append = function append(name, value) { - this._pairs.push([name, value]); + this._pairs.push([name, value]); }; prototype.toString = function toString(encoder) { - const _encode = encoder ? function(value) { - return encoder.call(this, value, encode$1); - } : encode$1; + const _encode = encoder ? function(value) { + return encoder.call(this, value, encode$1); + } : encode$1; - return this._pairs.map(function each(pair) { - return _encode(pair[0]) + '=' + _encode(pair[1]); - }, '').join('&'); + return this._pairs.map(function each(pair) { + return _encode(pair[0]) + '=' + _encode(pair[1]); + }, '').join('&'); }; /** @@ -2684,13 +2684,13 @@ prototype.toString = function toString(encoder) { * @returns {string} The encoded value. */ function encode(val) { - return encodeURIComponent(val). - replace(/%3A/gi, ':'). - replace(/%24/g, '$'). - replace(/%2C/gi, ','). - replace(/%20/g, '+'). - replace(/%5B/gi, '['). - replace(/%5D/gi, ']'); + return encodeURIComponent(val). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%20/g, '+'). + replace(/%5B/gi, '['). + replace(/%5D/gi, ']'); } /** @@ -2703,43 +2703,43 @@ function encode(val) { * @returns {string} The formatted url */ function buildURL(url, params, options) { - /*eslint no-param-reassign:0*/ - if (!params) { - return url; - } - - const _encode = options && options.encode || encode; - - const serializeFn = options && options.serialize; - - let serializedParams; - - if (serializeFn) { - serializedParams = serializeFn(params, options); - } else { - serializedParams = utils$1.isURLSearchParams(params) ? - params.toString() : - new AxiosURLSearchParams(params, options).toString(_encode); - } - - if (serializedParams) { - const hashmarkIndex = url.indexOf('#'); - - if (hashmarkIndex !== -1) { - url = url.slice(0, hashmarkIndex); - } - url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; - } - - return url; + /*eslint no-param-reassign:0*/ + if (!params) { + return url; + } + + const _encode = options && options.encode || encode; + + const serializeFn = options && options.serialize; + + let serializedParams; + + if (serializeFn) { + serializedParams = serializeFn(params, options); + } else { + serializedParams = utils$1.isURLSearchParams(params) ? + params.toString() : + new AxiosURLSearchParams(params, options).toString(_encode); + } + + if (serializedParams) { + const hashmarkIndex = url.indexOf("#"); + + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } + url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; + } + + return url; } class InterceptorManager { - constructor() { - this.handlers = []; - } + constructor() { + this.handlers = []; + } - /** + /** * Add a new interceptor to the stack * * @param {Function} fulfilled The function to handle `then` for a `Promise` @@ -2747,41 +2747,41 @@ class InterceptorManager { * * @return {Number} An ID used to remove interceptor later */ - use(fulfilled, rejected, options) { - this.handlers.push({ - fulfilled, - rejected, - synchronous: options ? options.synchronous : false, - runWhen: options ? options.runWhen : null - }); - return this.handlers.length - 1; - } - - /** + use(fulfilled, rejected, options) { + this.handlers.push({ + fulfilled, + rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null + }); + return this.handlers.length - 1; + } + + /** * Remove an interceptor from the stack * * @param {Number} id The ID that was returned by `use` * * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise */ - eject(id) { - if (this.handlers[id]) { - this.handlers[id] = null; - } - } + eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } + } - /** + /** * Clear all interceptors from the stack * * @returns {void} */ - clear() { - if (this.handlers) { - this.handlers = []; - } - } + clear() { + if (this.handlers) { + this.handlers = []; + } + } - /** + /** * Iterate over all the registered interceptors * * This method is particularly useful for skipping over any @@ -2791,21 +2791,21 @@ class InterceptorManager { * * @returns {void} */ - forEach(fn) { - utils$1.forEach(this.handlers, function forEachHandler(h) { - if (h !== null) { - fn(h); - } - }); - } + forEach(fn) { + utils$1.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); + } } var InterceptorManager$1 = InterceptorManager; var transitionalDefaults = { - silentJSONParsing: true, - forcedJSONParsing: true, - clarifyTimeoutError: false + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false }; var URLSearchParams$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams; @@ -2815,13 +2815,13 @@ var FormData$1 = typeof FormData !== 'undefined' ? FormData : null; var Blob$1 = typeof Blob !== 'undefined' ? Blob : null; var platform$1 = { - isBrowser: true, - classes: { - URLSearchParams: URLSearchParams$1, - FormData: FormData$1, - Blob: Blob$1 - }, - protocols: ['http', 'https', 'file', 'blob', 'url', 'data'] + isBrowser: true, + classes: { + URLSearchParams: URLSearchParams$1, + FormData: FormData$1, + Blob: Blob$1 + }, + protocols: ['http', 'https', 'file', 'blob', 'url', 'data'] }; const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined'; @@ -2844,9 +2844,9 @@ const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'unde * @returns {boolean} */ const hasStandardBrowserEnv = ( - (product) => { - return hasBrowserEnv && ['ReactNative', 'NativeScript', 'NS'].indexOf(product) < 0; - })(typeof navigator !== 'undefined' && navigator.product); + (product) => { + return hasBrowserEnv && ['ReactNative', 'NativeScript', 'NS'].indexOf(product) < 0 + })(typeof navigator !== 'undefined' && navigator.product); /** * Determine if we're running in a standard browser webWorker environment @@ -2858,37 +2858,37 @@ const hasStandardBrowserEnv = ( * This leads to a problem when axios post `FormData` in webWorker */ const hasStandardBrowserWebWorkerEnv = (() => { - return ( - typeof WorkerGlobalScope !== 'undefined' && + return ( + typeof WorkerGlobalScope !== 'undefined' && // eslint-disable-next-line no-undef self instanceof WorkerGlobalScope && typeof self.importScripts === 'function' - ); + ); })(); var utils = /*#__PURE__*/Object.freeze({ - __proto__: null, - hasBrowserEnv: hasBrowserEnv, - hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv, - hasStandardBrowserEnv: hasStandardBrowserEnv + __proto__: null, + hasBrowserEnv: hasBrowserEnv, + hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv, + hasStandardBrowserEnv: hasStandardBrowserEnv }); var platform = { - ...utils, - ...platform$1 + ...utils, + ...platform$1 }; function toURLEncodedForm(data, options) { - return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({ - visitor: function(value, key, path, helpers) { - if (platform.isNode && utils$1.isBuffer(value)) { - this.append(key, value.toString('base64')); - return false; - } - - return helpers.defaultVisitor.apply(this, arguments); - } - }, options)); + return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({ + visitor: function(value, key, path, helpers) { + if (platform.isNode && utils$1.isBuffer(value)) { + this.append(key, value.toString('base64')); + return false; + } + + return helpers.defaultVisitor.apply(this, arguments); + } + }, options)); } /** @@ -2899,13 +2899,13 @@ function toURLEncodedForm(data, options) { * @returns An array of strings. */ function parsePropPath(name) { - // foo[x][y][z] - // foo.x.y.z - // foo-x-y-z - // foo x y z - return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map(match => { - return match[0] === '[]' ? '' : match[1] || match[0]; - }); + // foo[x][y][z] + // foo.x.y.z + // foo-x-y-z + // foo x y z + return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map(match => { + return match[0] === '[]' ? '' : match[1] || match[0]; + }); } /** @@ -2916,16 +2916,16 @@ function parsePropPath(name) { * @returns An object with the same keys and values as the array. */ function arrayToObject(arr) { - const obj = {}; - const keys = Object.keys(arr); - let i; - const len = keys.length; - let key; - for (i = 0; i < len; i++) { - key = keys[i]; - obj[key] = arr[key]; - } - return obj; + const obj = {}; + const keys = Object.keys(arr); + let i; + const len = keys.length; + let key; + for (i = 0; i < len; i++) { + key = keys[i]; + obj[key] = arr[key]; + } + return obj; } /** @@ -2936,46 +2936,46 @@ function arrayToObject(arr) { * @returns {Object | null} The converted object. */ function formDataToJSON(formData) { - function buildPath(path, value, target, index) { - let name = path[index++]; - const isNumericKey = Number.isFinite(+name); - const isLast = index >= path.length; - name = !name && utils$1.isArray(target) ? target.length : name; - - if (isLast) { - if (utils$1.hasOwnProp(target, name)) { - target[name] = [target[name], value]; - } else { - target[name] = value; - } + function buildPath(path, value, target, index) { + let name = path[index++]; + const isNumericKey = Number.isFinite(+name); + const isLast = index >= path.length; + name = !name && utils$1.isArray(target) ? target.length : name; - return !isNumericKey; - } + if (isLast) { + if (utils$1.hasOwnProp(target, name)) { + target[name] = [target[name], value]; + } else { + target[name] = value; + } - if (!target[name] || !utils$1.isObject(target[name])) { - target[name] = []; - } + return !isNumericKey; + } - const result = buildPath(path, value, target[name], index); + if (!target[name] || !utils$1.isObject(target[name])) { + target[name] = []; + } - if (result && utils$1.isArray(target[name])) { - target[name] = arrayToObject(target[name]); - } + const result = buildPath(path, value, target[name], index); - return !isNumericKey; - } + if (result && utils$1.isArray(target[name])) { + target[name] = arrayToObject(target[name]); + } - if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) { - const obj = {}; + return !isNumericKey; + } - utils$1.forEachEntry(formData, (name, value) => { - buildPath(parsePropPath(name), value, obj, 0); - }); + if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) { + const obj = {}; - return obj; - } + utils$1.forEachEntry(formData, (name, value) => { + buildPath(parsePropPath(name), value, obj, 0); + }); + + return obj; + } - return null; + return null; } /** @@ -2989,141 +2989,141 @@ function formDataToJSON(formData) { * @returns {string} A stringified version of the rawValue. */ function stringifySafely(rawValue, parser, encoder) { - if (utils$1.isString(rawValue)) { - try { - (parser || JSON.parse)(rawValue); - return utils$1.trim(rawValue); - } catch (e) { - if (e.name !== 'SyntaxError') { - throw e; - } - } - } - - return (encoder || JSON.stringify)(rawValue); + if (utils$1.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils$1.trim(rawValue); + } catch (e) { + if (e.name !== 'SyntaxError') { + throw e; + } + } + } + + return (encoder || JSON.stringify)(rawValue); } const defaults = { - transitional: transitionalDefaults, + transitional: transitionalDefaults, - adapter: ['xhr', 'http'], + adapter: ['xhr', 'http'], - transformRequest: [function transformRequest(data, headers) { - const contentType = headers.getContentType() || ''; - const hasJSONContentType = contentType.indexOf('application/json') > -1; - const isObjectPayload = utils$1.isObject(data); + transformRequest: [function transformRequest(data, headers) { + const contentType = headers.getContentType() || ''; + const hasJSONContentType = contentType.indexOf('application/json') > -1; + const isObjectPayload = utils$1.isObject(data); - if (isObjectPayload && utils$1.isHTMLForm(data)) { - data = new FormData(data); - } + if (isObjectPayload && utils$1.isHTMLForm(data)) { + data = new FormData(data); + } - const isFormData = utils$1.isFormData(data); + const isFormData = utils$1.isFormData(data); - if (isFormData) { - if (!hasJSONContentType) { - return data; - } - return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data; - } + if (isFormData) { + if (!hasJSONContentType) { + return data; + } + return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data; + } - if (utils$1.isArrayBuffer(data) || + if (utils$1.isArrayBuffer(data) || utils$1.isBuffer(data) || utils$1.isStream(data) || utils$1.isFile(data) || utils$1.isBlob(data) - ) { - return data; - } - if (utils$1.isArrayBufferView(data)) { - return data.buffer; - } - if (utils$1.isURLSearchParams(data)) { - headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false); - return data.toString(); - } - - let isFileList; - - if (isObjectPayload) { - if (contentType.indexOf('application/x-www-form-urlencoded') > -1) { - return toURLEncodedForm(data, this.formSerializer).toString(); - } - - if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) { - const _FormData = this.env && this.env.FormData; - - return toFormData( - isFileList ? {'files[]': data} : data, - _FormData && new _FormData(), - this.formSerializer - ); - } - } - - if (isObjectPayload || hasJSONContentType ) { - headers.setContentType('application/json', false); - return stringifySafely(data); - } - - return data; - }], - - transformResponse: [function transformResponse(data) { - const transitional = this.transitional || defaults.transitional; - const forcedJSONParsing = transitional && transitional.forcedJSONParsing; - const JSONRequested = this.responseType === 'json'; - - if (data && utils$1.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) { - const silentJSONParsing = transitional && transitional.silentJSONParsing; - const strictJSONParsing = !silentJSONParsing && JSONRequested; - - try { - return JSON.parse(data); - } catch (e) { - if (strictJSONParsing) { - if (e.name === 'SyntaxError') { - throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); - } - throw e; - } - } - } - - return data; - }], - - /** + ) { + return data; + } + if (utils$1.isArrayBufferView(data)) { + return data.buffer; + } + if (utils$1.isURLSearchParams(data)) { + headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false); + return data.toString(); + } + + let isFileList; + + if (isObjectPayload) { + if (contentType.indexOf('application/x-www-form-urlencoded') > -1) { + return toURLEncodedForm(data, this.formSerializer).toString(); + } + + if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) { + const _FormData = this.env && this.env.FormData; + + return toFormData( + isFileList ? {'files[]': data} : data, + _FormData && new _FormData(), + this.formSerializer + ); + } + } + + if (isObjectPayload || hasJSONContentType ) { + headers.setContentType('application/json', false); + return stringifySafely(data); + } + + return data; + }], + + transformResponse: [function transformResponse(data) { + const transitional = this.transitional || defaults.transitional; + const forcedJSONParsing = transitional && transitional.forcedJSONParsing; + const JSONRequested = this.responseType === 'json'; + + if (data && utils$1.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) { + const silentJSONParsing = transitional && transitional.silentJSONParsing; + const strictJSONParsing = !silentJSONParsing && JSONRequested; + + try { + return JSON.parse(data); + } catch (e) { + if (strictJSONParsing) { + if (e.name === 'SyntaxError') { + throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); + } + throw e; + } + } + } + + return data; + }], + + /** * A timeout in milliseconds to abort a request. If set to 0 (default) a * timeout is not created. */ - timeout: 0, + timeout: 0, - xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN', + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', - maxContentLength: -1, - maxBodyLength: -1, + maxContentLength: -1, + maxBodyLength: -1, - env: { - FormData: platform.classes.FormData, - Blob: platform.classes.Blob - }, + env: { + FormData: platform.classes.FormData, + Blob: platform.classes.Blob + }, - validateStatus: function validateStatus(status) { - return status >= 200 && status < 300; - }, + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + }, - headers: { - common: { - 'Accept': 'application/json, text/plain, */*', - 'Content-Type': undefined - } - } + headers: { + common: { + 'Accept': 'application/json, text/plain, */*', + 'Content-Type': undefined + } + } }; utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => { - defaults.headers[method] = {}; + defaults.headers[method] = {}; }); var defaults$1 = defaults; @@ -3131,10 +3131,10 @@ var defaults$1 = defaults; // RawAxiosHeaders whose duplicates are ignored by node // c.f. https://nodejs.org/api/http.html#http_message_headers const ignoreDuplicateOf = utils$1.toObjectSet([ - 'age', 'authorization', 'content-length', 'content-type', 'etag', - 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', - 'last-modified', 'location', 'max-forwards', 'proxy-authorization', - 'referer', 'retry-after', 'user-agent' + 'age', 'authorization', 'content-length', 'content-type', 'etag', + 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', + 'last-modified', 'location', 'max-forwards', 'proxy-authorization', + 'referer', 'retry-after', 'user-agent' ]); /** @@ -3152,322 +3152,322 @@ const ignoreDuplicateOf = utils$1.toObjectSet([ * @returns {Object} Headers parsed into an object */ var parseHeaders = rawHeaders => { - const parsed = {}; - let key; - let val; - let i; - - rawHeaders && rawHeaders.split('\n').forEach(function parser(line) { - i = line.indexOf(':'); - key = line.substring(0, i).trim().toLowerCase(); - val = line.substring(i + 1).trim(); - - if (!key || (parsed[key] && ignoreDuplicateOf[key])) { - return; - } - - if (key === 'set-cookie') { - if (parsed[key]) { - parsed[key].push(val); - } else { - parsed[key] = [val]; - } - } else { - parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; - } - }); - - return parsed; + const parsed = {}; + let key; + let val; + let i; + + rawHeaders && rawHeaders.split('\n').forEach(function parser(line) { + i = line.indexOf(':'); + key = line.substring(0, i).trim().toLowerCase(); + val = line.substring(i + 1).trim(); + + if (!key || (parsed[key] && ignoreDuplicateOf[key])) { + return; + } + + if (key === 'set-cookie') { + if (parsed[key]) { + parsed[key].push(val); + } else { + parsed[key] = [val]; + } + } else { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + } + }); + + return parsed; }; const $internals = Symbol('internals'); function normalizeHeader(header) { - return header && String(header).trim().toLowerCase(); + return header && String(header).trim().toLowerCase(); } function normalizeValue(value) { - if (value === false || value == null) { - return value; - } + if (value === false || value == null) { + return value; + } - return utils$1.isArray(value) ? value.map(normalizeValue) : String(value); + return utils$1.isArray(value) ? value.map(normalizeValue) : String(value); } function parseTokens(str) { - const tokens = Object.create(null); - const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; - let match; + const tokens = Object.create(null); + const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; + let match; - while ((match = tokensRE.exec(str))) { - tokens[match[1]] = match[2]; - } + while ((match = tokensRE.exec(str))) { + tokens[match[1]] = match[2]; + } - return tokens; + return tokens; } const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { - if (utils$1.isFunction(filter)) { - return filter.call(this, value, header); - } + if (utils$1.isFunction(filter)) { + return filter.call(this, value, header); + } - if (isHeaderNameFilter) { - value = header; - } + if (isHeaderNameFilter) { + value = header; + } - if (!utils$1.isString(value)) return; + if (!utils$1.isString(value)) return; - if (utils$1.isString(filter)) { - return value.indexOf(filter) !== -1; - } + if (utils$1.isString(filter)) { + return value.indexOf(filter) !== -1; + } - if (utils$1.isRegExp(filter)) { - return filter.test(value); - } + if (utils$1.isRegExp(filter)) { + return filter.test(value); + } } function formatHeader(header) { - return header.trim() - .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => { - return char.toUpperCase() + str; - }); + return header.trim() + .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => { + return char.toUpperCase() + str; + }); } function buildAccessors(obj, header) { - const accessorName = utils$1.toCamelCase(' ' + header); - - ['get', 'set', 'has'].forEach(methodName => { - Object.defineProperty(obj, methodName + accessorName, { - value: function(arg1, arg2, arg3) { - return this[methodName].call(this, header, arg1, arg2, arg3); - }, - configurable: true - }); - }); + const accessorName = utils$1.toCamelCase(' ' + header); + + ['get', 'set', 'has'].forEach(methodName => { + Object.defineProperty(obj, methodName + accessorName, { + value: function(arg1, arg2, arg3) { + return this[methodName].call(this, header, arg1, arg2, arg3); + }, + configurable: true + }); + }); } class AxiosHeaders { - constructor(headers) { - headers && this.set(headers); - } + constructor(headers) { + headers && this.set(headers); + } - set(header, valueOrRewrite, rewrite) { - const self = this; + set(header, valueOrRewrite, rewrite) { + const self = this; - function setHeader(_value, _header, _rewrite) { - const lHeader = normalizeHeader(_header); + function setHeader(_value, _header, _rewrite) { + const lHeader = normalizeHeader(_header); - if (!lHeader) { - throw new Error('header name must be a non-empty string'); - } + if (!lHeader) { + throw new Error('header name must be a non-empty string'); + } - const key = utils$1.findKey(self, lHeader); + const key = utils$1.findKey(self, lHeader); - if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) { - self[key || _header] = normalizeValue(_value); - } - } + if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) { + self[key || _header] = normalizeValue(_value); + } + } - const setHeaders = (headers, _rewrite) => - utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); + const setHeaders = (headers, _rewrite) => + utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); - if (utils$1.isPlainObject(header) || header instanceof this.constructor) { - setHeaders(header, valueOrRewrite); - } else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { - setHeaders(parseHeaders(header), valueOrRewrite); - } else { - header != null && setHeader(valueOrRewrite, header, rewrite); - } + if (utils$1.isPlainObject(header) || header instanceof this.constructor) { + setHeaders(header, valueOrRewrite); + } else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { + setHeaders(parseHeaders(header), valueOrRewrite); + } else { + header != null && setHeader(valueOrRewrite, header, rewrite); + } - return this; - } + return this; + } - get(header, parser) { - header = normalizeHeader(header); + get(header, parser) { + header = normalizeHeader(header); - if (header) { - const key = utils$1.findKey(this, header); + if (header) { + const key = utils$1.findKey(this, header); - if (key) { - const value = this[key]; + if (key) { + const value = this[key]; - if (!parser) { - return value; - } + if (!parser) { + return value; + } - if (parser === true) { - return parseTokens(value); - } + if (parser === true) { + return parseTokens(value); + } - if (utils$1.isFunction(parser)) { - return parser.call(this, value, key); - } + if (utils$1.isFunction(parser)) { + return parser.call(this, value, key); + } - if (utils$1.isRegExp(parser)) { - return parser.exec(value); - } + if (utils$1.isRegExp(parser)) { + return parser.exec(value); + } - throw new TypeError('parser must be boolean|regexp|function'); - } - } - } + throw new TypeError('parser must be boolean|regexp|function'); + } + } + } - has(header, matcher) { - header = normalizeHeader(header); + has(header, matcher) { + header = normalizeHeader(header); - if (header) { - const key = utils$1.findKey(this, header); + if (header) { + const key = utils$1.findKey(this, header); - return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher))); - } + return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher))); + } - return false; - } + return false; + } - delete(header, matcher) { - const self = this; - let deleted = false; + delete(header, matcher) { + const self = this; + let deleted = false; - function deleteHeader(_header) { - _header = normalizeHeader(_header); + function deleteHeader(_header) { + _header = normalizeHeader(_header); - if (_header) { - const key = utils$1.findKey(self, _header); + if (_header) { + const key = utils$1.findKey(self, _header); - if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) { - delete self[key]; + if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) { + delete self[key]; - deleted = true; - } - } - } + deleted = true; + } + } + } - if (utils$1.isArray(header)) { - header.forEach(deleteHeader); - } else { - deleteHeader(header); - } + if (utils$1.isArray(header)) { + header.forEach(deleteHeader); + } else { + deleteHeader(header); + } - return deleted; - } + return deleted; + } - clear(matcher) { - const keys = Object.keys(this); - let i = keys.length; - let deleted = false; + clear(matcher) { + const keys = Object.keys(this); + let i = keys.length; + let deleted = false; - while (i--) { - const key = keys[i]; - if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { - delete this[key]; - deleted = true; - } - } + while (i--) { + const key = keys[i]; + if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { + delete this[key]; + deleted = true; + } + } - return deleted; - } + return deleted; + } - normalize(format) { - const self = this; - const headers = {}; + normalize(format) { + const self = this; + const headers = {}; - utils$1.forEach(this, (value, header) => { - const key = utils$1.findKey(headers, header); + utils$1.forEach(this, (value, header) => { + const key = utils$1.findKey(headers, header); - if (key) { - self[key] = normalizeValue(value); - delete self[header]; - return; - } + if (key) { + self[key] = normalizeValue(value); + delete self[header]; + return; + } - const normalized = format ? formatHeader(header) : String(header).trim(); + const normalized = format ? formatHeader(header) : String(header).trim(); - if (normalized !== header) { - delete self[header]; - } + if (normalized !== header) { + delete self[header]; + } - self[normalized] = normalizeValue(value); + self[normalized] = normalizeValue(value); - headers[normalized] = true; - }); + headers[normalized] = true; + }); - return this; - } + return this; + } - concat(...targets) { - return this.constructor.concat(this, ...targets); - } + concat(...targets) { + return this.constructor.concat(this, ...targets); + } - toJSON(asStrings) { - const obj = Object.create(null); + toJSON(asStrings) { + const obj = Object.create(null); - utils$1.forEach(this, (value, header) => { - value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value); - }); + utils$1.forEach(this, (value, header) => { + value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value); + }); - return obj; - } + return obj; + } - [Symbol.iterator]() { - return Object.entries(this.toJSON())[Symbol.iterator](); - } + [Symbol.iterator]() { + return Object.entries(this.toJSON())[Symbol.iterator](); + } - toString() { - return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n'); - } + toString() { + return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n'); + } - get [Symbol.toStringTag]() { - return 'AxiosHeaders'; - } + get [Symbol.toStringTag]() { + return 'AxiosHeaders'; + } - static from(thing) { - return thing instanceof this ? thing : new this(thing); - } + static from(thing) { + return thing instanceof this ? thing : new this(thing); + } - static concat(first, ...targets) { - const computed = new this(first); + static concat(first, ...targets) { + const computed = new this(first); - targets.forEach((target) => computed.set(target)); + targets.forEach((target) => computed.set(target)); - return computed; - } + return computed; + } - static accessor(header) { - const internals = this[$internals] = (this[$internals] = { - accessors: {} - }); + static accessor(header) { + const internals = this[$internals] = (this[$internals] = { + accessors: {} + }); - const accessors = internals.accessors; - const prototype = this.prototype; + const accessors = internals.accessors; + const prototype = this.prototype; - function defineAccessor(_header) { - const lHeader = normalizeHeader(_header); + function defineAccessor(_header) { + const lHeader = normalizeHeader(_header); - if (!accessors[lHeader]) { - buildAccessors(prototype, _header); - accessors[lHeader] = true; - } - } + if (!accessors[lHeader]) { + buildAccessors(prototype, _header); + accessors[lHeader] = true; + } + } - utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); + utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); - return this; - } + return this; + } } AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']); // reserved names hotfix utils$1.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => { - let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set` - return { - get: () => value, - set(headerValue) { - this[mapped] = headerValue; - } - }; + let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set` + return { + get: () => value, + set(headerValue) { + this[mapped] = headerValue; + } + } }); utils$1.freezeMethods(AxiosHeaders); @@ -3483,22 +3483,22 @@ var AxiosHeaders$1 = AxiosHeaders; * @returns {*} The resulting transformed data */ function transformData(fns, response) { - const config = this || defaults$1; - const context = response || config; - const headers = AxiosHeaders$1.from(context.headers); - let data = context.data; + const config = this || defaults$1; + const context = response || config; + const headers = AxiosHeaders$1.from(context.headers); + let data = context.data; - utils$1.forEach(fns, function transform(fn) { - data = fn.call(config, data, headers.normalize(), response ? response.status : undefined); - }); + utils$1.forEach(fns, function transform(fn) { + data = fn.call(config, data, headers.normalize(), response ? response.status : undefined); + }); - headers.normalize(); + headers.normalize(); - return data; + return data; } function isCancel(value) { - return !!(value && value.__CANCEL__); + return !!(value && value.__CANCEL__); } /** @@ -3511,13 +3511,13 @@ function isCancel(value) { * @returns {CanceledError} The created error. */ function CanceledError(message, config, request) { - // eslint-disable-next-line no-eq-null,eqeqeq - AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request); - this.name = 'CanceledError'; + // eslint-disable-next-line no-eq-null,eqeqeq + AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request); + this.name = 'CanceledError'; } utils$1.inherits(CanceledError, AxiosError, { - __CANCEL__: true + __CANCEL__: true }); /** @@ -3530,58 +3530,58 @@ utils$1.inherits(CanceledError, AxiosError, { * @returns {object} The response. */ function settle(resolve, reject, response) { - const validateStatus = response.config.validateStatus; - if (!response.status || !validateStatus || validateStatus(response.status)) { - resolve(response); - } else { - reject(new AxiosError( - 'Request failed with status code ' + response.status, - [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], - response.config, - response.request, - response - )); - } + const validateStatus = response.config.validateStatus; + if (!response.status || !validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(new AxiosError( + 'Request failed with status code ' + response.status, + [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + response.config, + response.request, + response + )); + } } var cookies = platform.hasStandardBrowserEnv ? -// Standard browser envs support document.cookie - { - write(name, value, expires, path, domain, secure) { - const cookie = [name + '=' + encodeURIComponent(value)]; + // Standard browser envs support document.cookie + { + write(name, value, expires, path, domain, secure) { + const cookie = [name + '=' + encodeURIComponent(value)]; - utils$1.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString()); + utils$1.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString()); - utils$1.isString(path) && cookie.push('path=' + path); + utils$1.isString(path) && cookie.push('path=' + path); - utils$1.isString(domain) && cookie.push('domain=' + domain); + utils$1.isString(domain) && cookie.push('domain=' + domain); - secure === true && cookie.push('secure'); + secure === true && cookie.push('secure'); - document.cookie = cookie.join('; '); - }, + document.cookie = cookie.join('; '); + }, - read(name) { - const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); - return (match ? decodeURIComponent(match[3]) : null); - }, + read(name) { + const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); + return (match ? decodeURIComponent(match[3]) : null); + }, - remove(name) { - this.write(name, '', Date.now() - 86400000); - } - } + remove(name) { + this.write(name, '', Date.now() - 86400000); + } + } - : + : -// Non-standard browser env (web workers, react-native) lack needed support. - { - write() {}, - read() { - return null; - }, - remove() {} - }; + // Non-standard browser env (web workers, react-native) lack needed support. + { + write() {}, + read() { + return null; + }, + remove() {} + }; /** * Determines whether the specified URL is absolute @@ -3591,10 +3591,10 @@ var cookies = platform.hasStandardBrowserEnv ? * @returns {boolean} True if the specified URL is absolute, otherwise false */ function isAbsoluteURL(url) { - // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). - // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed - // by any combination of letters, digits, plus, period, or hyphen. - return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); + // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); } /** @@ -3606,9 +3606,9 @@ function isAbsoluteURL(url) { * @returns {string} The combined URL */ function combineURLs(baseURL, relativeURL) { - return relativeURL - ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') - : baseURL; + return relativeURL + ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; } /** @@ -3622,78 +3622,78 @@ function combineURLs(baseURL, relativeURL) { * @returns {string} The combined full path */ function buildFullPath(baseURL, requestedURL) { - if (baseURL && !isAbsoluteURL(requestedURL)) { - return combineURLs(baseURL, requestedURL); - } - return requestedURL; + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; } var isURLSameOrigin = platform.hasStandardBrowserEnv ? // Standard browser envs have full support of the APIs needed to test // whether the request URL is of the same origin as current location. - (function standardBrowserEnv() { - const msie = /(msie|trident)/i.test(navigator.userAgent); - const urlParsingNode = document.createElement('a'); - let originURL; + (function standardBrowserEnv() { + const msie = /(msie|trident)/i.test(navigator.userAgent); + const urlParsingNode = document.createElement('a'); + let originURL; - /** + /** * Parse a URL to discover its components * * @param {String} url The URL to be parsed * @returns {Object} */ - function resolveURL(url) { - let href = url; - - if (msie) { - // IE needs attribute set twice to normalize properties - urlParsingNode.setAttribute('href', href); - href = urlParsingNode.href; - } - - urlParsingNode.setAttribute('href', href); - - // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils - return { - href: urlParsingNode.href, - protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', - host: urlParsingNode.host, - search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', - hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', - hostname: urlParsingNode.hostname, - port: urlParsingNode.port, - pathname: (urlParsingNode.pathname.charAt(0) === '/') ? - urlParsingNode.pathname : - '/' + urlParsingNode.pathname - }; - } - - originURL = resolveURL(window.location.href); - - /** + function resolveURL(url) { + let href = url; + + if (msie) { + // IE needs attribute set twice to normalize properties + urlParsingNode.setAttribute('href', href); + href = urlParsingNode.href; + } + + urlParsingNode.setAttribute('href', href); + + // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils + return { + href: urlParsingNode.href, + protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', + host: urlParsingNode.host, + search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', + hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', + hostname: urlParsingNode.hostname, + port: urlParsingNode.port, + pathname: (urlParsingNode.pathname.charAt(0) === '/') ? + urlParsingNode.pathname : + '/' + urlParsingNode.pathname + }; + } + + originURL = resolveURL(window.location.href); + + /** * Determine if a URL shares the same origin as the current location * * @param {String} requestURL The URL to test * @returns {boolean} True if URL shares the same origin, otherwise false */ - return function isURLSameOrigin(requestURL) { - const parsed = (utils$1.isString(requestURL)) ? resolveURL(requestURL) : requestURL; - return (parsed.protocol === originURL.protocol && + return function isURLSameOrigin(requestURL) { + const parsed = (utils$1.isString(requestURL)) ? resolveURL(requestURL) : requestURL; + return (parsed.protocol === originURL.protocol && parsed.host === originURL.host); - }; - })() : + }; + })() : -// Non standard browser envs (web workers, react-native) lack needed support. - (function nonStandardBrowserEnv() { - return function isURLSameOrigin() { - return true; - }; - })(); + // Non standard browser envs (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return function isURLSameOrigin() { + return true; + }; + })(); function parseProtocol(url) { - const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); - return match && match[1] || ''; + const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); + return match && match[1] || ''; } /** @@ -3703,310 +3703,310 @@ function parseProtocol(url) { * @returns {Function} */ function speedometer(samplesCount, min) { - samplesCount = samplesCount || 10; - const bytes = new Array(samplesCount); - const timestamps = new Array(samplesCount); - let head = 0; - let tail = 0; - let firstSampleTS; + samplesCount = samplesCount || 10; + const bytes = new Array(samplesCount); + const timestamps = new Array(samplesCount); + let head = 0; + let tail = 0; + let firstSampleTS; - min = min !== undefined ? min : 1000; + min = min !== undefined ? min : 1000; - return function push(chunkLength) { - const now = Date.now(); + return function push(chunkLength) { + const now = Date.now(); - const startedAt = timestamps[tail]; + const startedAt = timestamps[tail]; - if (!firstSampleTS) { - firstSampleTS = now; - } + if (!firstSampleTS) { + firstSampleTS = now; + } - bytes[head] = chunkLength; - timestamps[head] = now; + bytes[head] = chunkLength; + timestamps[head] = now; - let i = tail; - let bytesCount = 0; + let i = tail; + let bytesCount = 0; - while (i !== head) { - bytesCount += bytes[i++]; - i = i % samplesCount; - } + while (i !== head) { + bytesCount += bytes[i++]; + i = i % samplesCount; + } - head = (head + 1) % samplesCount; + head = (head + 1) % samplesCount; - if (head === tail) { - tail = (tail + 1) % samplesCount; - } + if (head === tail) { + tail = (tail + 1) % samplesCount; + } - if (now - firstSampleTS < min) { - return; - } + if (now - firstSampleTS < min) { + return; + } - const passed = startedAt && now - startedAt; + const passed = startedAt && now - startedAt; - return passed ? Math.round(bytesCount * 1000 / passed) : undefined; - }; + return passed ? Math.round(bytesCount * 1000 / passed) : undefined; + }; } -function progressEventReducer(listener, isDownloadStream) { - let bytesNotified = 0; - const _speedometer = speedometer(50, 250); - - return e => { - const loaded = e.loaded; - const total = e.lengthComputable ? e.total : undefined; - const progressBytes = loaded - bytesNotified; - const rate = _speedometer(progressBytes); - const inRange = loaded <= total; - - bytesNotified = loaded; - - const data = { - loaded, - total, - progress: total ? (loaded / total) : undefined, - bytes: progressBytes, - rate: rate ? rate : undefined, - estimated: rate && total && inRange ? (total - loaded) / rate : undefined, - event: e - }; - - data[isDownloadStream ? 'download' : 'upload'] = true; - - listener(data); - }; -} - -const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; - -var xhrAdapter = isXHRAdapterSupported && function(config) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - let requestData = config.data; - const requestHeaders = AxiosHeaders$1.from(config.headers).normalize(); - let {responseType, withXSRFToken} = config; - let onCanceled; - function done() { - if (config.cancelToken) { - config.cancelToken.unsubscribe(onCanceled); - } - - if (config.signal) { - config.signal.removeEventListener('abort', onCanceled); - } - } - - let contentType; - - if (utils$1.isFormData(requestData)) { - if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) { - requestHeaders.setContentType(false); // Let the browser set it - } else if ((contentType = requestHeaders.getContentType()) !== false) { - // fix semicolon duplication issue for ReactNative FormData implementation - const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : []; - requestHeaders.setContentType([type || 'multipart/form-data', ...tokens].join('; ')); - } - } - - let request = new XMLHttpRequest(); - - // HTTP basic authentication - if (config.auth) { - const username = config.auth.username || ''; - const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; - requestHeaders.set('Authorization', 'Basic ' + btoa(username + ':' + password)); - } - - const fullPath = buildFullPath(config.baseURL, config.url); - - request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); - - // Set the request timeout in MS - request.timeout = config.timeout; - - function onloadend() { - if (!request) { - return; - } - // Prepare the response - const responseHeaders = AxiosHeaders$1.from( - 'getAllResponseHeaders' in request && request.getAllResponseHeaders() - ); - const responseData = !responseType || responseType === 'text' || responseType === 'json' ? - request.responseText : request.response; - const response = { - data: responseData, - status: request.status, - statusText: request.statusText, - headers: responseHeaders, - config, - request - }; - - settle(function _resolve(value) { - resolve(value); - done(); - }, function _reject(err) { - reject(err); - done(); - }, response); - - // Clean up request - request = null; - } - - if ('onloadend' in request) { - // Use onloadend if available - request.onloadend = onloadend; - } else { - // Listen for ready state to emulate onloadend - request.onreadystatechange = function handleLoad() { - if (!request || request.readyState !== 4) { - return; - } - - // The request errored out and we didn't get a response, this will be - // handled by onerror instead - // With one exception: request that using file: protocol, most browsers - // will return status as 0 even though it's a successful request - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { - return; - } - // readystate handler is calling before onerror or ontimeout handlers, - // so we should call onloadend on the next 'tick' - setTimeout(onloadend); - }; - } - - // Handle browser request cancellation (as opposed to a manual cancellation) - request.onabort = function handleAbort() { - if (!request) { - return; - } - - reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request)); - - // Clean up request - request = null; - }; - - // Handle low level network errors - request.onerror = function handleError() { - // Real errors are hidden from us by the browser - // onerror should only fire if it's a network error - reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request)); - - // Clean up request - request = null; - }; - - // Handle timeout - request.ontimeout = function handleTimeout() { - let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; - const transitional = config.transitional || transitionalDefaults; - if (config.timeoutErrorMessage) { - timeoutErrorMessage = config.timeoutErrorMessage; - } - reject(new AxiosError( - timeoutErrorMessage, - transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, - config, - request)); - - // Clean up request - request = null; - }; - - // Add xsrf header - // This is only done if running in a standard browser environment. - // Specifically not if we're in a web worker, or react-native. - if(platform.hasStandardBrowserEnv) { - withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(config)); - - if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(fullPath))) { - // Add xsrf header - const xsrfValue = config.xsrfHeaderName && config.xsrfCookieName && cookies.read(config.xsrfCookieName); - - if (xsrfValue) { - requestHeaders.set(config.xsrfHeaderName, xsrfValue); - } - } - } - - // Remove Content-Type if data is undefined - requestData === undefined && requestHeaders.setContentType(null); - - // Add headers to the request - if ('setRequestHeader' in request) { - utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { - request.setRequestHeader(key, val); - }); - } - - // Add withCredentials to request if needed - if (!utils$1.isUndefined(config.withCredentials)) { - request.withCredentials = !!config.withCredentials; - } - - // Add responseType to request if needed - if (responseType && responseType !== 'json') { - request.responseType = config.responseType; - } - - // Handle progress if needed - if (typeof config.onDownloadProgress === 'function') { - request.addEventListener('progress', progressEventReducer(config.onDownloadProgress, true)); - } - - // Not all browsers support upload events - if (typeof config.onUploadProgress === 'function' && request.upload) { - request.upload.addEventListener('progress', progressEventReducer(config.onUploadProgress)); - } - - if (config.cancelToken || config.signal) { - // Handle cancellation - // eslint-disable-next-line func-names - onCanceled = cancel => { - if (!request) { - return; - } - reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel); - request.abort(); - request = null; - }; - - config.cancelToken && config.cancelToken.subscribe(onCanceled); - if (config.signal) { - config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); - } - } - - const protocol = parseProtocol(fullPath); - - if (protocol && platform.protocols.indexOf(protocol) === -1) { - reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); - return; - } - +function progressEventReducer(listener, isDownloadStream) { + let bytesNotified = 0; + const _speedometer = speedometer(50, 250); + + return e => { + const loaded = e.loaded; + const total = e.lengthComputable ? e.total : undefined; + const progressBytes = loaded - bytesNotified; + const rate = _speedometer(progressBytes); + const inRange = loaded <= total; + + bytesNotified = loaded; + + const data = { + loaded, + total, + progress: total ? (loaded / total) : undefined, + bytes: progressBytes, + rate: rate ? rate : undefined, + estimated: rate && total && inRange ? (total - loaded) / rate : undefined, + event: e + }; + + data[isDownloadStream ? 'download' : 'upload'] = true; + + listener(data); + }; +} - // Send the request - request.send(requestData || null); - }); +const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; + +var xhrAdapter = isXHRAdapterSupported && function (config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + let requestData = config.data; + const requestHeaders = AxiosHeaders$1.from(config.headers).normalize(); + let {responseType, withXSRFToken} = config; + let onCanceled; + function done() { + if (config.cancelToken) { + config.cancelToken.unsubscribe(onCanceled); + } + + if (config.signal) { + config.signal.removeEventListener('abort', onCanceled); + } + } + + let contentType; + + if (utils$1.isFormData(requestData)) { + if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) { + requestHeaders.setContentType(false); // Let the browser set it + } else if ((contentType = requestHeaders.getContentType()) !== false) { + // fix semicolon duplication issue for ReactNative FormData implementation + const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : []; + requestHeaders.setContentType([type || 'multipart/form-data', ...tokens].join('; ')); + } + } + + let request = new XMLHttpRequest(); + + // HTTP basic authentication + if (config.auth) { + const username = config.auth.username || ''; + const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; + requestHeaders.set('Authorization', 'Basic ' + btoa(username + ':' + password)); + } + + const fullPath = buildFullPath(config.baseURL, config.url); + + request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); + + // Set the request timeout in MS + request.timeout = config.timeout; + + function onloadend() { + if (!request) { + return; + } + // Prepare the response + const responseHeaders = AxiosHeaders$1.from( + 'getAllResponseHeaders' in request && request.getAllResponseHeaders() + ); + const responseData = !responseType || responseType === 'text' || responseType === 'json' ? + request.responseText : request.response; + const response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config, + request + }; + + settle(function _resolve(value) { + resolve(value); + done(); + }, function _reject(err) { + reject(err); + done(); + }, response); + + // Clean up request + request = null; + } + + if ('onloadend' in request) { + // Use onloadend if available + request.onloadend = onloadend; + } else { + // Listen for ready state to emulate onloadend + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + + // The request errored out and we didn't get a response, this will be + // handled by onerror instead + // With one exception: request that using file: protocol, most browsers + // will return status as 0 even though it's a successful request + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { + return; + } + // readystate handler is calling before onerror or ontimeout handlers, + // so we should call onloadend on the next 'tick' + setTimeout(onloadend); + }; + } + + // Handle browser request cancellation (as opposed to a manual cancellation) + request.onabort = function handleAbort() { + if (!request) { + return; + } + + reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request)); + + // Clean up request + request = null; + }; + + // Handle low level network errors + request.onerror = function handleError() { + // Real errors are hidden from us by the browser + // onerror should only fire if it's a network error + reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request)); + + // Clean up request + request = null; + }; + + // Handle timeout + request.ontimeout = function handleTimeout() { + let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; + const transitional = config.transitional || transitionalDefaults; + if (config.timeoutErrorMessage) { + timeoutErrorMessage = config.timeoutErrorMessage; + } + reject(new AxiosError( + timeoutErrorMessage, + transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, + config, + request)); + + // Clean up request + request = null; + }; + + // Add xsrf header + // This is only done if running in a standard browser environment. + // Specifically not if we're in a web worker, or react-native. + if(platform.hasStandardBrowserEnv) { + withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(config)); + + if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(fullPath))) { + // Add xsrf header + const xsrfValue = config.xsrfHeaderName && config.xsrfCookieName && cookies.read(config.xsrfCookieName); + + if (xsrfValue) { + requestHeaders.set(config.xsrfHeaderName, xsrfValue); + } + } + } + + // Remove Content-Type if data is undefined + requestData === undefined && requestHeaders.setContentType(null); + + // Add headers to the request + if ('setRequestHeader' in request) { + utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { + request.setRequestHeader(key, val); + }); + } + + // Add withCredentials to request if needed + if (!utils$1.isUndefined(config.withCredentials)) { + request.withCredentials = !!config.withCredentials; + } + + // Add responseType to request if needed + if (responseType && responseType !== 'json') { + request.responseType = config.responseType; + } + + // Handle progress if needed + if (typeof config.onDownloadProgress === 'function') { + request.addEventListener('progress', progressEventReducer(config.onDownloadProgress, true)); + } + + // Not all browsers support upload events + if (typeof config.onUploadProgress === 'function' && request.upload) { + request.upload.addEventListener('progress', progressEventReducer(config.onUploadProgress)); + } + + if (config.cancelToken || config.signal) { + // Handle cancellation + // eslint-disable-next-line func-names + onCanceled = cancel => { + if (!request) { + return; + } + reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel); + request.abort(); + request = null; + }; + + config.cancelToken && config.cancelToken.subscribe(onCanceled); + if (config.signal) { + config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); + } + } + + const protocol = parseProtocol(fullPath); + + if (protocol && platform.protocols.indexOf(protocol) === -1) { + reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); + return; + } + + + // Send the request + request.send(requestData || null); + }); }; const knownAdapters = { - http: httpAdapter$1, - xhr: xhrAdapter + http: httpAdapter$1, + xhr: xhrAdapter }; utils$1.forEach(knownAdapters, (fn, value) => { - if (fn) { - try { - Object.defineProperty(fn, 'name', {value}); - } catch (e) { - // eslint-disable-next-line no-empty - } - Object.defineProperty(fn, 'adapterName', {value}); - } + if (fn) { + try { + Object.defineProperty(fn, 'name', {value}); + } catch (e) { + // eslint-disable-next-line no-empty + } + Object.defineProperty(fn, 'adapterName', {value}); + } }); const renderReason = (reason) => `- ${reason}`; @@ -4014,56 +4014,56 @@ const renderReason = (reason) => `- ${reason}`; const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false; var adapters = { - getAdapter: (adapters) => { - adapters = utils$1.isArray(adapters) ? adapters : [adapters]; + getAdapter: (adapters) => { + adapters = utils$1.isArray(adapters) ? adapters : [adapters]; - const {length} = adapters; - let nameOrAdapter; - let adapter; + const {length} = adapters; + let nameOrAdapter; + let adapter; - const rejectedReasons = {}; + const rejectedReasons = {}; - for (let i = 0; i < length; i++) { - nameOrAdapter = adapters[i]; - let id; + for (let i = 0; i < length; i++) { + nameOrAdapter = adapters[i]; + let id; - adapter = nameOrAdapter; + adapter = nameOrAdapter; - if (!isResolvedHandle(nameOrAdapter)) { - adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; + if (!isResolvedHandle(nameOrAdapter)) { + adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; - if (adapter === undefined) { - throw new AxiosError(`Unknown adapter '${id}'`); - } - } + if (adapter === undefined) { + throw new AxiosError(`Unknown adapter '${id}'`); + } + } - if (adapter) { - break; - } + if (adapter) { + break; + } - rejectedReasons[id || '#' + i] = adapter; - } + rejectedReasons[id || '#' + i] = adapter; + } - if (!adapter) { + if (!adapter) { - const reasons = Object.entries(rejectedReasons) - .map(([id, state]) => `adapter ${id} ` + + const reasons = Object.entries(rejectedReasons) + .map(([id, state]) => `adapter ${id} ` + (state === false ? 'is not supported by the environment' : 'is not available in the build') - ); + ); - let s = length ? - (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) : - 'as no adapter specified'; + let s = length ? + (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) : + 'as no adapter specified'; - throw new AxiosError( - 'There is no suitable adapter to dispatch the request ' + s, - 'ERR_NOT_SUPPORT' - ); - } + throw new AxiosError( + `There is no suitable adapter to dispatch the request ` + s, + 'ERR_NOT_SUPPORT' + ); + } - return adapter; - }, - adapters: knownAdapters + return adapter; + }, + adapters: knownAdapters }; /** @@ -4074,13 +4074,13 @@ var adapters = { * @returns {void} */ function throwIfCancellationRequested(config) { - if (config.cancelToken) { - config.cancelToken.throwIfRequested(); - } + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } - if (config.signal && config.signal.aborted) { - throw new CanceledError(null, config); - } + if (config.signal && config.signal.aborted) { + throw new CanceledError(null, config); + } } /** @@ -4091,52 +4091,52 @@ function throwIfCancellationRequested(config) { * @returns {Promise} The Promise to be fulfilled */ function dispatchRequest(config) { - throwIfCancellationRequested(config); - - config.headers = AxiosHeaders$1.from(config.headers); - - // Transform request data - config.data = transformData.call( - config, - config.transformRequest - ); - - if (['post', 'put', 'patch'].indexOf(config.method) !== -1) { - config.headers.setContentType('application/x-www-form-urlencoded', false); - } - - const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter); - - return adapter(config).then(function onAdapterResolution(response) { - throwIfCancellationRequested(config); - - // Transform response data - response.data = transformData.call( - config, - config.transformResponse, - response - ); - - response.headers = AxiosHeaders$1.from(response.headers); - - return response; - }, function onAdapterRejection(reason) { - if (!isCancel(reason)) { - throwIfCancellationRequested(config); - - // Transform response data - if (reason && reason.response) { - reason.response.data = transformData.call( - config, - config.transformResponse, - reason.response - ); - reason.response.headers = AxiosHeaders$1.from(reason.response.headers); - } - } - - return Promise.reject(reason); - }); + throwIfCancellationRequested(config); + + config.headers = AxiosHeaders$1.from(config.headers); + + // Transform request data + config.data = transformData.call( + config, + config.transformRequest + ); + + if (['post', 'put', 'patch'].indexOf(config.method) !== -1) { + config.headers.setContentType('application/x-www-form-urlencoded', false); + } + + const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter); + + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); + + // Transform response data + response.data = transformData.call( + config, + config.transformResponse, + response + ); + + response.headers = AxiosHeaders$1.from(response.headers); + + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); + + // Transform response data + if (reason && reason.response) { + reason.response.data = transformData.call( + config, + config.transformResponse, + reason.response + ); + reason.response.headers = AxiosHeaders$1.from(reason.response.headers); + } + } + + return Promise.reject(reason); + }); } const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? thing.toJSON() : thing; @@ -4151,105 +4151,105 @@ const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? thing.toJSO * @returns {Object} New object resulting from merging config2 to config1 */ function mergeConfig(config1, config2) { - // eslint-disable-next-line no-param-reassign - config2 = config2 || {}; - const config = {}; - - function getMergedValue(target, source, caseless) { - if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) { - return utils$1.merge.call({caseless}, target, source); - } else if (utils$1.isPlainObject(source)) { - return utils$1.merge({}, source); - } else if (utils$1.isArray(source)) { - return source.slice(); - } - return source; - } - - // eslint-disable-next-line consistent-return - function mergeDeepProperties(a, b, caseless) { - if (!utils$1.isUndefined(b)) { - return getMergedValue(a, b, caseless); - } else if (!utils$1.isUndefined(a)) { - return getMergedValue(undefined, a, caseless); - } - } - - // eslint-disable-next-line consistent-return - function valueFromConfig2(a, b) { - if (!utils$1.isUndefined(b)) { - return getMergedValue(undefined, b); - } - } - - // eslint-disable-next-line consistent-return - function defaultToConfig2(a, b) { - if (!utils$1.isUndefined(b)) { - return getMergedValue(undefined, b); - } else if (!utils$1.isUndefined(a)) { - return getMergedValue(undefined, a); - } - } - - // eslint-disable-next-line consistent-return - function mergeDirectKeys(a, b, prop) { - if (prop in config2) { - return getMergedValue(a, b); - } else if (prop in config1) { - return getMergedValue(undefined, a); - } - } - - const mergeMap = { - url: valueFromConfig2, - method: valueFromConfig2, - data: valueFromConfig2, - baseURL: defaultToConfig2, - transformRequest: defaultToConfig2, - transformResponse: defaultToConfig2, - paramsSerializer: defaultToConfig2, - timeout: defaultToConfig2, - timeoutMessage: defaultToConfig2, - withCredentials: defaultToConfig2, - withXSRFToken: defaultToConfig2, - adapter: defaultToConfig2, - responseType: defaultToConfig2, - xsrfCookieName: defaultToConfig2, - xsrfHeaderName: defaultToConfig2, - onUploadProgress: defaultToConfig2, - onDownloadProgress: defaultToConfig2, - decompress: defaultToConfig2, - maxContentLength: defaultToConfig2, - maxBodyLength: defaultToConfig2, - beforeRedirect: defaultToConfig2, - transport: defaultToConfig2, - httpAgent: defaultToConfig2, - httpsAgent: defaultToConfig2, - cancelToken: defaultToConfig2, - socketPath: defaultToConfig2, - responseEncoding: defaultToConfig2, - validateStatus: mergeDirectKeys, - headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true) - }; - - utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) { - const merge = mergeMap[prop] || mergeDeepProperties; - const configValue = merge(config1[prop], config2[prop], prop); - (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); - }); - - return config; + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + const config = {}; + + function getMergedValue(target, source, caseless) { + if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) { + return utils$1.merge.call({caseless}, target, source); + } else if (utils$1.isPlainObject(source)) { + return utils$1.merge({}, source); + } else if (utils$1.isArray(source)) { + return source.slice(); + } + return source; + } + + // eslint-disable-next-line consistent-return + function mergeDeepProperties(a, b, caseless) { + if (!utils$1.isUndefined(b)) { + return getMergedValue(a, b, caseless); + } else if (!utils$1.isUndefined(a)) { + return getMergedValue(undefined, a, caseless); + } + } + + // eslint-disable-next-line consistent-return + function valueFromConfig2(a, b) { + if (!utils$1.isUndefined(b)) { + return getMergedValue(undefined, b); + } + } + + // eslint-disable-next-line consistent-return + function defaultToConfig2(a, b) { + if (!utils$1.isUndefined(b)) { + return getMergedValue(undefined, b); + } else if (!utils$1.isUndefined(a)) { + return getMergedValue(undefined, a); + } + } + + // eslint-disable-next-line consistent-return + function mergeDirectKeys(a, b, prop) { + if (prop in config2) { + return getMergedValue(a, b); + } else if (prop in config1) { + return getMergedValue(undefined, a); + } + } + + const mergeMap = { + url: valueFromConfig2, + method: valueFromConfig2, + data: valueFromConfig2, + baseURL: defaultToConfig2, + transformRequest: defaultToConfig2, + transformResponse: defaultToConfig2, + paramsSerializer: defaultToConfig2, + timeout: defaultToConfig2, + timeoutMessage: defaultToConfig2, + withCredentials: defaultToConfig2, + withXSRFToken: defaultToConfig2, + adapter: defaultToConfig2, + responseType: defaultToConfig2, + xsrfCookieName: defaultToConfig2, + xsrfHeaderName: defaultToConfig2, + onUploadProgress: defaultToConfig2, + onDownloadProgress: defaultToConfig2, + decompress: defaultToConfig2, + maxContentLength: defaultToConfig2, + maxBodyLength: defaultToConfig2, + beforeRedirect: defaultToConfig2, + transport: defaultToConfig2, + httpAgent: defaultToConfig2, + httpsAgent: defaultToConfig2, + cancelToken: defaultToConfig2, + socketPath: defaultToConfig2, + responseEncoding: defaultToConfig2, + validateStatus: mergeDirectKeys, + headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true) + }; + + utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) { + const merge = mergeMap[prop] || mergeDeepProperties; + const configValue = merge(config1[prop], config2[prop], prop); + (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); + }); + + return config; } -const VERSION = '1.6.2'; +const VERSION = "1.6.2"; const validators$1 = {}; // eslint-disable-next-line func-names ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => { - validators$1[type] = function validator(thing) { - return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; - }; + validators$1[type] = function validator(thing) { + return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; + }; }); const deprecatedWarnings = {}; @@ -4264,32 +4264,32 @@ const deprecatedWarnings = {}; * @returns {function} */ validators$1.transitional = function transitional(validator, version, message) { - function formatMessage(opt, desc) { - return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); - } - - // eslint-disable-next-line func-names - return (value, opt, opts) => { - if (validator === false) { - throw new AxiosError( - formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), - AxiosError.ERR_DEPRECATED - ); - } - - if (version && !deprecatedWarnings[opt]) { - deprecatedWarnings[opt] = true; - // eslint-disable-next-line no-console - console.warn( - formatMessage( - opt, - ' has been deprecated since v' + version + ' and will be removed in the near future' - ) - ); - } - - return validator ? validator(value, opt, opts) : true; - }; + function formatMessage(opt, desc) { + return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); + } + + // eslint-disable-next-line func-names + return (value, opt, opts) => { + if (validator === false) { + throw new AxiosError( + formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), + AxiosError.ERR_DEPRECATED + ); + } + + if (version && !deprecatedWarnings[opt]) { + deprecatedWarnings[opt] = true; + // eslint-disable-next-line no-console + console.warn( + formatMessage( + opt, + ' has been deprecated since v' + version + ' and will be removed in the near future' + ) + ); + } + + return validator ? validator(value, opt, opts) : true; + }; }; /** @@ -4303,31 +4303,31 @@ validators$1.transitional = function transitional(validator, version, message) { */ function assertOptions(options, schema, allowUnknown) { - if (typeof options !== 'object') { - throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE); - } - const keys = Object.keys(options); - let i = keys.length; - while (i-- > 0) { - const opt = keys[i]; - const validator = schema[opt]; - if (validator) { - const value = options[opt]; - const result = value === undefined || validator(value, opt, options); - if (result !== true) { - throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE); - } - continue; - } - if (allowUnknown !== true) { - throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION); - } - } + if (typeof options !== 'object') { + throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE); + } + const keys = Object.keys(options); + let i = keys.length; + while (i-- > 0) { + const opt = keys[i]; + const validator = schema[opt]; + if (validator) { + const value = options[opt]; + const result = value === undefined || validator(value, opt, options); + if (result !== true) { + throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE); + } + continue; + } + if (allowUnknown !== true) { + throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION); + } + } } var validator = { - assertOptions, - validators: validators$1 + assertOptions, + validators: validators$1 }; const validators = validator.validators; @@ -4340,15 +4340,15 @@ const validators = validator.validators; * @return {Axios} A new instance of Axios */ class Axios { - constructor(instanceConfig) { - this.defaults = instanceConfig; - this.interceptors = { - request: new InterceptorManager$1(), - response: new InterceptorManager$1() - }; - } - - /** + constructor(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new InterceptorManager$1(), + response: new InterceptorManager$1() + }; + } + + /** * Dispatch a request * * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) @@ -4356,167 +4356,167 @@ class Axios { * * @returns {Promise} The Promise to be fulfilled */ - request(configOrUrl, config) { - /*eslint no-param-reassign:0*/ - // Allow for axios('example/url'[, config]) a la fetch API - if (typeof configOrUrl === 'string') { - config = config || {}; - config.url = configOrUrl; - } else { - config = configOrUrl || {}; - } - - config = mergeConfig(this.defaults, config); - - const {transitional, paramsSerializer, headers} = config; - - if (transitional !== undefined) { - validator.assertOptions(transitional, { - silentJSONParsing: validators.transitional(validators.boolean), - forcedJSONParsing: validators.transitional(validators.boolean), - clarifyTimeoutError: validators.transitional(validators.boolean) - }, false); - } - - if (paramsSerializer != null) { - if (utils$1.isFunction(paramsSerializer)) { - config.paramsSerializer = { - serialize: paramsSerializer - }; - } else { - validator.assertOptions(paramsSerializer, { - encode: validators.function, - serialize: validators.function - }, true); - } - } - - // Set config.method - config.method = (config.method || this.defaults.method || 'get').toLowerCase(); - - // Flatten headers - let contextHeaders = headers && utils$1.merge( - headers.common, - headers[config.method] - ); - - headers && utils$1.forEach( - ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], - (method) => { - delete headers[method]; - } - ); - - config.headers = AxiosHeaders$1.concat(contextHeaders, headers); - - // filter out skipped interceptors - const requestInterceptorChain = []; - let synchronousRequestInterceptors = true; - this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { - if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { - return; - } - - synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; - - requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); - }); - - const responseInterceptorChain = []; - this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { - responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); - }); - - let promise; - let i = 0; - let len; - - if (!synchronousRequestInterceptors) { - const chain = [dispatchRequest.bind(this), undefined]; - chain.unshift.apply(chain, requestInterceptorChain); - chain.push.apply(chain, responseInterceptorChain); - len = chain.length; - - promise = Promise.resolve(config); - - while (i < len) { - promise = promise.then(chain[i++], chain[i++]); - } - - return promise; - } - - len = requestInterceptorChain.length; - - let newConfig = config; - - i = 0; - - while (i < len) { - const onFulfilled = requestInterceptorChain[i++]; - const onRejected = requestInterceptorChain[i++]; - try { - newConfig = onFulfilled(newConfig); - } catch (error) { - onRejected.call(this, error); - break; - } - } - - try { - promise = dispatchRequest.call(this, newConfig); - } catch (error) { - return Promise.reject(error); - } - - i = 0; - len = responseInterceptorChain.length; - - while (i < len) { - promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); - } - - return promise; - } - - getUri(config) { - config = mergeConfig(this.defaults, config); - const fullPath = buildFullPath(config.baseURL, config.url); - return buildURL(fullPath, config.params, config.paramsSerializer); - } + request(configOrUrl, config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof configOrUrl === 'string') { + config = config || {}; + config.url = configOrUrl; + } else { + config = configOrUrl || {}; + } + + config = mergeConfig(this.defaults, config); + + const {transitional, paramsSerializer, headers} = config; + + if (transitional !== undefined) { + validator.assertOptions(transitional, { + silentJSONParsing: validators.transitional(validators.boolean), + forcedJSONParsing: validators.transitional(validators.boolean), + clarifyTimeoutError: validators.transitional(validators.boolean) + }, false); + } + + if (paramsSerializer != null) { + if (utils$1.isFunction(paramsSerializer)) { + config.paramsSerializer = { + serialize: paramsSerializer + }; + } else { + validator.assertOptions(paramsSerializer, { + encode: validators.function, + serialize: validators.function + }, true); + } + } + + // Set config.method + config.method = (config.method || this.defaults.method || 'get').toLowerCase(); + + // Flatten headers + let contextHeaders = headers && utils$1.merge( + headers.common, + headers[config.method] + ); + + headers && utils$1.forEach( + ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], + (method) => { + delete headers[method]; + } + ); + + config.headers = AxiosHeaders$1.concat(contextHeaders, headers); + + // filter out skipped interceptors + const requestInterceptorChain = []; + let synchronousRequestInterceptors = true; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { + return; + } + + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; + + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + + const responseInterceptorChain = []; + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + }); + + let promise; + let i = 0; + let len; + + if (!synchronousRequestInterceptors) { + const chain = [dispatchRequest.bind(this), undefined]; + chain.unshift.apply(chain, requestInterceptorChain); + chain.push.apply(chain, responseInterceptorChain); + len = chain.length; + + promise = Promise.resolve(config); + + while (i < len) { + promise = promise.then(chain[i++], chain[i++]); + } + + return promise; + } + + len = requestInterceptorChain.length; + + let newConfig = config; + + i = 0; + + while (i < len) { + const onFulfilled = requestInterceptorChain[i++]; + const onRejected = requestInterceptorChain[i++]; + try { + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected.call(this, error); + break; + } + } + + try { + promise = dispatchRequest.call(this, newConfig); + } catch (error) { + return Promise.reject(error); + } + + i = 0; + len = responseInterceptorChain.length; + + while (i < len) { + promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); + } + + return promise; + } + + getUri(config) { + config = mergeConfig(this.defaults, config); + const fullPath = buildFullPath(config.baseURL, config.url); + return buildURL(fullPath, config.params, config.paramsSerializer); + } } // Provide aliases for supported request methods utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { - /*eslint func-names:0*/ - Axios.prototype[method] = function(url, config) { - return this.request(mergeConfig(config || {}, { - method, - url, - data: (config || {}).data - })); - }; + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, config) { + return this.request(mergeConfig(config || {}, { + method, + url, + data: (config || {}).data + })); + }; }); utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - /*eslint func-names:0*/ - - function generateHTTPMethod(isForm) { - return function httpMethod(url, data, config) { - return this.request(mergeConfig(config || {}, { - method, - headers: isForm ? { - 'Content-Type': 'multipart/form-data' - } : {}, - url, - data - })); - }; - } - - Axios.prototype[method] = generateHTTPMethod(); - - Axios.prototype[method + 'Form'] = generateHTTPMethod(true); + /*eslint func-names:0*/ + + function generateHTTPMethod(isForm) { + return function httpMethod(url, data, config) { + return this.request(mergeConfig(config || {}, { + method, + headers: isForm ? { + 'Content-Type': 'multipart/form-data' + } : {}, + url, + data + })); + }; + } + + Axios.prototype[method] = generateHTTPMethod(); + + Axios.prototype[method + 'Form'] = generateHTTPMethod(true); }); var Axios$1 = Axios; @@ -4529,112 +4529,112 @@ var Axios$1 = Axios; * @returns {CancelToken} */ class CancelToken { - constructor(executor) { - if (typeof executor !== 'function') { - throw new TypeError('executor must be a function.'); - } - - let resolvePromise; - - this.promise = new Promise(function promiseExecutor(resolve) { - resolvePromise = resolve; - }); - - const token = this; - - // eslint-disable-next-line func-names - this.promise.then(cancel => { - if (!token._listeners) return; - - let i = token._listeners.length; - - while (i-- > 0) { - token._listeners[i](cancel); - } - token._listeners = null; - }); - - // eslint-disable-next-line func-names - this.promise.then = onfulfilled => { - let _resolve; - // eslint-disable-next-line func-names - const promise = new Promise(resolve => { - token.subscribe(resolve); - _resolve = resolve; - }).then(onfulfilled); - - promise.cancel = function reject() { - token.unsubscribe(_resolve); - }; - - return promise; - }; - - executor(function cancel(message, config, request) { - if (token.reason) { - // Cancellation has already been requested - return; - } - - token.reason = new CanceledError(message, config, request); - resolvePromise(token.reason); - }); - } - - /** + constructor(executor) { + if (typeof executor !== 'function') { + throw new TypeError('executor must be a function.'); + } + + let resolvePromise; + + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + + const token = this; + + // eslint-disable-next-line func-names + this.promise.then(cancel => { + if (!token._listeners) return; + + let i = token._listeners.length; + + while (i-- > 0) { + token._listeners[i](cancel); + } + token._listeners = null; + }); + + // eslint-disable-next-line func-names + this.promise.then = onfulfilled => { + let _resolve; + // eslint-disable-next-line func-names + const promise = new Promise(resolve => { + token.subscribe(resolve); + _resolve = resolve; + }).then(onfulfilled); + + promise.cancel = function reject() { + token.unsubscribe(_resolve); + }; + + return promise; + }; + + executor(function cancel(message, config, request) { + if (token.reason) { + // Cancellation has already been requested + return; + } + + token.reason = new CanceledError(message, config, request); + resolvePromise(token.reason); + }); + } + + /** * Throws a `CanceledError` if cancellation has been requested. */ - throwIfRequested() { - if (this.reason) { - throw this.reason; - } - } + throwIfRequested() { + if (this.reason) { + throw this.reason; + } + } - /** + /** * Subscribe to the cancel signal */ - subscribe(listener) { - if (this.reason) { - listener(this.reason); - return; - } + subscribe(listener) { + if (this.reason) { + listener(this.reason); + return; + } - if (this._listeners) { - this._listeners.push(listener); - } else { - this._listeners = [listener]; - } - } + if (this._listeners) { + this._listeners.push(listener); + } else { + this._listeners = [listener]; + } + } - /** + /** * Unsubscribe from the cancel signal */ - unsubscribe(listener) { - if (!this._listeners) { - return; - } - const index = this._listeners.indexOf(listener); - if (index !== -1) { - this._listeners.splice(index, 1); - } - } - - /** + unsubscribe(listener) { + if (!this._listeners) { + return; + } + const index = this._listeners.indexOf(listener); + if (index !== -1) { + this._listeners.splice(index, 1); + } + } + + /** * Returns an object that contains a new `CancelToken` and a function that, when called, * cancels the `CancelToken`. */ - static source() { - let cancel; - const token = new CancelToken(function executor(c) { - cancel = c; - }); - return { - token, - cancel - }; - } + static source() { + let cancel; + const token = new CancelToken(function executor(c) { + cancel = c; + }); + return { + token, + cancel + }; + } } var CancelToken$1 = CancelToken; @@ -4661,9 +4661,9 @@ var CancelToken$1 = CancelToken; * @returns {Function} */ function spread(callback) { - return function wrap(arr) { - return callback.apply(null, arr); - }; + return function wrap(arr) { + return callback.apply(null, arr); + }; } /** @@ -4674,77 +4674,77 @@ function spread(callback) { * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false */ function isAxiosError(payload) { - return utils$1.isObject(payload) && (payload.isAxiosError === true); + return utils$1.isObject(payload) && (payload.isAxiosError === true); } const HttpStatusCode = { - Continue: 100, - SwitchingProtocols: 101, - Processing: 102, - EarlyHints: 103, - Ok: 200, - Created: 201, - Accepted: 202, - NonAuthoritativeInformation: 203, - NoContent: 204, - ResetContent: 205, - PartialContent: 206, - MultiStatus: 207, - AlreadyReported: 208, - ImUsed: 226, - MultipleChoices: 300, - MovedPermanently: 301, - Found: 302, - SeeOther: 303, - NotModified: 304, - UseProxy: 305, - Unused: 306, - TemporaryRedirect: 307, - PermanentRedirect: 308, - BadRequest: 400, - Unauthorized: 401, - PaymentRequired: 402, - Forbidden: 403, - NotFound: 404, - MethodNotAllowed: 405, - NotAcceptable: 406, - ProxyAuthenticationRequired: 407, - RequestTimeout: 408, - Conflict: 409, - Gone: 410, - LengthRequired: 411, - PreconditionFailed: 412, - PayloadTooLarge: 413, - UriTooLong: 414, - UnsupportedMediaType: 415, - RangeNotSatisfiable: 416, - ExpectationFailed: 417, - ImATeapot: 418, - MisdirectedRequest: 421, - UnprocessableEntity: 422, - Locked: 423, - FailedDependency: 424, - TooEarly: 425, - UpgradeRequired: 426, - PreconditionRequired: 428, - TooManyRequests: 429, - RequestHeaderFieldsTooLarge: 431, - UnavailableForLegalReasons: 451, - InternalServerError: 500, - NotImplemented: 501, - BadGateway: 502, - ServiceUnavailable: 503, - GatewayTimeout: 504, - HttpVersionNotSupported: 505, - VariantAlsoNegotiates: 506, - InsufficientStorage: 507, - LoopDetected: 508, - NotExtended: 510, - NetworkAuthenticationRequired: 511, + Continue: 100, + SwitchingProtocols: 101, + Processing: 102, + EarlyHints: 103, + Ok: 200, + Created: 201, + Accepted: 202, + NonAuthoritativeInformation: 203, + NoContent: 204, + ResetContent: 205, + PartialContent: 206, + MultiStatus: 207, + AlreadyReported: 208, + ImUsed: 226, + MultipleChoices: 300, + MovedPermanently: 301, + Found: 302, + SeeOther: 303, + NotModified: 304, + UseProxy: 305, + Unused: 306, + TemporaryRedirect: 307, + PermanentRedirect: 308, + BadRequest: 400, + Unauthorized: 401, + PaymentRequired: 402, + Forbidden: 403, + NotFound: 404, + MethodNotAllowed: 405, + NotAcceptable: 406, + ProxyAuthenticationRequired: 407, + RequestTimeout: 408, + Conflict: 409, + Gone: 410, + LengthRequired: 411, + PreconditionFailed: 412, + PayloadTooLarge: 413, + UriTooLong: 414, + UnsupportedMediaType: 415, + RangeNotSatisfiable: 416, + ExpectationFailed: 417, + ImATeapot: 418, + MisdirectedRequest: 421, + UnprocessableEntity: 422, + Locked: 423, + FailedDependency: 424, + TooEarly: 425, + UpgradeRequired: 426, + PreconditionRequired: 428, + TooManyRequests: 429, + RequestHeaderFieldsTooLarge: 431, + UnavailableForLegalReasons: 451, + InternalServerError: 500, + NotImplemented: 501, + BadGateway: 502, + ServiceUnavailable: 503, + GatewayTimeout: 504, + HttpVersionNotSupported: 505, + VariantAlsoNegotiates: 506, + InsufficientStorage: 507, + LoopDetected: 508, + NotExtended: 510, + NetworkAuthenticationRequired: 511, }; Object.entries(HttpStatusCode).forEach(([key, value]) => { - HttpStatusCode[value] = key; + HttpStatusCode[value] = key; }); var HttpStatusCode$1 = HttpStatusCode; @@ -4757,21 +4757,21 @@ var HttpStatusCode$1 = HttpStatusCode; * @returns {Axios} A new instance of Axios */ function createInstance(defaultConfig) { - const context = new Axios$1(defaultConfig); - const instance = bind(Axios$1.prototype.request, context); + const context = new Axios$1(defaultConfig); + const instance = bind(Axios$1.prototype.request, context); - // Copy axios.prototype to instance - utils$1.extend(instance, Axios$1.prototype, context, {allOwnKeys: true}); + // Copy axios.prototype to instance + utils$1.extend(instance, Axios$1.prototype, context, {allOwnKeys: true}); - // Copy context to instance - utils$1.extend(instance, context, null, {allOwnKeys: true}); + // Copy context to instance + utils$1.extend(instance, context, null, {allOwnKeys: true}); - // Factory for creating new instances - instance.create = function create(instanceConfig) { - return createInstance(mergeConfig(defaultConfig, instanceConfig)); - }; + // Factory for creating new instances + instance.create = function create(instanceConfig) { + return createInstance(mergeConfig(defaultConfig, instanceConfig)); + }; - return instance; + return instance; } // Create the default instance to be exported @@ -4795,7 +4795,7 @@ axios.Cancel = axios.CanceledError; // Expose all/spread axios.all = function all(promises) { - return Promise.all(promises); + return Promise.all(promises); }; axios.spread = spread; @@ -5058,193 +5058,193 @@ var clientMap = map$1; var rfdc_1 = rfdc; -function copyBuffer(cur) { - if (cur instanceof Buffer) { - return Buffer.from(cur); - } +function copyBuffer (cur) { + if (cur instanceof Buffer) { + return Buffer.from(cur) + } - return new cur.constructor(cur.buffer.slice(), cur.byteOffset, cur.length); + return new cur.constructor(cur.buffer.slice(), cur.byteOffset, cur.length) } -function rfdc(opts) { - opts = opts || {}; - - if (opts.circles) return rfdcCircles(opts); - return opts.proto ? cloneProto : clone; - - function cloneArray(a, fn) { - var keys = Object.keys(a); - var a2 = new Array(keys.length); - for (var i = 0; i < keys.length; i++) { - var k = keys[i]; - var cur = a[k]; - if (typeof cur !== 'object' || cur === null) { - a2[k] = cur; - } else if (cur instanceof Date) { - a2[k] = new Date(cur); - } else if (ArrayBuffer.isView(cur)) { - a2[k] = copyBuffer(cur); - } else { - a2[k] = fn(cur); - } - } - return a2; - } - - function clone(o) { - if (typeof o !== 'object' || o === null) return o; - if (o instanceof Date) return new Date(o); - if (Array.isArray(o)) return cloneArray(o, clone); - if (o instanceof Map) return new Map(cloneArray(Array.from(o), clone)); - if (o instanceof Set) return new Set(cloneArray(Array.from(o), clone)); - var o2 = {}; - for (var k in o) { - if (Object.hasOwnProperty.call(o, k) === false) continue; - var cur = o[k]; - if (typeof cur !== 'object' || cur === null) { - o2[k] = cur; - } else if (cur instanceof Date) { - o2[k] = new Date(cur); - } else if (cur instanceof Map) { - o2[k] = new Map(cloneArray(Array.from(cur), clone)); - } else if (cur instanceof Set) { - o2[k] = new Set(cloneArray(Array.from(cur), clone)); - } else if (ArrayBuffer.isView(cur)) { - o2[k] = copyBuffer(cur); - } else { - o2[k] = clone(cur); - } - } - return o2; - } - - function cloneProto(o) { - if (typeof o !== 'object' || o === null) return o; - if (o instanceof Date) return new Date(o); - if (Array.isArray(o)) return cloneArray(o, cloneProto); - if (o instanceof Map) return new Map(cloneArray(Array.from(o), cloneProto)); - if (o instanceof Set) return new Set(cloneArray(Array.from(o), cloneProto)); - var o2 = {}; - for (var k in o) { - var cur = o[k]; - if (typeof cur !== 'object' || cur === null) { - o2[k] = cur; - } else if (cur instanceof Date) { - o2[k] = new Date(cur); - } else if (cur instanceof Map) { - o2[k] = new Map(cloneArray(Array.from(cur), cloneProto)); - } else if (cur instanceof Set) { - o2[k] = new Set(cloneArray(Array.from(cur), cloneProto)); - } else if (ArrayBuffer.isView(cur)) { - o2[k] = copyBuffer(cur); - } else { - o2[k] = cloneProto(cur); - } - } - return o2; - } +function rfdc (opts) { + opts = opts || {}; + + if (opts.circles) return rfdcCircles(opts) + return opts.proto ? cloneProto : clone + + function cloneArray (a, fn) { + var keys = Object.keys(a); + var a2 = new Array(keys.length); + for (var i = 0; i < keys.length; i++) { + var k = keys[i]; + var cur = a[k]; + if (typeof cur !== 'object' || cur === null) { + a2[k] = cur; + } else if (cur instanceof Date) { + a2[k] = new Date(cur); + } else if (ArrayBuffer.isView(cur)) { + a2[k] = copyBuffer(cur); + } else { + a2[k] = fn(cur); + } + } + return a2 + } + + function clone (o) { + if (typeof o !== 'object' || o === null) return o + if (o instanceof Date) return new Date(o) + if (Array.isArray(o)) return cloneArray(o, clone) + if (o instanceof Map) return new Map(cloneArray(Array.from(o), clone)) + if (o instanceof Set) return new Set(cloneArray(Array.from(o), clone)) + var o2 = {}; + for (var k in o) { + if (Object.hasOwnProperty.call(o, k) === false) continue + var cur = o[k]; + if (typeof cur !== 'object' || cur === null) { + o2[k] = cur; + } else if (cur instanceof Date) { + o2[k] = new Date(cur); + } else if (cur instanceof Map) { + o2[k] = new Map(cloneArray(Array.from(cur), clone)); + } else if (cur instanceof Set) { + o2[k] = new Set(cloneArray(Array.from(cur), clone)); + } else if (ArrayBuffer.isView(cur)) { + o2[k] = copyBuffer(cur); + } else { + o2[k] = clone(cur); + } + } + return o2 + } + + function cloneProto (o) { + if (typeof o !== 'object' || o === null) return o + if (o instanceof Date) return new Date(o) + if (Array.isArray(o)) return cloneArray(o, cloneProto) + if (o instanceof Map) return new Map(cloneArray(Array.from(o), cloneProto)) + if (o instanceof Set) return new Set(cloneArray(Array.from(o), cloneProto)) + var o2 = {}; + for (var k in o) { + var cur = o[k]; + if (typeof cur !== 'object' || cur === null) { + o2[k] = cur; + } else if (cur instanceof Date) { + o2[k] = new Date(cur); + } else if (cur instanceof Map) { + o2[k] = new Map(cloneArray(Array.from(cur), cloneProto)); + } else if (cur instanceof Set) { + o2[k] = new Set(cloneArray(Array.from(cur), cloneProto)); + } else if (ArrayBuffer.isView(cur)) { + o2[k] = copyBuffer(cur); + } else { + o2[k] = cloneProto(cur); + } + } + return o2 + } } -function rfdcCircles(opts) { - var refs = []; - var refsNew = []; - - return opts.proto ? cloneProto : clone; - - function cloneArray(a, fn) { - var keys = Object.keys(a); - var a2 = new Array(keys.length); - for (var i = 0; i < keys.length; i++) { - var k = keys[i]; - var cur = a[k]; - if (typeof cur !== 'object' || cur === null) { - a2[k] = cur; - } else if (cur instanceof Date) { - a2[k] = new Date(cur); - } else if (ArrayBuffer.isView(cur)) { - a2[k] = copyBuffer(cur); - } else { - var index = refs.indexOf(cur); - if (index !== -1) { - a2[k] = refsNew[index]; - } else { - a2[k] = fn(cur); - } - } - } - return a2; - } - - function clone(o) { - if (typeof o !== 'object' || o === null) return o; - if (o instanceof Date) return new Date(o); - if (Array.isArray(o)) return cloneArray(o, clone); - if (o instanceof Map) return new Map(cloneArray(Array.from(o), clone)); - if (o instanceof Set) return new Set(cloneArray(Array.from(o), clone)); - var o2 = {}; - refs.push(o); - refsNew.push(o2); - for (var k in o) { - if (Object.hasOwnProperty.call(o, k) === false) continue; - var cur = o[k]; - if (typeof cur !== 'object' || cur === null) { - o2[k] = cur; - } else if (cur instanceof Date) { - o2[k] = new Date(cur); - } else if (cur instanceof Map) { - o2[k] = new Map(cloneArray(Array.from(cur), clone)); - } else if (cur instanceof Set) { - o2[k] = new Set(cloneArray(Array.from(cur), clone)); - } else if (ArrayBuffer.isView(cur)) { - o2[k] = copyBuffer(cur); - } else { - var i = refs.indexOf(cur); - if (i !== -1) { - o2[k] = refsNew[i]; - } else { - o2[k] = clone(cur); - } - } - } - refs.pop(); - refsNew.pop(); - return o2; - } - - function cloneProto(o) { - if (typeof o !== 'object' || o === null) return o; - if (o instanceof Date) return new Date(o); - if (Array.isArray(o)) return cloneArray(o, cloneProto); - if (o instanceof Map) return new Map(cloneArray(Array.from(o), cloneProto)); - if (o instanceof Set) return new Set(cloneArray(Array.from(o), cloneProto)); - var o2 = {}; - refs.push(o); - refsNew.push(o2); - for (var k in o) { - var cur = o[k]; - if (typeof cur !== 'object' || cur === null) { - o2[k] = cur; - } else if (cur instanceof Date) { - o2[k] = new Date(cur); - } else if (cur instanceof Map) { - o2[k] = new Map(cloneArray(Array.from(cur), cloneProto)); - } else if (cur instanceof Set) { - o2[k] = new Set(cloneArray(Array.from(cur), cloneProto)); - } else if (ArrayBuffer.isView(cur)) { - o2[k] = copyBuffer(cur); - } else { - var i = refs.indexOf(cur); - if (i !== -1) { - o2[k] = refsNew[i]; - } else { - o2[k] = cloneProto(cur); - } - } - } - refs.pop(); - refsNew.pop(); - return o2; - } +function rfdcCircles (opts) { + var refs = []; + var refsNew = []; + + return opts.proto ? cloneProto : clone + + function cloneArray (a, fn) { + var keys = Object.keys(a); + var a2 = new Array(keys.length); + for (var i = 0; i < keys.length; i++) { + var k = keys[i]; + var cur = a[k]; + if (typeof cur !== 'object' || cur === null) { + a2[k] = cur; + } else if (cur instanceof Date) { + a2[k] = new Date(cur); + } else if (ArrayBuffer.isView(cur)) { + a2[k] = copyBuffer(cur); + } else { + var index = refs.indexOf(cur); + if (index !== -1) { + a2[k] = refsNew[index]; + } else { + a2[k] = fn(cur); + } + } + } + return a2 + } + + function clone (o) { + if (typeof o !== 'object' || o === null) return o + if (o instanceof Date) return new Date(o) + if (Array.isArray(o)) return cloneArray(o, clone) + if (o instanceof Map) return new Map(cloneArray(Array.from(o), clone)) + if (o instanceof Set) return new Set(cloneArray(Array.from(o), clone)) + var o2 = {}; + refs.push(o); + refsNew.push(o2); + for (var k in o) { + if (Object.hasOwnProperty.call(o, k) === false) continue + var cur = o[k]; + if (typeof cur !== 'object' || cur === null) { + o2[k] = cur; + } else if (cur instanceof Date) { + o2[k] = new Date(cur); + } else if (cur instanceof Map) { + o2[k] = new Map(cloneArray(Array.from(cur), clone)); + } else if (cur instanceof Set) { + o2[k] = new Set(cloneArray(Array.from(cur), clone)); + } else if (ArrayBuffer.isView(cur)) { + o2[k] = copyBuffer(cur); + } else { + var i = refs.indexOf(cur); + if (i !== -1) { + o2[k] = refsNew[i]; + } else { + o2[k] = clone(cur); + } + } + } + refs.pop(); + refsNew.pop(); + return o2 + } + + function cloneProto (o) { + if (typeof o !== 'object' || o === null) return o + if (o instanceof Date) return new Date(o) + if (Array.isArray(o)) return cloneArray(o, cloneProto) + if (o instanceof Map) return new Map(cloneArray(Array.from(o), cloneProto)) + if (o instanceof Set) return new Set(cloneArray(Array.from(o), cloneProto)) + var o2 = {}; + refs.push(o); + refsNew.push(o2); + for (var k in o) { + var cur = o[k]; + if (typeof cur !== 'object' || cur === null) { + o2[k] = cur; + } else if (cur instanceof Date) { + o2[k] = new Date(cur); + } else if (cur instanceof Map) { + o2[k] = new Map(cloneArray(Array.from(cur), cloneProto)); + } else if (cur instanceof Set) { + o2[k] = new Set(cloneArray(Array.from(cur), cloneProto)); + } else if (ArrayBuffer.isView(cur)) { + o2[k] = copyBuffer(cur); + } else { + var i = refs.indexOf(cur); + if (i !== -1) { + o2[k] = refsNew[i]; + } else { + o2[k] = cloneProto(cur); + } + } + } + refs.pop(); + refsNew.pop(); + return o2 + } } var _default = rfdc_1(); @@ -5480,6 +5480,7 @@ function rdbClient(options = {}) { let c = { count, getMany, + aggregate: groupBy, getAll, getOne, getById, @@ -5525,6 +5526,16 @@ function rdbClient(options = {}) { return proxify(rows, strategy); } + async function groupBy(strategy) { + let args = negotiateGroupBy(null, strategy); + let body = stringify({ + path: 'aggregate', + args + }); + let adapter = netAdapter(url, tableName, { axios: axiosInterceptor, tableOptions }); + return adapter.post(body); + } + async function count(_) { let args = [_].concat(Array.prototype.slice.call(arguments).slice(1)); let body = stringify({ @@ -5577,30 +5588,66 @@ function rdbClient(options = {}) { return [_, where(strategy), ...rest]; else return args; - } - function where(_strategy, path = '') { - if (typeof _strategy !== 'object' || _strategy === null) - return _strategy; + function where(_strategy, path = '') { + if (typeof _strategy !== 'object' || _strategy === null) + return _strategy; - if (Array.isArray(_strategy)) { - return _strategy.map(item => where(item, path)); + if (Array.isArray(_strategy)) { + return _strategy.map(item => where(item, path)); + } + + const strategy = { ..._strategy }; + for (let name in _strategy) { + if (name === 'where' && typeof strategy[name] === 'function') + strategy.where = column(path + 'where')(strategy.where); // Assuming `column` is defined elsewhere. + else if (typeof strategy[name] === 'function') { + strategy[name] = aggregate(path, strategy[name]); + } + else + strategy[name] = where(_strategy[name], path + name + '.'); + } + return strategy; } - const strategy = { ..._strategy }; - for (let name in _strategy) { - if (name === 'where' && typeof strategy[name] === 'function') - strategy.where = column(path + 'where')(strategy.where); // Assuming `column` is defined elsewhere. - else if (typeof strategy[name] === 'function') { - strategy[name] = aggregate(path, strategy[name]); + } + + + + function negotiateGroupBy(_, strategy, ...rest) { + const args = Array.prototype.slice.call(arguments); + if (strategy) + return [_, where(strategy), ...rest]; + else + return args; + + function where(_strategy, path = '') { + if (typeof _strategy !== 'object' || _strategy === null) + return _strategy; + + if (Array.isArray(_strategy)) { + return _strategy.map(item => where(item, path)); } - else - strategy[name] = where(_strategy[name], path + name + '.'); + + const strategy = { ..._strategy }; + for (let name in _strategy) { + if (name === 'where' && typeof strategy[name] === 'function') + strategy.where = column(path + 'where')(strategy.where); // Assuming `column` is defined elsewhere. + else if (typeof strategy[name] === 'function') { + strategy[name] = groupByAggregate(path, strategy[name]); + } + else + strategy[name] = where(_strategy[name], path + name + '.'); + } + return strategy; } - return strategy; + } + + + async function _delete() { let args = Array.prototype.slice.call(arguments); let body = stringify({ @@ -5642,6 +5689,7 @@ function rdbClient(options = {}) { const concurrency = undefined; const args = [concurrency].concat(rest); if (Array.isArray(rows)) { + //todo const proxy = await getMany.apply(null, [rows, ...rest]); proxy.splice.apply(proxy, [0, proxy.length, ...rows]); await proxy.saveChanges.apply(proxy, args); @@ -6116,7 +6164,56 @@ function aggregate(path, arg) { if (property in c) return Reflect.get(...arguments); else { - subColumn = column(path + 'aggregate'); + subColumn = column(path + '_aggregate'); + return column(property); + } + } + + }; + let subColumn; + const proxy = new Proxy(c, handler); + + const result = arg(proxy); + + if (subColumn) + return subColumn(result.self()); + else + return result; + + + function sum(fn) { + return column(path + '_aggregate')(fn(column('')).groupSum()); + } + function avg(fn) { + return column(path + '_aggregate')(fn(column('')).groupAvg()); + } + function max(fn) { + return column(path + '_aggregate')(fn(column('')).groupMax()); + } + function min(fn) { + return column(path + '_aggregate')(fn(column('')).groupMin()); + } + function count(fn) { + return column(path + '_aggregate')(fn(column('')).groupCount()); + } +} + +function groupByAggregate(path, arg) { + + const c = { + sum, + count, + avg, + max, + min + }; + + let handler = { + get(_target, property,) { + if (property in c) + return Reflect.get(...arguments); + else { + subColumn = column(path + '_aggregate'); return column(property); } } @@ -6125,7 +6222,7 @@ function aggregate(path, arg) { let subColumn; const proxy = new Proxy(c, handler); - const result = arg(proxy); + const result = arg(proxy); if (subColumn) return subColumn(result.self()); @@ -6134,19 +6231,19 @@ function aggregate(path, arg) { function sum(fn) { - return column(path + 'aggregate')(fn(column('')).sum()); + return column(path + '_aggregate')(fn(column('')).sum()); } function avg(fn) { - return column(path + 'aggregate')(fn(column('')).avg()); + return column(path + '_aggregate')(fn(column('')).avg()); } function max(fn) { - return column(path + 'aggregate')(fn(column('')).max()); + return column(path + '_aggregate')(fn(column('')).max()); } function min(fn) { - return column(path + 'aggregate')(fn(column('')).min()); + return column(path + '_aggregate')(fn(column('')).min()); } function count(fn) { - return column(path + 'aggregate')(fn(column('')).count()); + return column(path + '_aggregate')(fn(column('')).count()); } }