---
title: "Ray Gunn First Look: The Newest Animated Film from Brad Bird Starring Sam Rockwell and Scarlett Joha"
url: https://stacklist.com/card/b107ed03-7452-45a5-9016-af1fdde8bc29
source_url: "https://www.netflix.com/tudum/articles/ray-gunn-first-look"
stack: https://stacklist.com/stack/5585fb0e-57ce-4bc8-a1e2-028396e6569e
summary: "IntersectionObserver is a JavaScript API that detects when elements enter or leave the viewport by calculating intersection rectangles and comparing threshold values. The code provides utility functions for computing bounding client rectangles, expanding root margins, and determining threshold crossings for intersection detection."
tags: "intersection-observer, javascript, dom-api, bounding-rect, web-api, polyfill"
key_entities: "IntersectionObserver (technology), JavaScript (technology), DOM API (technology), getBoundingClientRect (concept), Windows 7 IE11 (location)"
classification: "code"
content_hash: "sha256:d041839f589d7c44b5eafbd377ea47bcf769aea2a9d6e0b9e47ee9703dca32d6"
acp_version: "0.2"
token_counts_approximate: 22283
visibility: public
agent_accessible: true
status: "final"
---

# Ray Gunn First Look: The Newest Animated Film from Brad Bird Starring Sam Rockwell and Scarlett Joha

