UNPKG

@pollyjs/adapter

Version:

Extendable base adapter class used by @pollyjs

1,470 lines (1,174 loc) 42.4 kB
/** * @pollyjs/adapter v6.0.6 * * https://github.com/netflix/pollyjs * * Released under the Apache-2.0 License. */ 'use strict'; var utils = require('@pollyjs/utils'); // 7.2.1 RequireObjectCoercible(argument) var _defined = function (it) { if (it == undefined) throw TypeError("Can't call method on " + it); return it; }; // 7.1.13 ToObject(argument) var _toObject = function (it) { return Object(_defined(it)); }; var hasOwnProperty = {}.hasOwnProperty; var _has = function (it, key) { return hasOwnProperty.call(it, key); }; var toString = {}.toString; var _cof = function (it) { return toString.call(it).slice(8, -1); }; // fallback for non-array-like ES3 and non-enumerable old V8 strings // eslint-disable-next-line no-prototype-builtins var _iobject = Object('z').propertyIsEnumerable(0) ? Object : function (it) { return _cof(it) == 'String' ? it.split('') : Object(it); }; // to indexed object, toObject with fallback for non-array-like ES3 strings var _toIobject = function (it) { return _iobject(_defined(it)); }; // 7.1.4 ToInteger var ceil = Math.ceil; var floor = Math.floor; var _toInteger = function (it) { return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; // 7.1.15 ToLength var min = Math.min; var _toLength = function (it) { return it > 0 ? min(_toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; var max = Math.max; var min$1 = Math.min; var _toAbsoluteIndex = function (index, length) { index = _toInteger(index); return index < 0 ? max(index + length, 0) : min$1(index, length); }; // false -> Array#indexOf // true -> Array#includes var _arrayIncludes = function (IS_INCLUDES) { return function ($this, el, fromIndex) { var O = _toIobject($this); var length = _toLength(O.length); var index = _toAbsoluteIndex(fromIndex, length); var value; // Array#includes uses SameValueZero equality algorithm // eslint-disable-next-line no-self-compare if (IS_INCLUDES && el != el) while (length > index) { value = O[index++]; // eslint-disable-next-line no-self-compare if (value != value) return true; // Array#indexOf ignores holes, Array#includes - not } else for (;length > index; index++) if (IS_INCLUDES || index in O) { if (O[index] === el) return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; function unwrapExports (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } function getCjsExportFromNamespace (n) { return n && n['default'] || n; } var _core = createCommonjsModule(function (module) { var core = module.exports = { version: '2.6.9' }; if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef }); var _core_1 = _core.version; var _global = createCommonjsModule(function (module) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self // eslint-disable-next-line no-new-func : Function('return this')(); if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef }); var _library = true; var _shared = createCommonjsModule(function (module) { var SHARED = '__core-js_shared__'; var store = _global[SHARED] || (_global[SHARED] = {}); (module.exports = function (key, value) { return store[key] || (store[key] = value !== undefined ? value : {}); })('versions', []).push({ version: _core.version, mode: 'pure', copyright: '© 2019 Denis Pushkarev (zloirock.ru)' }); }); var id = 0; var px = Math.random(); var _uid = function (key) { return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; var shared = _shared('keys'); var _sharedKey = function (key) { return shared[key] || (shared[key] = _uid(key)); }; var arrayIndexOf = _arrayIncludes(false); var IE_PROTO = _sharedKey('IE_PROTO'); var _objectKeysInternal = function (object, names) { var O = _toIobject(object); var i = 0; var result = []; var key; for (key in O) if (key != IE_PROTO) _has(O, key) && result.push(key); // Don't enum bug & hidden keys while (names.length > i) if (_has(O, key = names[i++])) { ~arrayIndexOf(result, key) || result.push(key); } return result; }; // IE 8- don't enum bug keys var _enumBugKeys = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); // 19.1.2.14 / 15.2.3.14 Object.keys(O) var _objectKeys = Object.keys || function keys(O) { return _objectKeysInternal(O, _enumBugKeys); }; var _aFunction = function (it) { if (typeof it != 'function') throw TypeError(it + ' is not a function!'); return it; }; // optional / simple context binding var _ctx = function (fn, that, length) { _aFunction(fn); if (that === undefined) return fn; switch (length) { case 1: return function (a) { return fn.call(that, a); }; case 2: return function (a, b) { return fn.call(that, a, b); }; case 3: return function (a, b, c) { return fn.call(that, a, b, c); }; } return function (/* ...args */) { return fn.apply(that, arguments); }; }; var _isObject = function (it) { return typeof it === 'object' ? it !== null : typeof it === 'function'; }; var _anObject = function (it) { if (!_isObject(it)) throw TypeError(it + ' is not an object!'); return it; }; var _fails = function (exec) { try { return !!exec(); } catch (e) { return true; } }; // Thank's IE8 for his funny defineProperty var _descriptors = !_fails(function () { return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; }); var document = _global.document; // typeof document.createElement is 'object' in old IE var is = _isObject(document) && _isObject(document.createElement); var _domCreate = function (it) { return is ? document.createElement(it) : {}; }; var _ie8DomDefine = !_descriptors && !_fails(function () { return Object.defineProperty(_domCreate('div'), 'a', { get: function () { return 7; } }).a != 7; }); // 7.1.1 ToPrimitive(input [, PreferredType]) // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string var _toPrimitive = function (it, S) { if (!_isObject(it)) return it; var fn, val; if (S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) return val; if (typeof (fn = it.valueOf) == 'function' && !_isObject(val = fn.call(it))) return val; if (!S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) return val; throw TypeError("Can't convert object to primitive value"); }; var dP = Object.defineProperty; var f = _descriptors ? Object.defineProperty : function defineProperty(O, P, Attributes) { _anObject(O); P = _toPrimitive(P, true); _anObject(Attributes); if (_ie8DomDefine) try { return dP(O, P, Attributes); } catch (e) { /* empty */ } if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); if ('value' in Attributes) O[P] = Attributes.value; return O; }; var _objectDp = { f: f }; var _propertyDesc = function (bitmap, value) { return { enumerable: !(bitmap & 1), configurable: !(bitmap & 2), writable: !(bitmap & 4), value: value }; }; var _hide = _descriptors ? function (object, key, value) { return _objectDp.f(object, key, _propertyDesc(1, value)); } : function (object, key, value) { object[key] = value; return object; }; var PROTOTYPE = 'prototype'; var $export = function (type, name, source) { var IS_FORCED = type & $export.F; var IS_GLOBAL = type & $export.G; var IS_STATIC = type & $export.S; var IS_PROTO = type & $export.P; var IS_BIND = type & $export.B; var IS_WRAP = type & $export.W; var exports = IS_GLOBAL ? _core : _core[name] || (_core[name] = {}); var expProto = exports[PROTOTYPE]; var target = IS_GLOBAL ? _global : IS_STATIC ? _global[name] : (_global[name] || {})[PROTOTYPE]; var key, own, out; if (IS_GLOBAL) source = name; for (key in source) { // contains in native own = !IS_FORCED && target && target[key] !== undefined; if (own && _has(exports, key)) continue; // export native or passed out = own ? target[key] : source[key]; // prevent global pollution for namespaces exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] // bind timers to global for call from export context : IS_BIND && own ? _ctx(out, _global) // wrap global constructors for prevent change them in library : IS_WRAP && target[key] == out ? (function (C) { var F = function (a, b, c) { if (this instanceof C) { switch (arguments.length) { case 0: return new C(); case 1: return new C(a); case 2: return new C(a, b); } return new C(a, b, c); } return C.apply(this, arguments); }; F[PROTOTYPE] = C[PROTOTYPE]; return F; // make static versions for prototype methods })(out) : IS_PROTO && typeof out == 'function' ? _ctx(Function.call, out) : out; // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% if (IS_PROTO) { (exports.virtual || (exports.virtual = {}))[key] = out; // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% if (type & $export.R && expProto && !expProto[key]) _hide(expProto, key, out); } } }; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe $export.R = 128; // real proto method for `library` var _export = $export; // most Object methods by ES6 should accept primitives var _objectSap = function (KEY, exec) { var fn = (_core.Object || {})[KEY] || Object[KEY]; var exp = {}; exp[KEY] = exec(fn); _export(_export.S + _export.F * _fails(function () { fn(1); }), 'Object', exp); }; // 19.1.2.14 Object.keys(O) _objectSap('keys', function () { return function keys(it) { return _objectKeys(_toObject(it)); }; }); var keys = _core.Object.keys; var keys$1 = keys; var _redefine = _hide; var _meta = createCommonjsModule(function (module) { var META = _uid('meta'); var setDesc = _objectDp.f; var id = 0; var isExtensible = Object.isExtensible || function () { return true; }; var FREEZE = !_fails(function () { return isExtensible(Object.preventExtensions({})); }); var setMeta = function (it) { setDesc(it, META, { value: { i: 'O' + ++id, // object ID w: {} // weak collections IDs } }); }; var fastKey = function (it, create) { // return primitive with prefix if (!_isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if (!_has(it, META)) { // can't set metadata to uncaught frozen object if (!isExtensible(it)) return 'F'; // not necessary to add metadata if (!create) return 'E'; // add missing metadata setMeta(it); // return object ID } return it[META].i; }; var getWeak = function (it, create) { if (!_has(it, META)) { // can't set metadata to uncaught frozen object if (!isExtensible(it)) return true; // not necessary to add metadata if (!create) return false; // add missing metadata setMeta(it); // return hash weak collections IDs } return it[META].w; }; // add metadata on freeze-family methods calling var onFreeze = function (it) { if (FREEZE && meta.NEED && isExtensible(it) && !_has(it, META)) setMeta(it); return it; }; var meta = module.exports = { KEY: META, NEED: false, fastKey: fastKey, getWeak: getWeak, onFreeze: onFreeze }; }); var _meta_1 = _meta.KEY; var _meta_2 = _meta.NEED; var _meta_3 = _meta.fastKey; var _meta_4 = _meta.getWeak; var _meta_5 = _meta.onFreeze; var _wks = createCommonjsModule(function (module) { var store = _shared('wks'); var Symbol = _global.Symbol; var USE_SYMBOL = typeof Symbol == 'function'; var $exports = module.exports = function (name) { return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : _uid)('Symbol.' + name)); }; $exports.store = store; }); var def = _objectDp.f; var TAG = _wks('toStringTag'); var _setToStringTag = function (it, tag, stat) { if (it && !_has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); }; var f$1 = _wks; var _wksExt = { f: f$1 }; var defineProperty = _objectDp.f; var _wksDefine = function (name) { var $Symbol = _core.Symbol || (_core.Symbol = {}); if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: _wksExt.f(name) }); }; var f$2 = Object.getOwnPropertySymbols; var _objectGops = { f: f$2 }; var f$3 = {}.propertyIsEnumerable; var _objectPie = { f: f$3 }; // all enumerable object keys, includes symbols var _enumKeys = function (it) { var result = _objectKeys(it); var getSymbols = _objectGops.f; if (getSymbols) { var symbols = getSymbols(it); var isEnum = _objectPie.f; var i = 0; var key; while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key); } return result; }; // 7.2.2 IsArray(argument) var _isArray = Array.isArray || function isArray(arg) { return _cof(arg) == 'Array'; }; var _objectDps = _descriptors ? Object.defineProperties : function defineProperties(O, Properties) { _anObject(O); var keys = _objectKeys(Properties); var length = keys.length; var i = 0; var P; while (length > i) _objectDp.f(O, P = keys[i++], Properties[P]); return O; }; var document$1 = _global.document; var _html = document$1 && document$1.documentElement; // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var IE_PROTO$1 = _sharedKey('IE_PROTO'); var Empty = function () { /* empty */ }; var PROTOTYPE$1 = 'prototype'; // Create object with fake `null` prototype: use iframe Object with cleared prototype var createDict = function () { // Thrash, waste and sodomy: IE GC bug var iframe = _domCreate('iframe'); var i = _enumBugKeys.length; var lt = '<'; var gt = '>'; var iframeDocument; iframe.style.display = 'none'; _html.appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while (i--) delete createDict[PROTOTYPE$1][_enumBugKeys[i]]; return createDict(); }; var _objectCreate = Object.create || function create(O, Properties) { var result; if (O !== null) { Empty[PROTOTYPE$1] = _anObject(O); result = new Empty(); Empty[PROTOTYPE$1] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO$1] = O; } else result = createDict(); return Properties === undefined ? result : _objectDps(result, Properties); }; // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) var hiddenKeys = _enumBugKeys.concat('length', 'prototype'); var f$4 = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { return _objectKeysInternal(O, hiddenKeys); }; var _objectGopn = { f: f$4 }; // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window var gOPN = _objectGopn.f; var toString$1 = {}.toString; var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : []; var getWindowNames = function (it) { try { return gOPN(it); } catch (e) { return windowNames.slice(); } }; var f$5 = function getOwnPropertyNames(it) { return windowNames && toString$1.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(_toIobject(it)); }; var _objectGopnExt = { f: f$5 }; var gOPD = Object.getOwnPropertyDescriptor; var f$6 = _descriptors ? gOPD : function getOwnPropertyDescriptor(O, P) { O = _toIobject(O); P = _toPrimitive(P, true); if (_ie8DomDefine) try { return gOPD(O, P); } catch (e) { /* empty */ } if (_has(O, P)) return _propertyDesc(!_objectPie.f.call(O, P), O[P]); }; var _objectGopd = { f: f$6 }; // ECMAScript 6 symbols shim var META = _meta.KEY; var gOPD$1 = _objectGopd.f; var dP$1 = _objectDp.f; var gOPN$1 = _objectGopnExt.f; var $Symbol = _global.Symbol; var $JSON = _global.JSON; var _stringify = $JSON && $JSON.stringify; var PROTOTYPE$2 = 'prototype'; var HIDDEN = _wks('_hidden'); var TO_PRIMITIVE = _wks('toPrimitive'); var isEnum = {}.propertyIsEnumerable; var SymbolRegistry = _shared('symbol-registry'); var AllSymbols = _shared('symbols'); var OPSymbols = _shared('op-symbols'); var ObjectProto = Object[PROTOTYPE$2]; var USE_NATIVE = typeof $Symbol == 'function' && !!_objectGops.f; var QObject = _global.QObject; // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 var setter = !QObject || !QObject[PROTOTYPE$2] || !QObject[PROTOTYPE$2].findChild; // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 var setSymbolDesc = _descriptors && _fails(function () { return _objectCreate(dP$1({}, 'a', { get: function () { return dP$1(this, 'a', { value: 7 }).a; } })).a != 7; }) ? function (it, key, D) { var protoDesc = gOPD$1(ObjectProto, key); if (protoDesc) delete ObjectProto[key]; dP$1(it, key, D); if (protoDesc && it !== ObjectProto) dP$1(ObjectProto, key, protoDesc); } : dP$1; var wrap = function (tag) { var sym = AllSymbols[tag] = _objectCreate($Symbol[PROTOTYPE$2]); sym._k = tag; return sym; }; var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) { return typeof it == 'symbol'; } : function (it) { return it instanceof $Symbol; }; var $defineProperty = function defineProperty(it, key, D) { if (it === ObjectProto) $defineProperty(OPSymbols, key, D); _anObject(it); key = _toPrimitive(key, true); _anObject(D); if (_has(AllSymbols, key)) { if (!D.enumerable) { if (!_has(it, HIDDEN)) dP$1(it, HIDDEN, _propertyDesc(1, {})); it[HIDDEN][key] = true; } else { if (_has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false; D = _objectCreate(D, { enumerable: _propertyDesc(0, false) }); } return setSymbolDesc(it, key, D); } return dP$1(it, key, D); }; var $defineProperties = function defineProperties(it, P) { _anObject(it); var keys = _enumKeys(P = _toIobject(P)); var i = 0; var l = keys.length; var key; while (l > i) $defineProperty(it, key = keys[i++], P[key]); return it; }; var $create = function create(it, P) { return P === undefined ? _objectCreate(it) : $defineProperties(_objectCreate(it), P); }; var $propertyIsEnumerable = function propertyIsEnumerable(key) { var E = isEnum.call(this, key = _toPrimitive(key, true)); if (this === ObjectProto && _has(AllSymbols, key) && !_has(OPSymbols, key)) return false; return E || !_has(this, key) || !_has(AllSymbols, key) || _has(this, HIDDEN) && this[HIDDEN][key] ? E : true; }; var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { it = _toIobject(it); key = _toPrimitive(key, true); if (it === ObjectProto && _has(AllSymbols, key) && !_has(OPSymbols, key)) return; var D = gOPD$1(it, key); if (D && _has(AllSymbols, key) && !(_has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true; return D; }; var $getOwnPropertyNames = function getOwnPropertyNames(it) { var names = gOPN$1(_toIobject(it)); var result = []; var i = 0; var key; while (names.length > i) { if (!_has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key); } return result; }; var $getOwnPropertySymbols = function getOwnPropertySymbols(it) { var IS_OP = it === ObjectProto; var names = gOPN$1(IS_OP ? OPSymbols : _toIobject(it)); var result = []; var i = 0; var key; while (names.length > i) { if (_has(AllSymbols, key = names[i++]) && (IS_OP ? _has(ObjectProto, key) : true)) result.push(AllSymbols[key]); } return result; }; // 19.4.1.1 Symbol([description]) if (!USE_NATIVE) { $Symbol = function Symbol() { if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!'); var tag = _uid(arguments.length > 0 ? arguments[0] : undefined); var $set = function (value) { if (this === ObjectProto) $set.call(OPSymbols, value); if (_has(this, HIDDEN) && _has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; setSymbolDesc(this, tag, _propertyDesc(1, value)); }; if (_descriptors && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set }); return wrap(tag); }; _redefine($Symbol[PROTOTYPE$2], 'toString', function toString() { return this._k; }); _objectGopd.f = $getOwnPropertyDescriptor; _objectDp.f = $defineProperty; _objectGopn.f = _objectGopnExt.f = $getOwnPropertyNames; _objectPie.f = $propertyIsEnumerable; _objectGops.f = $getOwnPropertySymbols; if (_descriptors && !_library) { _redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); } _wksExt.f = function (name) { return wrap(_wks(name)); }; } _export(_export.G + _export.W + _export.F * !USE_NATIVE, { Symbol: $Symbol }); for (var es6Symbols = ( // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' ).split(','), j = 0; es6Symbols.length > j;)_wks(es6Symbols[j++]); for (var wellKnownSymbols = _objectKeys(_wks.store), k = 0; wellKnownSymbols.length > k;) _wksDefine(wellKnownSymbols[k++]); _export(_export.S + _export.F * !USE_NATIVE, 'Symbol', { // 19.4.2.1 Symbol.for(key) 'for': function (key) { return _has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = $Symbol(key); }, // 19.4.2.5 Symbol.keyFor(sym) keyFor: function keyFor(sym) { if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!'); for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key; }, useSetter: function () { setter = true; }, useSimple: function () { setter = false; } }); _export(_export.S + _export.F * !USE_NATIVE, 'Object', { // 19.1.2.2 Object.create(O [, Properties]) create: $create, // 19.1.2.4 Object.defineProperty(O, P, Attributes) defineProperty: $defineProperty, // 19.1.2.3 Object.defineProperties(O, Properties) defineProperties: $defineProperties, // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: $getOwnPropertyDescriptor, // 19.1.2.7 Object.getOwnPropertyNames(O) getOwnPropertyNames: $getOwnPropertyNames, // 19.1.2.8 Object.getOwnPropertySymbols(O) getOwnPropertySymbols: $getOwnPropertySymbols }); // Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives // https://bugs.chromium.org/p/v8/issues/detail?id=3443 var FAILS_ON_PRIMITIVES = _fails(function () { _objectGops.f(1); }); _export(_export.S + _export.F * FAILS_ON_PRIMITIVES, 'Object', { getOwnPropertySymbols: function getOwnPropertySymbols(it) { return _objectGops.f(_toObject(it)); } }); // 24.3.2 JSON.stringify(value [, replacer [, space]]) $JSON && _export(_export.S + _export.F * (!USE_NATIVE || _fails(function () { var S = $Symbol(); // MS Edge converts symbol values to JSON as {} // WebKit converts symbol values to JSON as null // V8 throws on boxed symbols return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}'; })), 'JSON', { stringify: function stringify(it) { var args = [it]; var i = 1; var replacer, $replacer; while (arguments.length > i) args.push(arguments[i++]); $replacer = replacer = args[1]; if (!_isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined if (!_isArray(replacer)) replacer = function (key, value) { if (typeof $replacer == 'function') value = $replacer.call(this, key, value); if (!isSymbol(value)) return value; }; args[1] = replacer; return _stringify.apply($JSON, args); } }); // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) $Symbol[PROTOTYPE$2][TO_PRIMITIVE] || _hide($Symbol[PROTOTYPE$2], TO_PRIMITIVE, $Symbol[PROTOTYPE$2].valueOf); // 19.4.3.5 Symbol.prototype[@@toStringTag] _setToStringTag($Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] _setToStringTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] _setToStringTag(_global.JSON, 'JSON', true); var getOwnPropertySymbols = _core.Object.getOwnPropertySymbols; var getOwnPropertySymbols$1 = getOwnPropertySymbols; // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) var $getOwnPropertyDescriptor$1 = _objectGopd.f; _objectSap('getOwnPropertyDescriptor', function () { return function getOwnPropertyDescriptor(it, key) { return $getOwnPropertyDescriptor$1(_toIobject(it), key); }; }); var $Object = _core.Object; var getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { return $Object.getOwnPropertyDescriptor(it, key); }; var getOwnPropertyDescriptor$1 = getOwnPropertyDescriptor; // all object keys, includes non-enumerable and symbols var Reflect = _global.Reflect; var _ownKeys = Reflect && Reflect.ownKeys || function ownKeys(it) { var keys = _objectGopn.f(_anObject(it)); var getSymbols = _objectGops.f; return getSymbols ? keys.concat(getSymbols(it)) : keys; }; var _createProperty = function (object, index, value) { if (index in object) _objectDp.f(object, index, _propertyDesc(0, value)); else object[index] = value; }; // https://github.com/tc39/proposal-object-getownpropertydescriptors _export(_export.S, 'Object', { getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) { var O = _toIobject(object); var getDesc = _objectGopd.f; var keys = _ownKeys(O); var result = {}; var i = 0; var key, desc; while (keys.length > i) { desc = getDesc(O, key = keys[i++]); if (desc !== undefined) _createProperty(result, key, desc); } return result; } }); var getOwnPropertyDescriptors = _core.Object.getOwnPropertyDescriptors; var getOwnPropertyDescriptors$1 = getOwnPropertyDescriptors; // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) _export(_export.S + _export.F * !_descriptors, 'Object', { defineProperties: _objectDps }); var $Object$1 = _core.Object; var defineProperties = function defineProperties(T, D) { return $Object$1.defineProperties(T, D); }; var defineProperties$1 = defineProperties; // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) _export(_export.S + _export.F * !_descriptors, 'Object', { defineProperty: _objectDp.f }); var $Object$2 = _core.Object; var defineProperty$1 = function defineProperty(it, key, desc) { return $Object$2.defineProperty(it, key, desc); }; var defineProperty$2 = defineProperty$1; var defineProperty$3 = createCommonjsModule(function (module) { function _defineProperty(obj, key, value) { if (key in obj) { defineProperty$2(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } module.exports = _defineProperty; module.exports["default"] = module.exports, module.exports.__esModule = true; }); var _defineProperty = unwrapExports(defineProperty$3); var es6_object_toString = /*#__PURE__*/Object.freeze({ }); _wksDefine('asyncIterator'); _wksDefine('observable'); getCjsExportFromNamespace(es6_object_toString); var symbol = _core.Symbol; var symbol$1 = symbol; var $JSON$1 = _core.JSON || (_core.JSON = { stringify: JSON.stringify }); var stringify = function stringify(it) { // eslint-disable-line no-unused-vars return $JSON$1.stringify.apply($JSON$1, arguments); }; var stringify$1 = stringify; var _stringWs = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; var space = '[' + _stringWs + ']'; var non = '\u200b\u0085'; var ltrim = RegExp('^' + space + space + '*'); var rtrim = RegExp(space + space + '*$'); var exporter = function (KEY, exec, ALIAS) { var exp = {}; var FORCE = _fails(function () { return !!_stringWs[KEY]() || non[KEY]() != non; }); var fn = exp[KEY] = FORCE ? exec(trim) : _stringWs[KEY]; if (ALIAS) exp[ALIAS] = fn; _export(_export.P + _export.F * FORCE, 'String', exp); }; // 1 -> String#trimLeft // 2 -> String#trimRight // 3 -> String#trim var trim = exporter.trim = function (string, TYPE) { string = String(_defined(string)); if (TYPE & 1) string = string.replace(ltrim, ''); if (TYPE & 2) string = string.replace(rtrim, ''); return string; }; var _stringTrim = exporter; var $parseFloat = _global.parseFloat; var $trim = _stringTrim.trim; var _parseFloat = 1 / $parseFloat(_stringWs + '-0') !== -Infinity ? function parseFloat(str) { var string = $trim(String(str), 3); var result = $parseFloat(string); return result === 0 && string.charAt(0) == '-' ? -0 : result; } : $parseFloat; // 18.2.4 parseFloat(string) _export(_export.G + _export.F * (parseFloat != _parseFloat), { parseFloat: _parseFloat }); var _parseFloat$1 = _core.parseFloat; var _parseFloat$2 = _parseFloat$1; const ALPHA_NUMERIC_DOT = /([0-9.]+)([a-zA-Z]+)/g; const TIMES = { ms: 1, millisecond: 1, milliseconds: 1, s: 1000, sec: 1000, secs: 1000, second: 1000, seconds: 1000, m: 60000, min: 60000, mins: 60000, minute: 60000, minutes: 60000, h: 3600000, hr: 3600000, hrs: 3600000, hour: 3600000, hours: 3600000, d: 86400000, day: 86400000, days: 86400000, w: 604800000, wk: 604800000, wks: 604800000, week: 604800000, weeks: 604800000, y: 31536000000, yr: 31536000000, yrs: 31536000000, year: 31536000000, years: 31536000000 }; function dehumanizeTime(input) { if (typeof input !== 'string') { return NaN; } const parts = input.replace(/ /g, '').match(ALPHA_NUMERIC_DOT); const sets = parts.map(part => part.split(ALPHA_NUMERIC_DOT).filter(o => o)); return sets.reduce((accum, [number, unit]) => { return accum + _parseFloat$2(number) * TIMES[unit]; }, 0); } function isExpired(recordedOn, expiresIn) { if (recordedOn && expiresIn) { return new Date() > new Date(new Date(recordedOn).getTime() + dehumanizeTime(expiresIn)); } return false; } function ownKeys(object, enumerableOnly) { var keys = keys$1(object); if (getOwnPropertySymbols$1) { var symbols = getOwnPropertySymbols$1(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return getOwnPropertyDescriptor$1(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (getOwnPropertyDescriptors$1) { defineProperties$1(target, getOwnPropertyDescriptors$1(source)); } else { ownKeys(Object(source)).forEach(function (key) { defineProperty$2(target, key, getOwnPropertyDescriptor$1(source, key)); }); } } return target; } function stringifyRequest(req, ...args) { const config = _objectSpread({}, req.config); // Remove all adapter & persister config options as they can cause a circular // structure to the final JSON ['adapter', 'adapterOptions', 'persister', 'persisterOptions'].forEach(k => delete config[k]); return stringify$1({ url: req.url, method: req.method, headers: req.headers, body: req.body, recordingName: req.recordingName, id: req.id, order: req.order, identifiers: req.identifiers, config }, ...args); } const { isArray } = Array; function normalizeRecordedResponse(response) { const { status, statusText, headers, content } = response; return { statusText, statusCode: status, headers: normalizeHeaders(headers), body: content && content.text, encoding: content && content.encoding }; } function normalizeHeaders(headers) { return (headers || []).reduce((accum, { name, value, _fromType }) => { const existingValue = accum[name]; if (existingValue) { if (!isArray(existingValue)) { accum[name] = [existingValue]; } accum[name].push(value); } else { accum[name] = _fromType === 'array' ? [value] : value; } return accum; }, {}); } function ownKeys$1(object, enumerableOnly) { var keys = keys$1(object); if (getOwnPropertySymbols$1) { var symbols = getOwnPropertySymbols$1(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return getOwnPropertyDescriptor$1(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (getOwnPropertyDescriptors$1) { defineProperties$1(target, getOwnPropertyDescriptors$1(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { defineProperty$2(target, key, getOwnPropertyDescriptor$1(source, key)); }); } } return target; } const REQUEST_HANDLER = symbol$1(); class Adapter { constructor(polly) { this.polly = polly; this.isConnected = false; } static get type() { return 'adapter'; } /* eslint-disable-next-line getter-return */ static get id() { utils.assert('Must override the static `id` getter.'); } get defaultOptions() { return {}; } get options() { return _objectSpread$1(_objectSpread$1({}, this.defaultOptions || {}), (this.polly.config.adapterOptions || {})[this.constructor.id] || {}); } get persister() { return this.polly.persister; } connect() { if (!this.isConnected) { this.onConnect(); this.isConnected = true; this.polly.logger.log.debug(`Connected to ${this.constructor.id} adapter.`); } } onConnect() { this.assert('Must implement the `onConnect` hook.'); } disconnect() { if (this.isConnected) { this.onDisconnect(); this.isConnected = false; this.polly.logger.log.debug(`Disconnected from ${this.constructor.id} adapter.`); } } onDisconnect() { this.assert('Must implement the `onDisconnect` hook.'); } timeout(pollyRequest, { time }) { const { timing } = pollyRequest.config; if (typeof timing === 'function') { return timing(time); } } async handleRequest(request) { const pollyRequest = this.polly.registerRequest(request); try { pollyRequest.on('identify', (...args) => this.onIdentifyRequest(...args)); await this.onRequest(pollyRequest); await pollyRequest.init(); await this[REQUEST_HANDLER](pollyRequest); if (pollyRequest.aborted) { throw new utils.PollyError('Request aborted.'); } await this.onRequestFinished(pollyRequest); } catch (error) { await this.onRequestFailed(pollyRequest, error); } return pollyRequest; } async [REQUEST_HANDLER](pollyRequest) { const { mode } = this.polly; const { _interceptor: interceptor } = pollyRequest; if (pollyRequest.aborted) { return; } if (pollyRequest.shouldIntercept) { await this.intercept(pollyRequest, interceptor); if (interceptor.shouldIntercept) { return; } } if (mode === utils.MODES.PASSTHROUGH || pollyRequest.shouldPassthrough || interceptor.shouldPassthrough) { return this.passthrough(pollyRequest); } this.assert('A persister must be configured in order to record and replay requests.', !!this.persister); if (mode === utils.MODES.RECORD) { return this.record(pollyRequest); } if (mode === utils.MODES.REPLAY) { return this.replay(pollyRequest); } // This should never be reached. If it did, then something screwy happened. this.assert('Unhandled request: \n' + stringifyRequest(pollyRequest, null, 2)); } async passthrough(pollyRequest) { pollyRequest.action = utils.ACTIONS.PASSTHROUGH; return this.onPassthrough(pollyRequest); } /** * @param {PollyRequest} pollyRequest */ async onPassthrough(pollyRequest) { const response = await this.onFetchResponse(pollyRequest); await pollyRequest.respond(response); } async intercept(pollyRequest, interceptor) { pollyRequest.action = utils.ACTIONS.INTERCEPT; await pollyRequest._intercept(interceptor); if (interceptor.shouldIntercept) { return this.onIntercept(pollyRequest, pollyRequest.response); } } /** * @param {PollyRequest} pollyRequest * @param {PollyResponse} pollyResponse */ async onIntercept(pollyRequest, pollyResponse) { await pollyRequest.respond(pollyResponse); } async record(pollyRequest) { pollyRequest.action = utils.ACTIONS.RECORD; if ('navigator' in global && !navigator.onLine) { pollyRequest.log.warn('[Polly] Recording may fail because the browser is offline.\n' + `${stringifyRequest(pollyRequest)}`); } return this.onRecord(pollyRequest); } /** * @param {PollyRequest} pollyRequest */ async onRecord(pollyRequest) { await this.onPassthrough(pollyRequest); if (!pollyRequest.aborted) { await this.persister.recordRequest(pollyRequest); } } async replay(pollyRequest) { const { config } = pollyRequest; const recordingEntry = await this.persister.findEntry(pollyRequest); if (recordingEntry) { /* Clone the recording entry so any changes will not actually persist to the stored recording. Note: Using JSON.parse/stringify instead of lodash/cloneDeep since the recording entry is stored as json. */ const clonedRecordingEntry = JSON.parse(stringify$1(recordingEntry)); await pollyRequest._emit('beforeReplay', clonedRecordingEntry); if (isExpired(clonedRecordingEntry.startedDateTime, config.expiresIn)) { const message = 'Recording for the following request has expired.\n' + `${stringifyRequest(pollyRequest, null, 2)}`; switch (config.expiryStrategy) { // exit into the record flow if expiryStrategy is "record". case utils.EXPIRY_STRATEGIES.RECORD: return this.record(pollyRequest); // throw an error and exit if expiryStrategy is "error". case utils.EXPIRY_STRATEGIES.ERROR: this.assert(message); break; // log a warning and continue if expiryStrategy is "warn". case utils.EXPIRY_STRATEGIES.WARN: pollyRequest.log.warn(`[Polly] ${message}`); break; // throw an error if we encounter an unsupported expiryStrategy. default: this.assert(`Invalid config option passed for "expiryStrategy": "${config.expiryStrategy}"`); break; } } await this.timeout(pollyRequest, clonedRecordingEntry); pollyRequest.action = utils.ACTIONS.REPLAY; return this.onReplay(pollyRequest, normalizeRecordedResponse(clonedRecordingEntry.response), clonedRecordingEntry); } if (config.recordIfMissing) { return this.record(pollyRequest); } this.assert('Recording for the following request is not found and `recordIfMissing` is `false`.\n' + stringifyRequest(pollyRequest, null, 2)); } /** * @param {PollyRequest} pollyRequest * @param {Object} normalizedResponse The normalized response generated from the recording entry * @param {Object} recordingEntry The entire recording entry */ async onReplay(pollyRequest, normalizedResponse) { await pollyRequest.respond(normalizedResponse); } assert(message, ...args) { utils.assert(`[${this.constructor.type}:${this.constructor.id}] ${message}`, ...args); } /** * @param {PollyRequest} pollyRequest */ onRequest() {} /** * @param {PollyRequest} pollyRequest */ async onIdentifyRequest(pollyRequest) { const { identifiers } = pollyRequest; // Serialize the request body so it can be properly hashed for (const type of ['blob', 'formData', 'buffer']) { identifiers.body = await utils.Serializers[type](identifiers.body); } } /** * @param {PollyRequest} pollyRequest */ async onRequestFinished(pollyRequest) { await this.onRespond(pollyRequest); pollyRequest.promise.resolve(); } /** * @param {PollyRequest} pollyRequest * @param {Error} [error] */ async onRequestFailed(pollyRequest, error) { const { aborted } = pollyRequest; error = error || new utils.PollyError('Request failed due to an unknown error.'); try { if (aborted) { await pollyRequest._emit('abort'); } else { await pollyRequest._emit('error', error); } await this.onRespond(pollyRequest, error); } finally { pollyRequest.promise.reject(error); } } /** * Make sure the response from a Polly request is delivered to the * user through the adapter interface. * * Calling `pollyjs.flush()` will await this method. * * @param {PollyRequest} pollyRequest * @param {Error} [error] */ async onRespond() {} /** * @param {PollyRequest} pollyRequest * @returns {Object({ statusCode: number, headers: Object, body: string })} */ async onFetchResponse() { this.assert('Must implement the `onFetchResponse` hook.'); } } module.exports = Adapter; //# sourceMappingURL=pollyjs-adapter.js.map