// or element, update the intersection rect. // Note: and cannot be clipped to a rect that's not also // the document rect, so no need to compute a new intersection. if (parent != document.body && parent != document.documentElement && parentComputedStyle.overflow != 'visible') { parentRect = getBoundingClientRect(parent); } } // If either of the above conditionals set a new parentRect, // calculate new intersection data. if (parentRect) { intersectionRect = computeRectIntersection(parentRect, intersectionRect); if (!intersectionRect) break; } parent = getParentNode(parent); } return intersectionRect; }; /** * Returns the root rect after being expanded by the rootMargin value. * @return {Object} The expanded root rect. * @private */ IntersectionObserver.prototype._getRootRect = function() { var rootRect; if (this.root) { rootRect = getBoundingClientRect(this.root); } else { // Use / instead of window since scroll bars affect size. var html = document.documentElement; var body = document.body; rootRect = { x: 0, y: 0, top: 0, left: 0, right: html.clientWidth || body.clientWidth, width: html.clientWidth || body.clientWidth, bottom: html.clientHeight || body.clientHeight, height: html.clientHeight || body.clientHeight }; } return this._expandRectByRootMargin(rootRect); }; /** * Accepts a rect and expands it by the rootMargin value. * @param {Object} rect The rect object to expand. * @return {Object} The expanded rect. * @private */ IntersectionObserver.prototype._expandRectByRootMargin = function(rect) { var margins = this._rootMarginValues.map(function(margin, i) { return margin.unit == 'px' ? margin.value : margin.value * (i % 2 ? rect.width : rect.height) / 100; }); var newRect = { top: rect.top - margins[0], right: rect.right + margins[1], bottom: rect.bottom + margins[2], left: rect.left - margins[3] }; newRect.width = newRect.right - newRect.left; newRect.height = newRect.bottom - newRect.top; newRect.x = newRect.left; newRect.y = newRect.top; return newRect; }; /** * Accepts an old and new entry and returns true if at least one of the * threshold values has been crossed. * @param {?IntersectionObserverEntry} oldEntry The previous entry for a * particular target element or null if no previous entry exists. * @param {IntersectionObserverEntry} newEntry The current entry for a * particular target element. * @return {boolean} Returns true if a any threshold has been crossed. * @private */ IntersectionObserver.prototype._hasCrossedThreshold = function(oldEntry, newEntry) { // To make comparing easier, an entry that has a ratio of 0 // but does not actually intersect is given a value of -1 var oldRatio = oldEntry && oldEntry.isIntersecting ? oldEntry.intersectionRatio || 0 : -1; var newRatio = newEntry.isIntersecting ? newEntry.intersectionRatio || 0 : -1; // Ignore unchanged ratios if (oldRatio === newRatio) return; for (var i = 0; i = 0 && height >= 0) && { x: left, y: top, top: top, bottom: bottom, left: left, right: right, width: width, height: height }; } /** * Shims the native getBoundingClientRect for compatibility with older IE. * @param {Element} el The element whose bounding rect to get. * @return {Object} The (possibly shimmed) rect of the element. */ function getBoundingClientRect(el) { var rect; try { rect = el.getBoundingClientRect(); } catch (err) { // Ignore Windows 7 IE11 "Unspecified error" // https://github.com/w3c/IntersectionObserver/pull/205 } if (!rect) return getEmptyRect(); // Older IE if (!(rect.width && rect.height && rect.x && rect.y)) { rect = { x: rect.left, y: rect.top, top: rect.top, right: rect.right, bottom: rect.bottom, left: rect.left, width: rect.right - rect.left, height: rect.bottom - rect.top }; } return rect; } /** * Returns an empty rect object. An empty rect is returned when an element * is not in the DOM. * @return {Object} The empty rect. */ function getEmptyRect() { return { x: 0, y: 0, top: 0, bottom: 0, left: 0, right: 0, width: 0, height: 0 }; } /** * Checks to see if a parent element contains a child element (including inside * shadow DOM). * @param {Node} parent The parent element. * @param {Node} child The child element. * @return {boolean} True if the parent node contains the child node. */ function containsDeep(parent, child) { var node = child; while (node) { if (node == parent) return true; node = getParentNode(node); } return false; } /** * Gets the parent node of an element or its host element if the parent node * is a shadow root. * @param {Node} node The node whose parent to get. * @return {Node|null} The parent node or null if no parent exists. */ function getParentNode(node) { var parent = node.parentNode; if (parent && parent.nodeType == 11 && parent.host) { // If the parent is a shadow root, return the host element. return parent.host; } if (parent && parent.assignedSlot) { // If the parent is distributed in a , return the parent of a slot. return parent.assignedSlot.parentNode; } return parent; } // Exposes the constructors globally. window.IntersectionObserver = IntersectionObserver; window.IntersectionObserverEntry = IntersectionObserverEntry; }(window, document)); } if (!("IntersectionObserverEntry"in window&&"isIntersecting"in window.IntersectionObserverEntry.prototype )) { // IntersectionObserverEntry // Minimal polyfill for Edge 15's lack of `isIntersecting` // See: https://github.com/w3c/IntersectionObserver/issues/211 Object.defineProperty(IntersectionObserverEntry.prototype, 'isIntersecting', { get: function () { return this.intersectionRatio > 0; } } ); } if (!("Reflect"in self )) { // Reflect // 26.1 The Reflect Object try { Object.defineProperty(self, "Reflect", { value: self.Reflect || {}, writable: true, configurable: true, enumerable: false }); } catch (e) { self.Reflect = self.Reflect || {}; } } if (!("flags"in RegExp.prototype )) { // RegExp.prototype.flags /* global Get, ToBoolean, Type */ Object.defineProperty(RegExp.prototype, 'flags', { configurable: true, enumerable: false, get: function () { // 21.2.5.3.1 Let R be the this value. var R = this; // 21.2.5.3.2 If Type(R) is not Object, throw a TypeError exception. if (Type(R) !== 'object') { throw new TypeError('Method called on incompatible type: must be an object.'); } // 21.2.5.3.3 Let result be the empty String. var result = ''; // 21.2.5.3.4 Let global be ToBoolean(? Get(R, "global")). var global = ToBoolean(Get(R, 'global')); // 21.2.5.3.5 If global is true, append the code unit 0x0067 (LATIN SMALL LETTER G) as the last code unit of result. if (global) { result += 'g'; } // 21.2.5.3.6 Let ignoreCase be ToBoolean(? Get(R, "ignoreCase")). var ignoreCase = ToBoolean(Get(R, 'ignoreCase')); // 21.2.5.3.7 If ignoreCase is true, append the code unit 0x0069 (LATIN SMALL LETTER I) as the last code unit of result. if (ignoreCase) { result += 'i'; } // 21.2.5.3.8 Let multiline be ToBoolean(? Get(R, "multiline")). var multiline = ToBoolean(Get(R, 'multiline')); // 21.2.5.3.9 If multiline is true, append the code unit 0x006D (LATIN SMALL LETTER M) as the last code unit of result. if (multiline) { result += 'm'; } // 21.2.5.3.10 Let unicode be ToBoolean(? Get(R, "unicode")). var unicode = ToBoolean(Get(R, 'unicode')); // 21.2.5.3.11 If unicode is true, append the code unit 0x0075 (LATIN SMALL LETTER U) as the last code unit of result. if (unicode) { result += 'u'; } // 21.2.5.3.12 Let sticky be ToBoolean(? Get(R, "sticky")). var sticky = ToBoolean(Get(R, 'sticky')); // 21.2.5.3.13 If sticky is true, append the code unit 0x0079 (LATIN SMALL LETTER Y) as the last code unit of result. if (sticky) { result += 'y'; } // 21.2.5.3.14 Return result. return result; } }); } if (!("requestAnimationFrame"in self )) { // requestAnimationFrame (function (global) { var rafPrefix; // do not inject RAF in order to avoid broken performance var nowOffset = Date.now(); // use performance api if exist, otherwise use Date.now. // Date.now polyfill required. var pnow = function () { if (global.performance && typeof global.performance.now === 'function') { return global.performance.now(); } // fallback return Date.now() - nowOffset; }; if ('mozRequestAnimationFrame' in global) { rafPrefix = 'moz'; } else if ('webkitRequestAnimationFrame' in global) { rafPrefix = 'webkit'; } if (rafPrefix) { global.requestAnimationFrame = function (callback) { return global[rafPrefix + 'RequestAnimationFrame'](function () { callback(pnow()); }); }; global.cancelAnimationFrame = global[rafPrefix + 'CancelAnimationFrame']; } else { var lastTime = Date.now(); global.requestAnimationFrame = function (callback) { if (typeof callback !== 'function') { throw new TypeError(callback + ' is not a function'); } var currentTime = Date.now(), delay = 16 + lastTime - currentTime; if (delay performance.now(); if (futureRafTime) { rafTime = rafTime - (activeFrameTime * 2); } // Calculate the frame rate. var nextFrameTime = rafTime - frameDeadline + activeFrameTime; if (nextFrameTime 0) { var callbackObject = timedOutCallbacks.shift(); runCallback(callbackObject); } // While there is deadline time remaining, run remaining scheduled // callbacks. while (scheduledCallbacks.length > 0 && timeRemaining() > 0) { callbackObject = scheduledCallbacks.shift(); runCallback(callbackObject); } // Schedule callbacks added during this idle period to run in the next // idle period (nested callbacks). if (nestedCallbacks.length > 0) { scheduledCallbacks = scheduledCallbacks.concat(nestedCallbacks); nestedCallbacks = []; } // Schedule any remaining callbacks for a future idle period. if (scheduledCallbacks.length > 0) { scheduleAnimationFrame(); } isCallbackRunning = false; } /** * @param {function} callback * @return {number} - The idle callback identifier. */ global.requestIdleCallback = function requestIdleCallback(callback, options) { var id = ++idleCallbackIdentifier; // Create an object to store the callback, its options, and the time it // was added. var callbackObject = { id: id, callback: callback, options: options || {}, added: performance.now() }; // If an idle callback is running already this is a nested idle callback // and should be scheduled for a different period. If no idle callback // is running schedule immediately. if (isCallbackRunning) { nestedCallbacks.push(callbackObject); } else { scheduledCallbacks.push(callbackObject); } // Run scheduled idle callbacks after the next animation frame. scheduleAnimationFrame(); // Return the callbacks identifier. return id; }; /** * @param {number} - The idle callback identifier to cancel. * @return {undefined} */ global.cancelIdleCallback = function cancelIdleCallback(id) { if(arguments.length === 0) { throw new TypeError('cancelIdleCallback requires at least 1 argument'); } var callbackFilter = function (callbackObject) { return callbackObject.id !== id; }; // Find and remove the callback from the scheduled idle callbacks, // and nested callbacks (cancelIdleCallback may be called in an idle period). scheduledCallbacks = scheduledCallbacks.filter(callbackFilter); nestedCallbacks = nestedCallbacks.filter(callbackFilter); }; /** IdleDeadline Polyfill * @example * requestIdleCallback(function (deadline) { * console.log(deadline instanceof IdleDeadline); // true * }); */ global.IdleDeadline = function IdleDeadline() { if (!allowIdleDeadlineConstructor) { throw new TypeError('Illegal constructor'); } }; Object.defineProperty(global.IdleDeadline.prototype, 'timeRemaining', { value: function() { throw new TypeError('Illegal invocation'); } }); if (Object.prototype.hasOwnProperty.call(Object.prototype, '__defineGetter__')) { Object.defineProperty(global.IdleDeadline.prototype, 'didTimeout', { get: function () { throw new TypeError('Illegal invocation'); } }); } else { Object.defineProperty(global.IdleDeadline.prototype, 'didTimeout', { value: undefined }); } }(self)); } if (!("fromCodePoint"in String&&1===String.fromCodePoint.length )) { // String.fromCodePoint /* global CreateMethodProperty, IsArray, SameValue, ToInteger, ToNumber, UTF16Encoding */ // 21.1.2.2. String.fromCodePoint ( ...codePoints ) CreateMethodProperty(String, 'fromCodePoint', function fromCodePoint(_) { // Polyfill.io - List to store the characters whilst iterating over the code points. var result = []; // 1. Let codePoints be a List containing the arguments passed to this function. var codePoints = arguments; // 2. Let length be the number of elements in codePoints. var length = arguments.length; // 3. Let elements be a new empty List. var elements = []; // 4. Let nextIndex be 0. var nextIndex = 0; // 5. Repeat, while nextIndex 0x10FFFF, throw a RangeError exception. if (nextCP 0x10FFFF) { throw new RangeError('Invalid code point ' + Object.prototype.toString.call(nextCP)); } // e. Append the elements of the UTF16Encoding of nextCP to the end of elements. // Polyfill.io - UTF16Encoding can return a single codepoint or a list of multiple codepoints. var cp = UTF16Encoding(nextCP); if (IsArray(cp)) { elements = elements.concat(cp); } else { elements.push(cp); } // f. Let nextIndex be nextIndex + 1. nextIndex = nextIndex + 1; // Polyfill.io - Retrieving the characters whilst iterating enables the function to work in a memory efficient and performant way. result.push(String.fromCharCode.apply(null, elements)); } // 6. Return the String value whose elements are, in order, the elements in the List elements. If length is 0, the empty string is returned. return length === 0 ? '' : result.join(''); }); } if (!("at"in String.prototype )) { // String.prototype.at /* global CreateMethodProperty, RequireObjectCoercible, ToIntegerOrInfinity, ToString */ // 22.1.3.1. String.prototype.at ( index ) CreateMethodProperty(String.prototype, 'at', function at(index) { // 1. Let O be ? RequireObjectCoercible(this value). var O = RequireObjectCoercible(this); // 2. Let S be ? ToString(O). var S = ToString(O); // 3. Let len be the length of S. var len = S.length; // 4. Let relativeIndex be ? ToIntegerOrInfinity(index). var relativeIndex = ToIntegerOrInfinity(index); // 5. If relativeIndex ≥ 0, then // 5.a. Let k be relativeIndex. // 6. Else, // 6.a. Let k be len + relativeIndex. var k = relativeIndex >= 0 ? relativeIndex : len + relativeIndex; // 7. If k = len) return undefined; // 8. Return the substring of S from k to k + 1. return S.substring(k, k + 1); }); } if (!("codePointAt"in String.prototype )) { // String.prototype.codePointAt /* global CreateMethodProperty, RequireObjectCoercible, ToInteger, ToString, UTF16Decode */ // 21.1.3.3. String.prototype.codePointAt ( pos ) CreateMethodProperty(String.prototype, 'codePointAt', function codePointAt(pos) { // 1. Let O be ? RequireObjectCoercible(this value). var O = RequireObjectCoercible(this); // 2. Let S be ? ToString(O). var S = ToString(O); // 3. Let position be ? ToInteger(pos). var position = ToInteger(pos); // 4. Let size be the length of S. var size = S.length; // 5. If position = size) { return undefined; } // 6. Let first be the numeric value of the code unit at index position within the String S. var first = String.prototype.charCodeAt.call(S, position); // 7. If first 0xDBFF or position+1 = size, return first. if (first 0xDBFF || position + 1 === size) { return first; } // 8. Let second be the numeric value of the code unit at index position+1 within the String S. var second = String.prototype.charCodeAt.call(S, position + 1); // 9. If second 0xDFFF, return first. if (second 0xDFFF) { return first; } // 10. Return UTF16Decode(first, second). // 21.1.3.3.10 Return UTF16Decode(first, second). return UTF16Decode(first, second); }); } // _ESAbstract.AdvanceStringIndex /* global */ // 22.2.5.2.3 AdvanceStringIndex ( S, index, unicode ) function AdvanceStringIndex(S, index, unicode) { // eslint-disable-line no-unused-vars // 1. Assert: index ≤ 253 - 1. if (index > Number.MAX_SAFE_INTEGER) { throw new TypeError('Assertion failed: `index` must be = length) { return index + 1; } // 5. Let cp be ! CodePointAt(S, index). var cp = S.codePointAt(index); // 6. Return index + cp.[[CodeUnitCount]]. return index + cp.length; } if (!("endsWith"in String.prototype )) { // String.prototype.endsWith /* global CreateMethodProperty, IsRegExp, RequireObjectCoercible, ToInteger, ToString */ // 21.1.3.6. String.prototype.endsWith ( searchString [ , endPosition ] ) CreateMethodProperty(String.prototype, 'endsWith', function endsWith(searchString /* [ , endPosition ] */) { 'use strict'; var endPosition = arguments.length > 1 ? arguments[1] : undefined; // 1. Let O be ? RequireObjectCoercible(this value). var O = RequireObjectCoercible(this); // 2. Let S be ? ToString(O). var S = ToString(O); // 3. Let isRegExp be ? IsRegExp(searchString). var isRegExp = IsRegExp(searchString); // 4. If isRegExp is true, throw a TypeError exception. if (isRegExp) { throw new TypeError('First argument to String.prototype.endsWith must not be a regular expression'); } // 5. Let searchStr be ? ToString(searchString). var searchStr = ToString(searchString); // 6. Let len be the length of S. var len = S.length; // 7. If endPosition is undefined, let pos be len, else let pos be ? ToInteger(endPosition). var pos = endPosition === undefined ? len : ToInteger(endPosition); // 8. Let end be min(max(pos, 0), len). var end = Math.min(Math.max(pos, 0), len); // 9. Let searchLength be the length of searchStr. var searchLength = searchStr.length; // 10. Let start be end - searchLength. var start = end - searchLength; // 11. If start is less than 0, return false. if (start 1 ? arguments[1] : undefined; // 1. Let O be ? RequireObjectCoercible(this value). var O = RequireObjectCoercible(this); // 2. Let S be ? ToString(O). var S = ToString(O); // 3. Let isRegExp be ? IsRegExp(searchString). var isRegExp = IsRegExp(searchString); // 4. If isRegExp is true, throw a TypeError exception. if (isRegExp) { throw new TypeError('First argument to String.prototype.includes must not be a regular expression'); } // 5. Let searchStr be ? ToString(searchString). var searchStr = ToString(searchString); // 6. Let pos be ? ToInteger(position). (If position is undefined, this step produces the value 0.) var pos = ToInteger(position); // 7. Let len be the length of S. var len = S.length; // 8. Let start be min(max(pos, 0), len). var start = Math.min(Math.max(pos, 0), len); // 9. Let searchLen be the length of searchStr. // var searchLength = searchStr.length; // 10. If there exists any integer k not smaller than start such that k + searchLen is not greater than len, and for all nonnegative integers j less than searchLen, the code unit at index k+j within S is the same as the code unit at index j within searchStr, return true; but if there is no such integer k, return false. return String.prototype.indexOf.call(S, searchStr, start) !== -1; }); } if (!("padEnd"in String.prototype )) { // String.prototype.padEnd /* global CreateMethodProperty, RequireObjectCoercible, ToLength, ToString */ // 21.1.3.13. String.prototype.padEnd( maxLength [ , fillString ] ) CreateMethodProperty(String.prototype, 'padEnd', function padEnd(maxLength /* [ , fillString ] */) { 'use strict'; var fillString = arguments.length > 1 ? arguments[1] : undefined; // 1. Let O be ? RequireObjectCoercible(this value). var O = RequireObjectCoercible(this); // 2. Let S be ? ToString(O). var S = ToString(O); // 3. Let intMaxLength be ? ToLength(maxLength). var intMaxLength = ToLength(maxLength); // 4. Let stringLength be the length of S. var stringLength = S.length; // 5. If intMaxLength is not greater than stringLength, return S. if (intMaxLength 1 ? arguments[1] : undefined; // 1. Let O be ? RequireObjectCoercible(this value). var O = RequireObjectCoercible(this); // 2. Let S be ? ToString(O). var S = ToString(O); // 3. Let intMaxLength be ? ToLength(maxLength). var intMaxLength = ToLength(maxLength); // 4. Let stringLength be the length of S. var stringLength = S.length; // 5. If intMaxLength is not greater than stringLength, return S. if (intMaxLength 1 ? arguments[1] : undefined; // 1. Let O be ? RequireObjectCoercible(this value). var O = RequireObjectCoercible(this); // 2. Let S be ? ToString(O). var S = ToString(O); // 3. Let isRegExp be ? IsRegExp(searchString). var isRegExp = IsRegExp(searchString); // 4. If isRegExp is true, throw a TypeError exception. if (isRegExp) { throw new TypeError('First argument to String.prototype.startsWith must not be a regular expression'); } // 5. Let searchStr be ? ToString(searchString). var searchStr = ToString(searchString); // 6. Let pos be ? ToInteger(position). (If position is undefined, this step produces the value 0.) var pos = ToInteger(position); // 7. Let len be the length of S. var len = S.length; // 8. Let start be min(max(pos, 0), len). var start = Math.min(Math.max(pos, 0), len); // 9. Let searchLength be the length of searchStr. var searchLength = searchStr.length; // 10. If searchLength+start is greater than len, return false. if (searchLength + start > len) { return false; } // 11. If the sequence of elements of S starting at start of length searchLength is the same as the full element sequence of searchStr, return true. if (S.substr(start).indexOf(searchString) === 0) { return true; } // 12. Otherwise, return false. return false; }); } if (!("trim"in String.prototype&&function(){var r="​᠎" return!"\t\n\v\f\r \u2028\u2029\ufeff".trim()&&r.trim()===r}() )) { // String.prototype.trim /* global CreateMethodProperty, TrimString */ // 21.1.3.27. String.prototype.trim ( ) CreateMethodProperty(String.prototype, 'trim', function trim() { 'use strict'; // Let S be this value. var S = this; // Return ? TrimString(S, "start+end"). return TrimString(S, "start+end"); }); } if (!("parseFloat"in Number&&1/parseFloat("\t\n\v\f\r \u2028\u2029\ufeff-0")==-1/0 )) { // Number.parseFloat /* global CreateMethodProperty */ (function (nativeparseFloat, global) { // Polyfill.io - parseFloat is incorrect in older browsers var parseFloat = function parseFloat(str) { var string = String(str).trim(); var result = nativeparseFloat(string); return result === 0 && string.charAt(0) == '-' ? -0 : result; } CreateMethodProperty(global, 'parseFloat', parseFloat); // 20.1.2.12. Number.parseFloat ( string ) // The value of the Number.parseFloat data property is the same built-in function object that is the value of the parseFloat property of the global object defined in 18.2.4. CreateMethodProperty(Number, 'parseFloat', global.parseFloat); }(parseFloat, this)); } if (!("parseInt"in Number&&8===Number.parseInt("08") )) { // Number.parseInt /* global CreateMethodProperty */ (function (nativeParseInt, global) { // Polyfill.io - parseInt is incorrect in older browsers var parseInt = function parseInt(str, radix) { var string = String(str).trim(); return nativeParseInt(string, (radix >>> 0) || (/^[-+]?0[xX]/.test(string) ? 16 : 10)); } CreateMethodProperty(global, 'parseInt', parseInt); // 20.1.2.13. Number.parseInt ( string, radix ) // The value of the Number.parseInt data property is the same built-in function object that is the value of the parseInt property of the global object defined in 18.2.5. CreateMethodProperty(Number, 'parseInt', global.parseInt); }(parseInt, this)); } if (!("trimEnd"in String.prototype&&function(){var n="​᠎" return!"\t\n\v\f\r \u2028\u2029\ufeff".trimEnd()&&n.trimEnd()===n}() )) { // String.prototype.trimEnd /* global CreateMethodProperty, TrimString */ // 21.1.3.28 String.prototype.trimEnd ( ) CreateMethodProperty(String.prototype, 'trimEnd', function trimEnd() { 'use strict'; // 1. Let S be this value. var S = this; // 2. Return ? TrimString(S, "end"). return TrimString(S, "end"); }); } if (!("trimStart"in String.prototype&&function(){var t="​᠎" return!"\t\n\v\f\r \u2028\u2029\ufeff".trimStart()&&t.trimStart()===t}() )) { // String.prototype.trimStart /* global CreateMethodProperty, TrimString */ // 21.1.3.29 String.prototype.trimStart ( ) CreateMethodProperty(String.prototype, 'trimStart', function trimStart() { 'use strict'; // 1. Let S be this value. var S = this; // 2. Return ? TrimString(S, "start"). return TrimString(S, "start"); }); } if (!("Symbol"in self&&0===self.Symbol.length )) { // Symbol // A modification of https://github.com/WebReflection/get-own-property-symbols // (C) Andrea Giammarchi - MIT Licensed /* global Type */ (function (Object, GOPS, global) { 'use strict'; //so that ({}).toString.call(null) returns the correct [object Null] rather than [object Window] var setDescriptor; var id = 0; var random = '' + Math.random(); var prefix = '__\x01symbol:'; var prefixLength = prefix.length; var internalSymbol = '__\x01symbol@@' + random; var emptySymbolLookup = {}; var DP = 'defineProperty'; var DPies = 'defineProperties'; var GOPN = 'getOwnPropertyNames'; var GOPD = 'getOwnPropertyDescriptor'; var PIE = 'propertyIsEnumerable'; var ObjectProto = Object.prototype; var hOP = ObjectProto.hasOwnProperty; var pIE = ObjectProto[PIE]; var toString = ObjectProto.toString; var concat = Array.prototype.concat; var cachedWindowNames = Object.getOwnPropertyNames ? Object.getOwnPropertyNames(self) : []; var nGOPN = Object[GOPN]; var gOPN = function getOwnPropertyNames (obj) { if (toString.call(obj) === '[object Window]') { try { return nGOPN(obj); } catch (e) { // IE bug where layout engine calls userland gOPN for cross-domain `window` objects return concat.call([], cachedWindowNames); } } return nGOPN(obj); }; var gOPD = Object[GOPD]; var objectCreate = Object.create; var objectKeys = Object.keys; var freeze = Object.freeze || Object; var objectDefineProperty = Object[DP]; var $defineProperties = Object[DPies]; var descriptor = gOPD(Object, GOPN); var addInternalIfNeeded = function (o, uid, enumerable) { if (!hOP.call(o, internalSymbol)) { try { objectDefineProperty(o, internalSymbol, { enumerable: false, configurable: false, writable: false, value: {} }); } catch (e) { o[internalSymbol] = {}; } } o[internalSymbol]['@@' + uid] = enumerable; }; var createWithSymbols = function (proto, descriptors) { var self = objectCreate(proto); gOPN(descriptors).forEach(function (key) { if (propertyIsEnumerable.call(descriptors, key)) { $defineProperty(self, key, descriptors[key]); } }); return self; }; var copyAsNonEnumerable = function (descriptor) { var newDescriptor = objectCreate(descriptor); newDescriptor.enumerable = false; return newDescriptor; }; var get = function get(){}; var onlyNonSymbols = function (name) { return name != internalSymbol && !hOP.call(source, name); }; var onlySymbols = function (name) { return name != internalSymbol && hOP.call(source, name); }; var propertyIsEnumerable = function propertyIsEnumerable(key) { var uid = '' + key; return onlySymbols(uid) ? ( hOP.call(this, uid) && this[internalSymbol] && this[internalSymbol]['@@' + uid] ) : pIE.call(this, key); }; var setAndGetSymbol = function (uid) { var descriptor = { enumerable: false, configurable: true, get: get, set: function (value) { setDescriptor(this, uid, { enumerable: false, configurable: true, writable: true, value: value }); addInternalIfNeeded(this, uid, true); } }; try { objectDefineProperty(ObjectProto, uid, descriptor); } catch (e) { ObjectProto[uid] = descriptor.value; } source[uid] = objectDefineProperty( Object(uid), 'constructor', sourceConstructor ); var description = gOPD(Symbol.prototype, 'description'); if (description) { objectDefineProperty( source[uid], 'description', description ); } return freeze(source[uid]); }; var symbolDescription = function (s) { var sym = thisSymbolValue(s); // 3. Return sym.[[Description]]. if (supportsInferredNames) { var name = getInferredName(sym); if (name !== "") { return name.slice(1, -1); // name.slice('['.length, -']'.length); } } if (emptySymbolLookup[sym] !== undefined) { return emptySymbolLookup[sym]; } var string = sym.toString(); var randomStartIndex = string.lastIndexOf("0."); string = string.slice(10, randomStartIndex); if (string === "") { return undefined; } return string; }; var Symbol = function Symbol() { var description = arguments[0]; if (this instanceof Symbol) { throw new TypeError('Symbol is not a constructor'); } var uid = prefix.concat(description || '', random, ++id); if (description !== undefined && (description === null || isNaN(description) || String(description) === "")) { emptySymbolLookup[uid] = String(description); } var that = setAndGetSymbol(uid); return that; }; var source = objectCreate(null); var sourceConstructor = {value: Symbol}; var sourceMap = function (uid) { return source[uid]; }; var $defineProperty = function defineProperty(o, key, descriptor) { var uid = '' + key; if (onlySymbols(uid)) { setDescriptor(o, uid, descriptor.enumerable ? copyAsNonEnumerable(descriptor) : descriptor); addInternalIfNeeded(o, uid, !!descriptor.enumerable); } else { objectDefineProperty(o, key, descriptor); } return o; }; var onlyInternalSymbols = function (obj) { return function (name) { return hOP.call(obj, internalSymbol) && hOP.call(obj[internalSymbol], '@@' + name); }; }; var $getOwnPropertySymbols = function getOwnPropertySymbols(o) { return gOPN(o).filter(o === ObjectProto ? onlyInternalSymbols(o) : onlySymbols).map(sourceMap); } ; descriptor.value = $defineProperty; objectDefineProperty(Object, DP, descriptor); descriptor.value = $getOwnPropertySymbols; objectDefineProperty(Object, GOPS, descriptor); descriptor.value = function getOwnPropertyNames(o) { return gOPN(o).filter(onlyNonSymbols); }; objectDefineProperty(Object, GOPN, descriptor); descriptor.value = function defineProperties(o, descriptors) { var symbols = $getOwnPropertySymbols(descriptors); if (symbols.length) { objectKeys(descriptors).concat(symbols).forEach(function (uid) { if (propertyIsEnumerable.call(descriptors, uid)) { $defineProperty(o, uid, descriptors[uid]); } }); } else { $defineProperties(o, descriptors); } return o; }; objectDefineProperty(Object, DPies, descriptor); descriptor.value = propertyIsEnumerable; objectDefineProperty(ObjectProto, PIE, descriptor); descriptor.value = Symbol; objectDefineProperty(global, 'Symbol', descriptor); // defining `Symbol.for(key)` descriptor.value = function (key) { var uid = prefix.concat(prefix, key, random); return uid in ObjectProto ? source[uid] : setAndGetSymbol(uid); }; objectDefineProperty(Symbol, 'for', descriptor); // defining `Symbol.keyFor(symbol)` descriptor.value = function (symbol) { if (onlyNonSymbols(symbol)) throw new TypeError(symbol + ' is not a symbol'); return hOP.call(source, symbol) ? symbol.slice(prefixLength * 2, -random.length) : void 0 ; }; objectDefineProperty(Symbol, 'keyFor', descriptor); descriptor.value = function getOwnPropertyDescriptor(o, key) { var descriptor = gOPD(o, key); if (descriptor && onlySymbols(key)) { descriptor.enumerable = propertyIsEnumerable.call(o, key); } return descriptor; }; objectDefineProperty(Object, GOPD, descriptor); descriptor.value = function create(proto, descriptors) { return arguments.length === 1 || typeof descriptors === "undefined" ? objectCreate(proto) : createWithSymbols(proto, descriptors); }; objectDefineProperty(Object, 'create', descriptor); var strictModeSupported = (function(){ 'use strict'; return this; }).call(null) === null; if (strictModeSupported) { descriptor.value = function () { var str = toString.call(this); return (str === '[object String]' && onlySymbols(this)) ? '[object Symbol]' : str; }; } else { descriptor.value = function () { // https://github.com/Financial-Times/polyfill-library/issues/164#issuecomment-486965300 // Polyfill.io this code is here for the situation where a browser does not // support strict mode and is executing `Object.prototype.toString.call(null)`. // This code ensures that we return the correct result in that situation however, // this code also introduces a bug where it will return the incorrect result for // `Object.prototype.toString.call(window)`. We can't have the correct result for // both `window` and `null`, so we have opted for `null` as we believe this is the more // common situation. if (this === window) { return '[object Null]'; } var str = toString.call(this); return (str === '[object String]' && onlySymbols(this)) ? '[object Symbol]' : str; }; } objectDefineProperty(ObjectProto, 'toString', descriptor); setDescriptor = function (o, key, descriptor) { var protoDescriptor = gOPD(ObjectProto, key); delete ObjectProto[key]; objectDefineProperty(o, key, descriptor); if (o !== ObjectProto) { objectDefineProperty(ObjectProto, key, protoDescriptor); } }; // The abstract operation thisSymbolValue(value) performs the following steps: function thisSymbolValue(value) { // 1. If Type(value) is Symbol, return value. if (Type(value) === "symbol") { return value; } // 2. If Type(value) is Object and value has a [[SymbolData]] internal slot, then // a. Let s be value.[[SymbolData]]. // b. Assert: Type(s) is Symbol. // c. Return s. // 3. Throw a TypeError exception. throw TypeError(value + " is not a symbol"); } // Symbol.prototype.description if (function () { // supports getters try { var a = {}; Object.defineProperty(a, "t", { configurable: true, enumerable: false, get: function() { return true; }, set: undefined }); return !!a.t; } catch (e) { return false; } }()) { var getInferredName; try { // eslint-disable-next-line no-new-func getInferredName = Function("s", "var v = s.valueOf(); return { [v]() {} }[v].name;"); // eslint-disable-next-line no-empty } catch (e) { } var inferred = function () { }; var supportsInferredNames = getInferredName && inferred.name === "inferred" ? getInferredName : null; // 19.4.3.2 get Symbol.prototype.description Object.defineProperty(global.Symbol.prototype, "description", { configurable: true, enumerable: false, get: function () { // 1. Let s be the this value. var s = this; return symbolDescription(s); } }); } }(Object, 'getOwnPropertySymbols', self)); } if (!(self.Reflect&&"ownKeys"in self.Reflect )) { // Reflect.ownKeys /* global CreateMethodProperty, Reflect, Type */ // 26.1.10 Reflect.ownKeys ( target ) CreateMethodProperty(Reflect, 'ownKeys', function ownKeys(target) { // 1. If Type(target) is not Object, throw a TypeError exception. if (Type(target) !== "object") { throw new TypeError(Object.prototype.toString.call(target) + ' is not an Object'); } // polyfill-library - These steps are taken care of by Object.getOwnPropertyNames. // 2. Let keys be ? target.[[OwnPropertyKeys]](). // 3. Return CreateArrayFromList(keys). return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)); }); } if (!("getOwnPropertyDescriptor"in Object&&"function"==typeof Object.getOwnPropertyDescriptor&&function(){try{var t={} return t.test=0,0===Object.getOwnPropertyDescriptors(t).test.value}catch(t){return!1}}() )) { // Object.getOwnPropertyDescriptors /* global CreateMethodProperty, Reflect, ToObject, CreateDataProperty */ // 19.1.2.9. Object.getOwnPropertyDescriptors ( O ) CreateMethodProperty( Object, 'getOwnPropertyDescriptors', function getOwnPropertyDescriptors(O) { // 1. Let obj be ? ToObject(O). var obj = ToObject(O); // 2. Let ownKeys be ? obj.[[OwnPropertyKeys]](). var ownKeys = Reflect.ownKeys(obj); // 3. Let descriptors be ! ObjectCreate(%ObjectPrototype%). var descriptors = {}; // 4. For each element key of ownKeys in List order, do var length = ownKeys.length; for (var i = 0; i 1 ? arguments[1] : GetMethod(obj, Symbol.iterator); // 2. Let iterator be ? Call(method, obj). var iterator = Call(method, obj); // 3. If Type(iterator) is not Object, throw a TypeError exception. if (Type(iterator) !== 'object') { throw new TypeError('bad iterator'); } // 4. Let nextMethod be ? GetV(iterator, "next"). var nextMethod = GetV(iterator, "next"); // 5. Let iteratorRecord be Record {[[Iterator]]: iterator, [[NextMethod]]: nextMethod, [[Done]]: false}. var iteratorRecord = Object.create(null); iteratorRecord['[[Iterator]]'] = iterator; iteratorRecord['[[NextMethod]]'] = nextMethod; iteratorRecord['[[Done]]'] = false; // 6. Return iteratorRecord. return iteratorRecord; } // _ESAbstract.AddEntriesFromIterable /* global IsCallable, GetIterator, IteratorStep, IteratorValue, IteratorClose, Get, Call, Type */ // eslint-disable-next-line no-unused-vars var AddEntriesFromIterable = (function() { var toString = {}.toString; var split = "".split; // 23.1.1.2 AddEntriesFromIterable ( target, iterable, adder ) return function AddEntriesFromIterable(target, iterable, adder) { // 1. If IsCallable(adder) is false, throw a TypeError exception. if (IsCallable(adder) === false) { throw new TypeError("adder is not callable."); } // 2. Assert: iterable is present, and is neither undefined nor null. // 3. Let iteratorRecord be ? GetIterator(iterable). var iteratorRecord = GetIterator(iterable); // 4. Repeat, // eslint-disable-next-line no-constant-condition while (true) { // a. Let next be ? IteratorStep(iteratorRecord). var next = IteratorStep(iteratorRecord); // b. If next is false, return target. if (next === false) { return target; } // c. Let nextItem be ? IteratorValue(next). var nextItem = IteratorValue(next); // d. If Type(nextItem) is not Object, then if (Type(nextItem) !== "object") { // i. Let error be ThrowCompletion(a newly created TypeError object). var error = new TypeError("nextItem is not an object"); // ii. Return ? IteratorClose(iteratorRecord, error). IteratorClose(iteratorRecord, error); throw error; } // Polyfill.io fallback for non-array-like strings which exist in some ES3 user-agents nextItem = (Type(nextItem) === "string" || nextItem instanceof String) && toString.call(nextItem) == "[object String]" ? split.call(nextItem, "") : nextItem; var k; try { // e. Let k be Get(nextItem, "0"). k = Get(nextItem, "0"); // eslint-disable-next-line no-catch-shadow } catch (k) { // f. If k is an abrupt completion, return ? IteratorClose(iteratorRecord, k). return IteratorClose(iteratorRecord, k); } var v; try { // g. Let v be Get(nextItem, "1"). v = Get(nextItem, "1"); // eslint-disable-next-line no-catch-shadow } catch (v) { // h. If v is an abrupt completion, return ? IteratorClose(iteratorRecord, v). return IteratorClose(iteratorRecord, v); } try { // i. Let status be Call(adder, target, « k.[[Value]], v.[[Value]] »). Call(adder, target, [k, v]); // eslint-disable-next-line no-catch-shadow } catch (status) { // j. If status is an abrupt completion, return ? IteratorClose(iteratorRecord, status). return IteratorClose(iteratorRecord, status); } } }; })(); // _ESAbstract.IterableToList /* global GetIterator, IteratorStep, IteratorValue */ // 7.4.11 IterableToList ( items [ , method ] ) function IterableToList(items /*, method */) { // eslint-disable-line no-unused-vars // 1. If method is present, then // 1.a. Let iteratorRecord be ? GetIterator(items, sync, method). // 2. Else, // 2.a. Let iteratorRecord be ? GetIterator(items, sync). var iteratorRecord = arguments.length > 1 ? GetIterator(items, arguments[1]) : GetIterator(items); // 3. Let values be a new empty List. var values = []; // 4. Let next be true. var next = true; // 5. Repeat, while next is not false, while (next !== false) { // 5.a. Set next to ? IteratorStep(iteratorRecord). next = IteratorStep(iteratorRecord); // 5.b. If next is not false, then if (next !== false) { // 5.b.i. Let nextValue be ? IteratorValue(next). var nextValue = IteratorValue(next); // 5.b.ii. Append nextValue to the end of the List values. values.push(nextValue); } } // 6. Return values. return values; } if (!("AggregateError"in self )) { // AggregateError /* global _ErrorConstructor, CreateDataPropertyOrThrow, CreateMethodProperty, IterableToList */ (function () { var hasErrorCause = (function () { try { return new Error('m', { cause: 'c' }).cause === 'c'; } catch (e) { return false; } })(); function AggregateError (errors, message) { if (!(this instanceof AggregateError)) return new AggregateError(errors, message); var temp = typeof message === 'undefined' ? new Error() : new Error(message); CreateDataPropertyOrThrow(this, 'name', 'AggregateError'); CreateDataPropertyOrThrow(this, 'message', temp.message); CreateDataPropertyOrThrow(this, 'stack', temp.stack); var errorsList; if (Array.isArray(errors)) { errorsList = errors.slice(); } else { try { errorsList = IterableToList(errors); } catch (_error) { throw new TypeError('Argument is not iterable'); } } CreateDataPropertyOrThrow(this, 'errors', errorsList); } AggregateError.prototype = Object.create(Error.prototype); AggregateError.prototype.constructor = AggregateError; CreateMethodProperty(self, 'AggregateError', AggregateError); // If `Error.cause` is available, add it to `AggregateError` if (hasErrorCause) { CreateMethodProperty(self, 'AggregateError', _ErrorConstructor('AggregateError')); } })(); } if (!("Symbol"in self&&"match"in self.Symbol )) { // Symbol.match /* global Symbol */ Object.defineProperty(Symbol, 'match', { value: Symbol('match') }); } if (!("Symbol"in self&&"matchAll"in self.Symbol )) { // Symbol.matchAll /* global Symbol */ // 20.4.2.8 Symbol.matchAll Object.defineProperty(Symbol, 'matchAll', { value: Symbol('matchAll') }); } if (!("Symbol"in self&&"replace"in self.Symbol )) { // Symbol.replace /* global Symbol */ Object.defineProperty(Symbol, 'replace', { value: Symbol('replace') }); } if (!("replaceAll"in String.prototype )) { // String.prototype.replaceAll /* global CreateMethodProperty, RequireObjectCoercible, ToString, IsRegExp, Get, GetMethod, Call, IsCallable, StringIndexOf, GetSubstitution */ // 21.1.3.18 String.prototype.replaceAll ( searchValue, replaceValue ) CreateMethodProperty(String.prototype, 'replaceAll', function replaceAll(searchValue, replaceValue ) { 'use strict'; // 1. Let O be ? RequireObjectCoercible(this value). var O = RequireObjectCoercible(this); // 2. If searchValue is neither undefined nor null, then if (searchValue !== undefined && searchValue !== null) { // 2.a. Let isRegExp be ? IsRegExp(searchValue). var isRegExp = IsRegExp(searchValue); // 2.b. If isRegExp is true, then if (isRegExp) { // 2.b.i. Let flags be ? Get(searchValue, "flags"). var flags = Get(searchValue, "flags"); // IE doesn't have RegExp.prototype.flags support, it does have RegExp.prototype.global // 2.b.iii. If ? ToString(flags) does not contain "g", throw a TypeError exception. if (!('flags' in RegExp.prototype) && searchValue.global !== true) { throw TypeError(''); } else if ('flags' in RegExp.prototype) { // 2.b.ii. Perform ? RequireObjectCoercible(flags). RequireObjectCoercible(flags) // 2.b.iii. If ? ToString(flags) does not contain "g", throw a TypeError exception. if (ToString(flags).indexOf('g') === -1) { throw TypeError(''); } } } // 2.c. Let replacer be ? GetMethod(searchValue, @@replace). var replacer = 'Symbol' in self && 'replace' in self.Symbol ? GetMethod(searchValue, self.Symbol.replace) : undefined; // 2.d. If replacer is not undefined, then if (replacer !== undefined) { // 2.d.i. Return ? Call(replacer, searchValue, « O, replaceValue »). return Call(replacer, searchValue, [ O, replaceValue ]); } } // 3. Let string be ? ToString(O). var string = ToString(O); // 4. Let searchString be ? ToString(searchValue). var searchString = ToString(searchValue); // 5. Let functionalReplace be IsCallable(replaceValue). var functionalReplace = IsCallable(replaceValue); // 6. If functionalReplace is false, then if (functionalReplace === false) { // 6.a. Set replaceValue to ? ToString(replaceValue). replaceValue = ToString(replaceValue); } // 7. Let searchLength be the length of searchString. var searchLength = searchString.length; // 8. Let advanceBy be max(1, searchLength). var advanceBy = Math.max(1, searchLength); // 9. Let matchPositions be a new empty List. var matchPositions = []; // 10. Let position be ! StringIndexOf(string, searchString, 0). var position = StringIndexOf(string, searchString, 0); // 11. Repeat, while position is not -1, while (position !== -1) { // 11.a. Append position to the end of matchPositions. matchPositions.push(position); // 11.b. Set position to ! StringIndexOf(string, searchString, position + advanceBy). position = StringIndexOf(string, searchString, position + advanceBy); } // 12. Let endOfLastMatch be 0. var endOfLastMatch = 0; // 13. Let result be the empty String. var result = ''; // 14. For each element position of matchPositions, do for (var i = 0; i -1; // 11. If flags contains "u", let fullUnicode be true. // 12. Else, let fullUnicode be false. var fullUnicode = flags.indexOf('u') > -1; // 13. Return ! CreateRegExpStringIterator(matcher, S, global, fullUnicode). return CreateRegExpStringIterator(matcher, S, global, fullUnicode); }); } if (!("matchAll"in String.prototype )) { // String.prototype.matchAll /* global Call, CreateMethodProperty, Get, GetMethod, Invoke, IsRegExp, RequireObjectCoercible, ToString */ // 22.1.3.13 String.prototype.matchAll ( regexp ) CreateMethodProperty(String.prototype, 'matchAll', function matchAll(regexp) { 'use strict'; // 1. Let O be ? RequireObjectCoercible(this value). var O = RequireObjectCoercible(this); // 2. If regexp is neither undefined nor null, then if (regexp !== undefined && regexp !== null) { // 2.a. Let isRegExp be ? IsRegExp(regexp). var isRegExp = IsRegExp(regexp); // 2.b. If isRegExp is true, then if (isRegExp) { // 2.b.i. Let flags be ? Get(regexp, "flags"). var flags = Get(regexp, "flags"); // IE doesn't have RegExp.prototype.flags support, it does have RegExp.prototype.global // 2.b.iii. If ? ToString(flags) does not contain "g", throw a TypeError exception. if (!('flags' in RegExp.prototype) && regexp.global !== true) { throw TypeError(''); } else if ('flags' in RegExp.prototype) { // 2.b.ii. Perform ? RequireObjectCoercible(flags). RequireObjectCoercible(flags) // 2.b.iii. If ? ToString(flags) does not contain "g", throw a TypeError exception. if (ToString(flags).indexOf('g') === -1) { throw TypeError(''); } } } // 2.c. Let matcher be ? GetMethod(regexp, @@matchAll). var matcher = 'Symbol' in self && 'matchAll' in self.Symbol ? GetMethod(regexp, self.Symbol.matchAll) : undefined; // 2.d. If matcher is not undefined, then if (matcher !== undefined) { // 2.d.i. Return ? Call(matcher, regexp, « O »). return Call(matcher, regexp, [ O ]); } } // 3. Let S be ? ToString(O). var S = ToString(O); // 4. Let rx be ? RegExpCreate(regexp, "g"). var rx = new RegExp(regexp, 'g'); // 5. Return ? Invoke(rx, @@matchAll, « S »). return Invoke(rx, 'Symbol' in self && 'matchAll' in self.Symbol && self.Symbol.matchAll, [ S ]); }); } // _Iterator /* global Symbol */ // A modification of https://github.com/medikoo/es6-iterator // Copyright (C) 2013-2015 Mariusz Nowak (www.medikoo.com) var Iterator = (function () { // eslint-disable-line no-unused-vars var clear = function () { this.length = 0; return this; }; var callable = function (fn) { if (typeof fn !== 'function') throw new TypeError(fn + " is not a function"); return fn; }; var Iterator = function (list, context) { if (!(this instanceof Iterator)) { return new Iterator(list, context); } Object.defineProperties(this, { __list__: { writable: true, value: list }, __context__: { writable: true, value: context }, __nextIndex__: { writable: true, value: 0 } }); if (!context) return; callable(context.on); context.on('_add', this._onAdd.bind(this)); context.on('_delete', this._onDelete.bind(this)); context.on('_clear', this._onClear.bind(this)); }; Object.defineProperties(Iterator.prototype, Object.assign({ constructor: { value: Iterator, configurable: true, enumerable: false, writable: true }, _next: { value: function () { var i; if (!this.__list__) return; if (this.__redo__) { i = this.__redo__.shift(); if (i !== undefined) return i; } if (this.__nextIndex__ = this.__nextIndex__) return; ++this.__nextIndex__; if (!this.__redo__) { Object.defineProperty(this, '__redo__', { value: [index], configurable: true, enumerable: false, writable: false }); return; } this.__redo__.forEach(function (redo, i) { if (redo >= index) this.__redo__[i] = ++redo; }, this); this.__redo__.push(index); }, configurable: true, enumerable: false, writable: true }, _onDelete: { value: function (index) { var i; if (index >= this.__nextIndex__) return; --this.__nextIndex__; if (!this.__redo__) return; i = this.__redo__.indexOf(index); if (i !== -1) this.__redo__.splice(i, 1); this.__redo__.forEach(function (redo, i) { if (redo > index) this.__redo__[i] = --redo; }, this); }, configurable: true, enumerable: false, writable: true }, _onClear: { value: function () { if (this.__redo__) clear.call(this.__redo__); this.__nextIndex__ = 0; }, configurable: true, enumerable: false, writable: true } })); Object.defineProperty(Iterator.prototype, Symbol.iterator, { value: function () { return this; }, configurable: true, enumerable: false, writable: true }); Object.defineProperty(Iterator.prototype, Symbol.toStringTag, { value: 'Iterator', configurable: false, enumerable: false, writable: true }); return Iterator; }()); // _ArrayIterator /* global Iterator, Symbol */ // A modification of https://github.com/medikoo/es6-iterator // Copyright (C) 2013-2015 Mariusz Nowak (www.medikoo.com) var ArrayIterator = (function() { // eslint-disable-line no-unused-vars var ArrayIterator = function(arr, kind) { if (!(this instanceof ArrayIterator)) return new ArrayIterator(arr, kind); Iterator.call(this, arr); if (!kind) kind = 'value'; else if (String.prototype.includes.call(kind, 'key+value')) kind = 'key+value'; else if (String.prototype.includes.call(kind, 'key')) kind = 'key'; else kind = 'value'; Object.defineProperty(this, '__kind__', { value: kind, configurable: false, enumerable: false, writable: false }); }; if (Object.setPrototypeOf) Object.setPrototypeOf(ArrayIterator, Iterator.prototype); ArrayIterator.prototype = Object.create(Iterator.prototype, { constructor: { value: ArrayIterator, configurable: true, enumerable: false, writable: true }, _resolve: { value: function(i) { if (this.__kind__ === 'value') return this.__list__[i]; if (this.__kind__ === 'key+value') return [i, this.__list__[i]]; return i; }, configurable: true, enumerable: false, writable: true }, toString: { value: function() { return '[object Array Iterator]'; }, configurable: true, enumerable: false, writable: true } }); Object.defineProperty(ArrayIterator.prototype, Symbol.toStringTag, { value: 'Array Iterator', writable: false, enumerable: false, configurable: true }); return ArrayIterator; }()); if (!("Symbol"in self&&"iterator"in self.Symbol&&!!Array.prototype.entries )) { // Array.prototype.entries /* global CreateMethodProperty, ToObject, ArrayIterator */ // 22.1.3.4. Array.prototype.entries ( ) CreateMethodProperty(Array.prototype, 'entries', function entries() { // 1. Let O be ? ToObject(this value). var O = ToObject(this); // 2. Return CreateArrayIterator(O, "key+value"). // TODO: Add CreateArrayIterator return new ArrayIterator(O, 'key+value'); }); } if (!("Symbol"in self&&"iterator"in self.Symbol&&!!Array.prototype.keys )) { // Array.prototype.keys /* global CreateMethodProperty, ToObject, ArrayIterator */ // 22.1.3.14. Array.prototype.keys ( ) CreateMethodProperty(Array.prototype, 'keys', function keys() { // 1. Let O be ? ToObject(this value). var O = ToObject(this); // 2. Return CreateArrayIterator(O, "key"). // TODO: Add CreateArrayIterator. return new ArrayIterator(O, 'key'); }); } if (!("values"in Array.prototype )) { // Array.prototype.values /* global CreateMethodProperty, Symbol, ToObject, ArrayIterator */ // 22.1.3.30/ Array.prototype.values ( ) // Polyfill.io - Firefox, Chrome and Opera have Array.prototype[Symbol.iterator], which is the exact same function as Array.prototype.values. if ('Symbol' in self && 'iterator' in Symbol && typeof Array.prototype[Symbol.iterator] === 'function') { CreateMethodProperty(Array.prototype, 'values', Array.prototype[Symbol.iterator]); } else { CreateMethodProperty(Array.prototype, 'values', function values () { // 1. Let O be ? ToObject(this value). var O = ToObject(this); // 2. Return CreateArrayIterator(O, "value"). // TODO: Add CreateArrayIterator return new ArrayIterator(O, 'value'); }); } } // _StringIterator // A modification of https://github.com/medikoo/es6-iterator // Copyright (C) 2013-2015 Mariusz Nowak (www.medikoo.com) /* global Iterator, Symbol */ var StringIterator = (function() { // eslint-disable-line no-unused-vars var StringIterator = function (str) { if (!(this instanceof StringIterator)) return new StringIterator(str); str = String(str); Iterator.call(this, str); Object.defineProperty(this, '__length__', { value: str.length, configurable: false, enumerable: false, writable: false }); }; if (Object.setPrototypeOf) Object.setPrototypeOf(StringIterator, Iterator); StringIterator.prototype = Object.create(Iterator.prototype, { constructor: { value: StringIterator, configurable: true, enumerable: false, writable: true }, _next: { value: function() { if (!this.__list__) return; if (this.__nextIndex__ = 0xD800) && (code 0 ? arguments[0] : undefined; // 5. If iterable is either undefined or null, return map. if (iterable === null || iterable === undefined) { return map; } // 6. Let adder be ? Get(map, "set"). var adder = map.set; // 7. If IsCallable(adder) is false, throw a TypeError exception. if (!IsCallable(adder)) { throw new TypeError("Map.prototype.set is not a function"); } // 8. Let iteratorRecord be ? GetIterator(iterable). try { var iteratorRecord = GetIterator(iterable); // 9. Repeat, // eslint-disable-next-line no-constant-condition while (true) { // a. Let next be ? IteratorStep(iteratorRecord). var next = IteratorStep(iteratorRecord); // b. If next is false, return map. if (next === false) { return map; } // c. Let nextItem be ? IteratorValue(next). var nextItem = IteratorValue(next); // d. If Type(nextItem) is not Object, then if (Type(nextItem) !== 'object') { // i. Let error be Completion{[[Type]]: throw, [[Value]]: a newly created TypeError object, [[Target]]: empty}. try { throw new TypeError('Iterator value ' + nextItem + ' is not an entry object'); } catch (error) { // ii. Return ? IteratorClose(iteratorRecord, error). return IteratorClose(iteratorRecord, error); } } try { // Polyfill.io - The try catch accounts for steps: f, h, and j. // e. Let k be Get(nextItem, "0"). var k = nextItem[0]; // f. If k is an abrupt completion, return ? IteratorClose(iteratorRecord, k). // g. Let v be Get(nextItem, "1"). var v = nextItem[1]; // h. If v is an abrupt completion, return ? IteratorClose(iteratorRecord, v). // i. Let status be Call(adder, map, « k.[[Value]], v.[[Value]] »). adder.call(map, k, v); } catch (e) { // j. If status is an abrupt completion, return ? IteratorClose(iteratorRecord, status). return IteratorClose(iteratorRecord, e); } } } catch (e) { // Polyfill.io - For user agents which do not have iteration methods on argument objects or arrays, we can special case those. if (Array.isArray(iterable) || Object.prototype.toString.call(iterable) === '[object Arguments]') { var index; var length = iterable.length; for (index = 0; index { * console.log(v); * }); * ``` */ then: function (onFulfilled, onRejected) { if (this._s === undefined) throw genTypeError(); return addHandler( this, newCapablePromise(Yaku.speciesConstructor(this, Yaku)), onFulfilled, onRejected ); }, /** * The `catch()` method returns a Promise and deals with rejected cases only. * It behaves the same as calling `Promise.prototype.then(undefined, onRejected)`. * @param {Function} onRejected A Function called when the Promise is rejected. * This function has one argument, the rejection reason. * @return {Yaku} A Promise that deals with rejected cases only. * @example * ```js * var Promise = require('yaku'); * var p = Promise.reject(new Error("ERR")); * * p['catch']((v) => { * console.log(v); * }); * ``` */ 'catch': function (onRejected) { return this.then($undefined, onRejected); }, /** * Register a callback to be invoked when a promise is settled (either fulfilled or rejected). * Similar with the try-catch-finally, it's often used for cleanup. * @param {Function} onFinally A Function called when the Promise is settled. * It will not receive any argument. * @return {Yaku} A Promise that will reject if onFinally throws an error or returns a rejected promise. * Else it will resolve previous promise's final state (either fulfilled or rejected). * @example * ```js * var Promise = require('yaku'); * var p = Math.random() > 0.5 ? Promise.resolve() : Promise.reject(); * p.finally(() => { * console.log('finally'); * }); * ``` */ 'finally': function (onFinally) { return this.then(function (val) { return Yaku.resolve(onFinally()).then(function () { return val; }); }, function (err) { return Yaku.resolve(onFinally()).then(function () { throw err; }); }); }, // The number of current promises that attach to this Yaku instance. _c: 0, // The parent Yaku. _p: $null }); /** * The `Promise.resolve(value)` method returns a Promise object that is resolved with the given value. * If the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable, * adopting its eventual state; otherwise the returned promise will be fulfilled with the value. * @param {Any} value Argument to be resolved by this Promise. * Can also be a Promise or a thenable to resolve. * @return {Yaku} * @example * ```js * var Promise = require('yaku'); * var p = Promise.resolve(10); * ``` */ Yaku.resolve = function (val) { return isYaku(val) ? val : settleWithX(newCapablePromise(this), val); }; /** * The `Promise.reject(reason)` method returns a Promise object that is rejected with the given reason. * @param {Any} reason Reason why this Promise rejected. * @return {Yaku} * @example * ```js * var Promise = require('yaku'); * var p = Promise.reject(new Error("ERR")); * ``` */ Yaku.reject = function (reason) { return settlePromise(newCapablePromise(this), $rejected, reason); }; /** * The `Promise.race(iterable)` method returns a promise that resolves or rejects * as soon as one of the promises in the iterable resolves or rejects, * with the value or reason from that promise. * @param {iterable} iterable An iterable object, such as an Array. * @return {Yaku} The race function returns a Promise that is settled * the same way as the first passed promise to settle. * It resolves or rejects, whichever happens first. * @example * ```js * var Promise = require('yaku'); * Promise.race([ * 123, * Promise.resolve(0) * ]) * .then((value) => { * console.log(value); // => 123 * }); * ``` */ Yaku.race = function (iterable) { var self = this , p = newCapablePromise(self) , resolve = function (val) { settlePromise(p, $resolved, val); } , reject = function (val) { settlePromise(p, $rejected, val); } , ret = genTryCatcher(each)(iterable, function (v) { self.resolve(v).then(resolve, reject); }); if (ret === $tryErr) return self.reject(ret.e); return p; }; /** * The `Promise.all(iterable)` method returns a promise that resolves when * all of the promises in the iterable argument have resolved. * * The result is passed as an array of values from all the promises. * If something passed in the iterable array is not a promise, * it's converted to one by Promise.resolve. If any of the passed in promises rejects, * the all Promise immediately rejects with the value of the promise that rejected, * discarding all the other promises whether or not they have resolved. * @param {iterable} iterable An iterable object, such as an Array. * @return {Yaku} * @example * ```js * var Promise = require('yaku'); * Promise.all([ * 123, * Promise.resolve(0) * ]) * .then((values) => { * console.log(values); // => [123, 0] * }); * ``` * @example * Use with iterable. * ```js * var Promise = require('yaku'); * Promise.all((function * () { * yield 10; * yield new Promise(function (r) { setTimeout(r, 1000, "OK") }); * })()) * .then((values) => { * console.log(values); // => [123, 0] * }); * ``` */ Yaku.all = function (iterable) { var self = this , p1 = newCapablePromise(self) , res = [] , ret ; function reject (reason) { settlePromise(p1, $rejected, reason); } ret = genTryCatcher(each)(iterable, function (item, i) { self.resolve(item).then(function (value) { res[i] = value; if (!--ret) settlePromise(p1, $resolved, res); }, reject); }); if (ret === $tryErr) return self.reject(ret.e); if (!ret) settlePromise(p1, $resolved, []); return p1; }; /** * The ES6 Symbol object that Yaku should use, by default it will use the * global one. * @type {Object} * @example * ```js * var core = require("core-js/library"); * var Promise = require("yaku"); * Promise.Symbol = core.Symbol; * ``` */ Yaku.Symbol = root[$Symbol] || {}; // To support browsers that don't support `Object.defineProperty`. genTryCatcher(function () { Object.defineProperty(Yaku, getSpecies(), { get: function () { return this; } }); })(); /** * Use this api to custom the species behavior. * https://tc39.github.io/ecma262/#sec-speciesconstructor * @param {Any} O The current this object. * @param {Function} defaultConstructor */ Yaku.speciesConstructor = function (O, D) { var C = O.constructor; return C ? (C[getSpecies()] || D) : D; }; /** * Catch all possibly unhandled rejections. If you want to use specific * format to display the error stack, overwrite it. * If it is set, auto `console.error` unhandled rejection will be disabled. * @param {Any} reason The rejection reason. * @param {Yaku} p The promise that was rejected. * @example * ```js * var Promise = require('yaku'); * Promise.unhandledRejection = (reason) => { * console.error(reason); * }; * * // The console will log an unhandled rejection error message. * Promise.reject('my reason'); * * // The below won't log the unhandled rejection error message. * Promise.reject('v')["catch"](() => {}); * ``` */ Yaku.unhandledRejection = function (reason, p) { console && console.error( $unhandledRejectionMsg, isLongStackTrace ? p.longStack : genStackInfo(reason, p) ); }; /** * Emitted whenever a Promise was rejected and an error handler was * attached to it (for example with `["catch"]()`) later than after an event loop turn. * @param {Any} reason The rejection reason. * @param {Yaku} p The promise that was rejected. */ Yaku.rejectionHandled = $noop; /** * It is used to enable the long stack trace. * Once it is enabled, it can't be reverted. * While it is very helpful in development and testing environments, * it is not recommended to use it in production. It will slow down * application and eat up memory. * It will add an extra property `longStack` to the Error object. * @example * ```js * var Promise = require('yaku'); * Promise.enableLongStackTrace(); * Promise.reject(new Error("err"))["catch"]((err) => { * console.log(err.longStack); * }); * ``` */ Yaku.enableLongStackTrace = function () { isLongStackTrace = true; }; /** * Only Node has `process.nextTick` function. For browser there are * so many ways to polyfill it. Yaku won't do it for you, instead you * can choose what you prefer. For example, this project * [next-tick](https://github.com/medikoo/next-tick). * By default, Yaku will use `process.nextTick` on Node, `setTimeout` on browser. * @type {Function} * @example * ```js * var Promise = require('yaku'); * Promise.nextTick = require('next-tick'); * ``` * @example * You can even use sync resolution if you really know what you are doing. * ```js * var Promise = require('yaku'); * Promise.nextTick = fn => fn(); * ``` */ Yaku.nextTick = isBrowser ? function (fn) { nativePromise ? new nativePromise(function (resolve) { resolve(); }).then(fn) : setTimeout(fn); } : process.nextTick; // ********************** Private ********************** Yaku._s = 1; /** * All static variable name will begin with `$`. Such as `$rejected`. * @private */ // ******************************* Utils ******************************** function getSpecies () { return Yaku[$Symbol][$species] || $speciesKey; } function extend (src, target) { for (var k in target) { src[k] = target[k]; } } function isObject (obj) { return obj && typeof obj === 'object'; } function isFunction (obj) { return typeof obj === 'function'; } function isInstanceOf (a, b) { return a instanceof b; } function isError (obj) { return isInstanceOf(obj, Err); } function ensureType (obj, fn, msg) { if (!fn(obj)) throw genTypeError(msg); } /** * Wrap a function into a try-catch. * @private * @return {Any | $tryErr} */ function tryCatcher () { try { return $tryCatchFn.apply($tryCatchThis, arguments); } catch (e) { $tryErr.e = e; return $tryErr; } } /** * Generate a try-catch wrapped function. * @private * @param {Function} fn * @return {Function} */ function genTryCatcher (fn, self) { $tryCatchFn = fn; $tryCatchThis = self; return tryCatcher; } /** * Generate a scheduler. * @private * @param {Integer} initQueueSize * @param {Function} fn `(Yaku, Value) ->` The schedule handler. * @return {Function} `(Yaku, Value) ->` The scheduler. */ function genScheduler (initQueueSize, fn) { /** * All async promise will be scheduled in * here, so that they can be execute on the next tick. * @private */ var fnQueue = Arr(initQueueSize) , fnQueueLen = 0; /** * Run all queued functions. * @private */ function flush () { var i = 0; while (i initQueueSize) fnQueue.length = initQueueSize; } return function (v, arg) { fnQueue[fnQueueLen++] = v; fnQueue[fnQueueLen++] = arg; if (fnQueueLen === 2) Yaku.nextTick(flush); }; } /** * Generate a iterator * @param {Any} obj * @private * @return {Object || TypeError} */ function each (iterable, fn) { var len , i = 0 , iter , item , ret ; if (!iterable) throw genTypeError($invalidArgument); var gen = iterable[Yaku[$Symbol][$iterator]]; if (isFunction(gen)) iter = gen.call(iterable); else if (isFunction(iterable.next)) { iter = iterable; } else if (isInstanceOf(iterable, Arr)) { len = iterable.length; while (i `. * @private * @param {Yaku} self * @param {Integer} state The value is one of `$pending`, `$resolved` or `$rejected`. * @return {Function} `(value) -> undefined` A resolve or reject function. */ function genSettler (self, state) { var isCalled = false; return function (value) { if (isCalled) return; isCalled = true; if (isLongStackTrace) self[$settlerTrace] = genTraceInfo(true); if (state === $resolved) settleWithX(self, value); else settlePromise(self, state, value); }; } /** * Link the promise1 to the promise2. * @private * @param {Yaku} p1 * @param {Yaku} p2 * @param {Function} onFulfilled * @param {Function} onRejected */ function addHandler (p1, p2, onFulfilled, onRejected) { // 2.2.1 if (isFunction(onFulfilled)) p2._onFulfilled = onFulfilled; if (isFunction(onRejected)) { if (p1[$unhandled]) emitEvent($rejectionHandled, p1); p2._onRejected = onRejected; } if (isLongStackTrace) p2._p = p1; p1[p1._c++] = p2; // 2.2.6 if (p1._s !== $pending) scheduleHandler(p1, p2); // 2.2.7 return p2; } // iterate tree function hashOnRejected (node) { // A node shouldn't be checked twice. if (node._umark) return true; else node._umark = true; var i = 0 , len = node._c , child; while (i 0 ? arguments[0] : undefined; // 5. If iterable is either undefined or null, return set. if (iterable === null || iterable === undefined) { return set; } // 6. Let adder be ? Get(set, "add"). var adder = set.add; // 7. If IsCallable(adder) is false, throw a TypeError exception. if (!IsCallable(adder)) { throw new TypeError("Set.prototype.add is not a function"); } try { // 8. Let iteratorRecord be ? GetIterator(iterable). var iteratorRecord = GetIterator(iterable); // 9. Repeat, // eslint-disable-next-line no-constant-condition while (true) { // a. Let next be ? IteratorStep(iteratorRecord). var next = IteratorStep(iteratorRecord); // b. If next is false, return set. if (next === false) { return set; } // c. Let nextValue be ? IteratorValue(next). var nextValue = IteratorValue(next); // d. Let status be Call(adder, set, « nextValue.[[Value]] »). try { adder.call(set, nextValue); } catch (e) { // e. If status is an abrupt completion, return ? IteratorClose(iteratorRecord, status). return IteratorClose(iteratorRecord, e); } } } catch (e) { // Polyfill.io - For user agents which do not have iteration methods on argument objects or arrays, we can special case those. if (Array.isArray(iterable) || Object.prototype.toString.call(iterable) === '[object Arguments]') { var index; var length = iterable.length; for (index = 0; index 1 ? arguments[1] : undefined; if (mapfn === undefined) { var mapping = false; // 3. Else, } else { // a. If IsCallable(mapfn) is false, throw a TypeError exception. if (IsCallable(mapfn) === false) { throw new TypeError(Object.prototype.toString.call(mapfn) + ' is not a function.'); } // b. If thisArg is present, let T be thisArg; else let T be undefined. var thisArg = arguments.length > 2 ? arguments[2] : undefined; if (thisArg !== undefined) { var T = thisArg; } else { T = undefined; } // c. Let mapping be true. mapping = true; } // 4. Let usingIterator be ? GetMethod(items, @@iterator). var usingIterator = GetMethod(items, Symbol.iterator); // 5. If usingIterator is not undefined, then if (usingIterator !== undefined) { // a. If IsConstructor(C) is true, then if (IsConstructor(C)) { // i. Let A be ? Construct(C). var A = Construct(C); // b. Else, } else { // i. Let A be ! ArrayCreate(0). A = ArrayCreate(0); } // c. Let iteratorRecord be ? GetIterator(items, usingIterator). var iteratorRecord = GetIterator(items, usingIterator); // d. Let k be 0. var k = 0; // e. Repeat, // eslint-disable-next-line no-constant-condition while (true) { // i. If k ≥ 2^53-1, then if (k >= (Math.pow(2, 53) - 1)) { // 1. Let error be Completion{[[Type]]: throw, [[Value]]: a newly created TypeError object, [[Target]]: empty}. var error = new TypeError('Iteration count can not be greater than or equal 9007199254740991.'); // 2. Return ? IteratorClose(iteratorRecord, error). return IteratorClose(iteratorRecord, error); } // ii. Let Pk be ! ToString(k). var Pk = ToString(k); // iii. Let next be ? IteratorStep(iteratorRecord). var next = IteratorStep(iteratorRecord); // iv. If next is false, then if (next === false) { // 1. Perform ? Set(A, "length", k, true). A.length = k; // 2. Return A. return A; } // v. Let nextValue be ? IteratorValue(next). var nextValue = IteratorValue(next); // vi. If mapping is true, then if (mapping) { try { // Polyfill.io - The try catch accounts for step 2. // 1. Let mappedValue be Call(mapfn, T, « nextValue, k »). var mappedValue = Call(mapfn, T, [nextValue, k]); // 2. If mappedValue is an abrupt completion, return ? IteratorClose(iteratorRecord, mappedValue). // 3. Let mappedValue be mappedValue.[[Value]]. } catch (e) { return IteratorClose(iteratorRecord, e); } // vii. Else, let mappedValue be nextValue. } else { mappedValue = nextValue; } try { // Polyfill.io - The try catch accounts for step ix. // viii. Let defineStatus be CreateDataPropertyOrThrow(A, Pk, mappedValue). CreateDataPropertyOrThrow(A, Pk, mappedValue); // ix. If defineStatus is an abrupt completion, return ? IteratorClose(iteratorRecord, defineStatus). } catch (e) { return IteratorClose(iteratorRecord, e); } // x. Increase k by 1. k = k + 1; } } // 6. NOTE: items is not an Iterable so assume it is an array-like object. // 7. Let arrayLike be ! ToObject(items). // Polyfill.io - For Strings we need to split astral symbols into surrogate pairs. if (isString(items)) { var arrayLike = stringMatch.call(items, /[\uD800-\uDBFF][\uDC00-\uDFFF]?|[^\uD800-\uDFFF]|./g) || []; } else { arrayLike = ToObject(items); } // 8. Let len be ? ToLength(? Get(arrayLike, "length")). var len = ToLength(Get(arrayLike, "length")); // 9. If IsConstructor(C) is true, then if (IsConstructor(C)) { // a. Let A be ? Construct(C, « len »). A = Construct(C, [len]); // 10. Else, } else { // a. Let A be ? ArrayCreate(len). A = ArrayCreate(len); } // 11. Let k be 0. k = 0; // 12. Repeat, while k = 0 ? relativeIndex : len + relativeIndex; // 7. If k = len) return undefined; // 8. Return ! Get(O, ! ToString(𝔽(k))). return Get(O, ToString(k)); } // in IE11, `Int8Array.prototype` inherits directly from `Object.prototype` // in that case, don't define it on the parent; define it directly on the prototype if ('__proto__' in self.Int8Array.prototype && self.Int8Array.prototype.__proto__ !== Object.prototype) { // set this on the underlying "TypedArrayPrototype", which is shared with all "TypedArray" subclasses CreateMethodProperty(self.Int8Array.prototype.__proto__, 'at', at); } else { CreateMethodProperty(self.Int8Array.prototype, 'at', at); CreateMethodProperty(self.Uint8Array.prototype, 'at', at); CreateMethodProperty(self.Uint8ClampedArray.prototype, 'at', at); CreateMethodProperty(self.Int16Array.prototype, 'at', at); CreateMethodProperty(self.Uint16Array.prototype, 'at', at); CreateMethodProperty(self.Int32Array.prototype, 'at', at); CreateMethodProperty(self.Uint32Array.prototype, 'at', at); CreateMethodProperty(self.Float32Array.prototype, 'at', at); CreateMethodProperty(self.Float64Array.prototype, 'at', at); } })(); } if (!("Int8Array"in self&&"entries"in self.Int8Array.prototype )) { // TypedArray.prototype.entries /* global CreateMethodProperty, ArrayIterator */ // 23.2.3.7 %TypedArray%.prototype.entries ( ) (function () { function entries() { // 1. Let O be the this value. var O = this; // 2. Perform ? ValidateTypedArray(O). // TODO: Add ValidateTypedArray // 3. Return CreateArrayIterator(O, key). // TODO: Add CreateArrayIterator return new ArrayIterator(O, 'key+value'); } // use "Int8Array" as a proxy for support of "TypedArray" subclasses var fnName = 'entries' // in IE11, `Int8Array.prototype` inherits directly from `Object.prototype` // in that case, don't define it on the parent; define it directly on the prototype if ('__proto__' in self.Int8Array.prototype && self.Int8Array.prototype.__proto__ !== Object.prototype) { // set this on the underlying "TypedArrayPrototype", which is shared with all "TypedArray" subclasses CreateMethodProperty(self.Int8Array.prototype.__proto__, fnName, entries); } else { CreateMethodProperty(self.Int8Array.prototype, fnName, entries); CreateMethodProperty(self.Uint8Array.prototype, fnName, entries); CreateMethodProperty(self.Uint8ClampedArray.prototype, fnName, entries); CreateMethodProperty(self.Int16Array.prototype, fnName, entries); CreateMethodProperty(self.Uint16Array.prototype, fnName, entries); CreateMethodProperty(self.Int32Array.prototype, fnName, entries); CreateMethodProperty(self.Uint32Array.prototype, fnName, entries); CreateMethodProperty(self.Float32Array.prototype, fnName, entries); CreateMethodProperty(self.Float64Array.prototype, fnName, entries); } })(); } if (!("Int8Array"in self&&"findLast"in self.Int8Array.prototype )) { // TypedArray.prototype.findLast /* global Call, CreateMethodProperty, Get, IsCallable, ToBoolean, ToString */ // 23.2.3.13 %TypedArray%.prototype.findLast ( predicate [ , thisArg ] ) (function () { function findLast(predicate /*[ , thisArg ]*/) { // 1. Let O be the this value. var O = this; // 2. Perform ? ValidateTypedArray(O). // TODO: Add ValidateTypedArray // 3. Let len be O.[[ArrayLength]]. var len = O.length; // 4. If IsCallable(predicate) is false, throw a TypeError exception. if (!IsCallable(predicate)) throw TypeError(); // 5. Let k be len - 1. var k = len - 1; // 6. Repeat, while k ≥ 0, while (k >= 0) { // a. Let Pk be ! ToString(𝔽(k)). var Pk = ToString(k); // b. Let kValue be ! Get(O, Pk). var kValue = Get(O, Pk); // c. Let testResult be ToBoolean(? Call(predicate, thisArg, « kValue, 𝔽(k), O »)). var testResult = ToBoolean(Call(predicate, arguments.length > 1 ? arguments[1] : undefined, [kValue, k, O])) // d. If testResult is true, return kValue. if (testResult) { return kValue; } // e. Set k to k - 1. k = k - 1; } // 7. Return undefined. return undefined; } var fnName = 'findLast' // in IE11, `Int8Array.prototype` inherits directly from `Object.prototype` // in that case, don't define it on the parent; define it directly on the prototype if ('__proto__' in self.Int8Array.prototype && self.Int8Array.prototype.__proto__ !== Object.prototype) { // set this on the underlying "TypedArrayPrototype", which is shared with all "TypedArray" subclasses CreateMethodProperty(self.Int8Array.prototype.__proto__, fnName, findLast); } else { CreateMethodProperty(self.Int8Array.prototype, fnName, findLast); CreateMethodProperty(self.Uint8Array.prototype, fnName, findLast); CreateMethodProperty(self.Uint8ClampedArray.prototype, fnName, findLast); CreateMethodProperty(self.Int16Array.prototype, fnName, findLast); CreateMethodProperty(self.Uint16Array.prototype, fnName, findLast); CreateMethodProperty(self.Int32Array.prototype, fnName, findLast); CreateMethodProperty(self.Uint32Array.prototype, fnName, findLast); CreateMethodProperty(self.Float32Array.prototype, fnName, findLast); CreateMethodProperty(self.Float64Array.prototype, fnName, findLast); } })(); } if (!("Int8Array"in self&&"findLastIndex"in self.Int8Array.prototype )) { // TypedArray.prototype.findLastIndex /* global Call, CreateMethodProperty, Get, IsCallable, ToBoolean, ToString */ // 23.2.3.14 %TypedArray%.prototype.findLastIndex ( predicate [ , thisArg ] ) (function () { function findLastIndex(predicate /*[ , thisArg ]*/) { // 1. Let O be the this value. var O = this; // 2. Perform ? ValidateTypedArray(O). // TODO: Add ValidateTypedArray // 3. Let len be O.[[ArrayLength]]. var len = O.length; // 4. If IsCallable(predicate) is false, throw a TypeError exception. if (!IsCallable(predicate)) throw TypeError(); // 5. Let k be len - 1. var k = len - 1; // 6. Repeat, while k ≥ 0, while (k >= 0) { // a. Let Pk be ! ToString(𝔽(k)). var Pk = ToString(k); // b. Let kValue be ! Get(O, Pk). var kValue = Get(O, Pk); // c. Let testResult be ToBoolean(? Call(predicate, thisArg, « kValue, 𝔽(k), O »)). var testResult = ToBoolean(Call(predicate, arguments.length > 1 ? arguments[1] : undefined, [kValue, k, O])) // d. If testResult is true, return 𝔽(k). if (testResult) { return k; } // e. Set k to k - 1. k = k - 1; } // 7. Return -1𝔽. return -1; } var fnName = 'findLastIndex' // in IE11, `Int8Array.prototype` inherits directly from `Object.prototype` // in that case, don't define it on the parent; define it directly on the prototype if ('__proto__' in self.Int8Array.prototype && self.Int8Array.prototype.__proto__ !== Object.prototype) { // set this on the underlying "TypedArrayPrototype", which is shared with all "TypedArray" subclasses CreateMethodProperty(self.Int8Array.prototype.__proto__, fnName, findLastIndex); } else { CreateMethodProperty(self.Int8Array.prototype, fnName, findLastIndex); CreateMethodProperty(self.Uint8Array.prototype, fnName, findLastIndex); CreateMethodProperty(self.Uint8ClampedArray.prototype, fnName, findLastIndex); CreateMethodProperty(self.Int16Array.prototype, fnName, findLastIndex); CreateMethodProperty(self.Uint16Array.prototype, fnName, findLastIndex); CreateMethodProperty(self.Int32Array.prototype, fnName, findLastIndex); CreateMethodProperty(self.Uint32Array.prototype, fnName, findLastIndex); CreateMethodProperty(self.Float32Array.prototype, fnName, findLastIndex); CreateMethodProperty(self.Float64Array.prototype, fnName, findLastIndex); } })(); } if (!("Int8Array"in self&&"keys"in self.Int8Array.prototype )) { // TypedArray.prototype.keys /* global CreateMethodProperty, ArrayIterator */ // 23.2.3.19 %TypedArray%.prototype.keys ( ) (function () { function keys() { // 1. Let O be the this value. var O = this; // 2. Perform ? ValidateTypedArray(O). // TODO: Add ValidateTypedArray // 3. Return CreateArrayIterator(O, key). // TODO: Add CreateArrayIterator return new ArrayIterator(O, 'key'); } // use "Int8Array" as a proxy for support of "TypedArray" subclasses var fnName = 'keys' // in IE11, `Int8Array.prototype` inherits directly from `Object.prototype` // in that case, don't define it on the parent; define it directly on the prototype if ('__proto__' in self.Int8Array.prototype && self.Int8Array.prototype.__proto__ !== Object.prototype) { // set this on the underlying "TypedArrayPrototype", which is shared with all "TypedArray" subclasses CreateMethodProperty(self.Int8Array.prototype.__proto__, fnName, keys); } else { CreateMethodProperty(self.Int8Array.prototype, fnName, keys); CreateMethodProperty(self.Uint8Array.prototype, fnName, keys); CreateMethodProperty(self.Uint8ClampedArray.prototype, fnName, keys); CreateMethodProperty(self.Int16Array.prototype, fnName, keys); CreateMethodProperty(self.Uint16Array.prototype, fnName, keys); CreateMethodProperty(self.Int32Array.prototype, fnName, keys); CreateMethodProperty(self.Uint32Array.prototype, fnName, keys); CreateMethodProperty(self.Float32Array.prototype, fnName, keys); CreateMethodProperty(self.Float64Array.prototype, fnName, keys); } })(); } if (!("Int8Array"in self&&"sort"in self.Int8Array.prototype )) { // TypedArray.prototype.sort /* global CreateMethodProperty, IsCallable */ // 23.2.3.29 %TypedArray%.prototype.sort ( comparefn ) (function () { function sort(comparefn) { // 1. If comparefn is not undefined and IsCallable(comparefn) is false, throw a TypeError exception. if (comparefn !== undefined && IsCallable(comparefn) === false) { throw new TypeError( "The comparison function must be either a function or undefined" ); } // 2. Let obj be the this value. var obj = this; // 3. Perform ? ValidateTypedArray(obj). // TODO: Add ValidateTypedArray // 4. Let len be obj.[[ArrayLength]]. var len = obj.length; // Polyfill.io - This is based on https://github.com/inexorabletash/polyfill/blob/716a3f36ca10fad032083014faf1a47c638e2502/typedarray.js#L848-L858 // 5. NOTE: The following closure performs a numeric comparison rather than the string comparison used in 23.1.3.30. // 6. Let SortCompare be a new Abstract Closure with parameters (x, y) that captures comparefn and performs the following steps when called: // a. Return ? CompareTypedArrayElements(x, y, comparefn). function sortCompare(x, y) { if (x !== x && y !== y) return +0; if (x !== x) return 1; if (y !== y) return -1; if (comparefn !== undefined) { return comparefn(x, y); } if (x y) return 1; return +0; } // 7. Let sortedList be ? SortIndexedProperties(obj, len, SortCompare, read-through-holes). var sortedList = Array(len); for (var i = 0; i = 0 ? relativeIndex : len + relativeIndex; // 7. If O.[[ContentType]] is BigInt, let numericValue be ? ToBigInt(value). // TODO: Add BigInt support // 8. Else, let numericValue be ? ToNumber(value). var numericValue = ToNumber(value); // 9. If IsValidIntegerIndex(O, 𝔽(actualIndex)) is false, throw a RangeError exception. if (IsValidIntegerIndex(O, actualIndex) === false) { throw new RangeError('Invalid index'); } // 10. Let A be ? TypedArrayCreateSameType(O, « 𝔽(len) »). var A = TypedArrayCreateSameType(O, [ len ]); // 11. Let k be 0. var k = 0; // 12. Repeat, while k // * Safely create multi-byte chars with decodeURIComponent, by only passing it // valid and full characters (e.g. "%F0" separately from "%F0%9F%92%A9" throws). // Anything else is kept as literal or replaced with U+FFFD, as per the URL spec. if (!cachedDecodePattern) { // In a UTF-8 multibyte sequence, non-initial bytes are always between %80 and %BF var uContinuation = '%[89AB][0-9A-F]'; // The length of a UTF-8 sequence is specified by the first byte // // One-byte sequences: 0xxxxxxx // So the byte is between %00 and %7F var u1Bytes = '%[0-7][0-9A-F]'; // Two-byte sequences: 110xxxxx 10xxxxxx // So the first byte is between %C0 and %DF var u2Bytes = '%[CD][0-9A-F]' + uContinuation; // Three-byte sequences: 1110xxxx 10xxxxxx 10xxxxxx // So the first byte is between %E0 and %EF var u3Bytes = '%E[0-9A-F]' + uContinuation + uContinuation; // Four-byte sequences: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // So the first byte is between %F0 and %F7 var u4Bytes = '%F[0-7]' + uContinuation + uContinuation +uContinuation; var anyByte = '%[0-9A-F][0-9A-F]'; // Match some consecutive percent-escaped bytes. More precisely, match // 1-4 bytes that validly encode one character in UTF-8, or 1 byte that // would be invalid in UTF-8 in this location. cachedDecodePattern = new RegExp( '(' + u4Bytes + ')|(' + u3Bytes + ')|(' + u2Bytes + ')|(' + u1Bytes + ')|(' + anyByte + ')', 'gi' ); } return bytes.replace(cachedDecodePattern, function (match, u4, u3, u2, u1, uBad) { return (uBad !== undefined) ? '\uFFFD' : decodeURIComponent(match); }); } // NOTE: Doesn't do the encoding/decoding dance // // https://url.spec.whatwg.org/#concept-urlencoded-parser function urlencoded_parse(input, isindex) { var sequences = input.split('&'); if (isindex && sequences[0].indexOf('=') === -1) sequences[0] = '=' + sequences[0]; var pairs = []; sequences.forEach(function (bytes) { if (bytes.length === 0) return; var index = bytes.indexOf('='); if (index !== -1) { var name = bytes.substring(0, index); var value = bytes.substring(index + 1); } else { name = bytes; value = ''; } name = name.replace(/\+/g, ' '); value = value.replace(/\+/g, ' '); pairs.push({ name: name, value: value }); }); var output = []; pairs.forEach(function (pair) { output.push({ name: percent_decode(pair.name), value: percent_decode(pair.value) }); }); return output; } function URLUtils(url) { if (nativeURL) return new origURL(url); var anchor = document.createElement('a'); anchor.href = url; return anchor; } function URLSearchParams(init) { var $this = this; this._list = []; if (init === undefined || init === null) { // no-op } else if (init instanceof URLSearchParams) { // In ES6 init would be a sequence, but special case for ES5. this._list = urlencoded_parse(String(init)); } else if (typeof init === 'object' && isSequence(init)) { Array.from(init).forEach(function(e) { if (!isSequence(e)) throw TypeError(); var nv = Array.from(e); if (nv.length !== 2) throw TypeError(); $this._list.push({name: String(nv[0]), value: String(nv[1])}); }); } else if (typeof init === 'object' && init) { Object.keys(init).forEach(function(key) { $this._list.push({name: String(key), value: String(init[key])}); }); } else { init = String(init); if (init.substring(0, 1) === '?') init = init.substring(1); this._list = urlencoded_parse(init); } this._url_object = null; this._setList = function (list) { if (!updating) $this._list = list; }; var updating = false; this._update_steps = function() { if (updating) return; updating = true; if (!$this._url_object) return; // Partial workaround for IE issue with 'about:' if ($this._url_object.protocol === 'about:' && $this._url_object.pathname.indexOf('?') !== -1) { $this._url_object.pathname = $this._url_object.pathname.split('?')[0]; } $this._url_object.search = urlencoded_serialize($this._list); updating = false; }; } Object.defineProperties(URLSearchParams.prototype, { append: { value: function (name, value) { this._list.push({ name: name, value: value }); this._update_steps(); }, writable: true, enumerable: true, configurable: true }, 'delete': { value: function (name) { for (var i = 0; i 1) ? arguments[1] : undefined; this._list.forEach(function(pair) { callback.call(thisArg, pair.value, pair.name); }); }, writable: true, enumerable: true, configurable: true }, toString: { value: function () { return urlencoded_serialize(this._list); }, writable: true, enumerable: false, configurable: true }, sort: { value: function sort() { var entries = this.entries(); var entry = entries.next(); var keys = []; var values = {}; while (!entry.done) { var value = entry.value; var key = value[0]; keys.push(key); if (!(Object.prototype.hasOwnProperty.call(values, key))) { values[key] = []; } values[key].push(value[1]); entry = entries.next(); } keys.sort(); for (var i = 0; i = source.length) return {done: true, value: undefined}; var pair = source[index++]; return {done: false, value: kind === 'key' ? pair.name : kind === 'value' ? pair.value : [pair.name, pair.value]}; }; } if ('Symbol' in global && 'iterator' in global.Symbol) { Object.defineProperty(URLSearchParams.prototype, global.Symbol.iterator, { value: URLSearchParams.prototype.entries, writable: true, enumerable: true, configurable: true}); Object.defineProperty(Iterator.prototype, global.Symbol.iterator, { value: function() { return this; }, writable: true, enumerable: true, configurable: true}); } function URL(url, base) { if (!(this instanceof global.URL)) throw new TypeError("Failed to construct 'URL': Please use the 'new' operator."); if (base) { url = (function () { if (nativeURL) return new origURL(url, base).href; var iframe; try { var doc; // Use another document/base tag/anchor for relative URL resolution, if possible if (Object.prototype.toString.call(window.operamini) === "[object OperaMini]") { iframe = document.createElement('iframe'); iframe.style.display = 'none'; document.documentElement.appendChild(iframe); doc = iframe.contentWindow.document; } else if (document.implementation && document.implementation.createHTMLDocument) { doc = document.implementation.createHTMLDocument(''); } else if (document.implementation && document.implementation.createDocument) { doc = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null); doc.documentElement.appendChild(doc.createElement('head')); doc.documentElement.appendChild(doc.createElement('body')); } else if (window.ActiveXObject) { doc = new window.ActiveXObject('htmlfile'); doc.write('
