element.');\n }\n var callbackRef = function callbackRef(element) {\n var containerElements = _this3.props.containerElements;\n if (child) {\n if (typeof child.ref === 'function') {\n child.ref(element);\n } else if (child.ref) {\n child.ref.current = element;\n }\n }\n _this3.focusTrapElements = containerElements ? containerElements : [element];\n };\n var childWithRef = React.cloneElement(child, {\n ref: callbackRef\n });\n return childWithRef;\n }\n return null;\n }\n }]);\n}(React.Component); // support server-side rendering where `Element` will not be defined\nvar ElementType = typeof Element === 'undefined' ? Function : Element;\nFocusTrap.propTypes = {\n active: PropTypes.bool,\n paused: PropTypes.bool,\n focusTrapOptions: PropTypes.shape({\n document: PropTypes.object,\n onActivate: PropTypes.func,\n onPostActivate: PropTypes.func,\n checkCanFocusTrap: PropTypes.func,\n onPause: PropTypes.func,\n onPostPause: PropTypes.func,\n onUnpause: PropTypes.func,\n onPostUnpause: PropTypes.func,\n onDeactivate: PropTypes.func,\n onPostDeactivate: PropTypes.func,\n checkCanReturnFocus: PropTypes.func,\n initialFocus: PropTypes.oneOfType([PropTypes.instanceOf(ElementType), PropTypes.string, PropTypes.bool, PropTypes.func]),\n fallbackFocus: PropTypes.oneOfType([PropTypes.instanceOf(ElementType), PropTypes.string,\n // NOTE: does not support `false` as value (or return value from function)\n PropTypes.func]),\n escapeDeactivates: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),\n clickOutsideDeactivates: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),\n returnFocusOnDeactivate: PropTypes.bool,\n setReturnFocus: PropTypes.oneOfType([PropTypes.instanceOf(ElementType), PropTypes.string, PropTypes.bool, PropTypes.func]),\n allowOutsideClick: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),\n preventScroll: PropTypes.bool,\n tabbableOptions: PropTypes.shape({\n displayCheck: PropTypes.oneOf(['full', 'legacy-full', 'non-zero-area', 'none']),\n getShadowRoot: PropTypes.oneOfType([PropTypes.bool, PropTypes.func])\n }),\n trapStack: PropTypes.array,\n isKeyForward: PropTypes.func,\n isKeyBackward: PropTypes.func\n }),\n containerElements: PropTypes.arrayOf(PropTypes.instanceOf(ElementType)),\n // DOM element ONLY\n children: PropTypes.oneOfType([PropTypes.element,\n // React element\n PropTypes.instanceOf(ElementType) // DOM element\n ])\n\n // NOTE: _createFocusTrap is internal, for testing purposes only, so we don't\n // specify it here. It's expected to be set to the function returned from\n // require('focus-trap'), or one with a compatible interface.\n};\nFocusTrap.defaultProps = {\n active: true,\n paused: false,\n focusTrapOptions: {},\n _createFocusTrap: createFocusTrap\n};\nmodule.exports = FocusTrap;","/*!\n* focus-trap 7.6.1\n* @license MIT, https://github.com/focus-trap/focus-trap/blob/master/LICENSE\n*/\nimport { isFocusable, tabbable, focusable, isTabbable, getTabIndex } from 'tabbable';\n\nfunction _arrayLikeToArray(r, a) {\n (null == a || a > r.length) && (a = r.length);\n for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];\n return n;\n}\nfunction _arrayWithoutHoles(r) {\n if (Array.isArray(r)) return _arrayLikeToArray(r);\n}\nfunction _defineProperty(e, r, t) {\n return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n value: t,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }) : e[r] = t, e;\n}\nfunction _iterableToArray(r) {\n if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r);\n}\nfunction _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\nfunction ownKeys(e, r) {\n var t = Object.keys(e);\n if (Object.getOwnPropertySymbols) {\n var o = Object.getOwnPropertySymbols(e);\n r && (o = o.filter(function (r) {\n return Object.getOwnPropertyDescriptor(e, r).enumerable;\n })), t.push.apply(t, o);\n }\n return t;\n}\nfunction _objectSpread2(e) {\n for (var r = 1; r < arguments.length; r++) {\n var t = null != arguments[r] ? arguments[r] : {};\n r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {\n _defineProperty(e, r, t[r]);\n }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {\n Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));\n });\n }\n return e;\n}\nfunction _toConsumableArray(r) {\n return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();\n}\nfunction _toPrimitive(t, r) {\n if (\"object\" != typeof t || !t) return t;\n var e = t[Symbol.toPrimitive];\n if (void 0 !== e) {\n var i = e.call(t, r || \"default\");\n if (\"object\" != typeof i) return i;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (\"string\" === r ? String : Number)(t);\n}\nfunction _toPropertyKey(t) {\n var i = _toPrimitive(t, \"string\");\n return \"symbol\" == typeof i ? i : i + \"\";\n}\nfunction _unsupportedIterableToArray(r, a) {\n if (r) {\n if (\"string\" == typeof r) return _arrayLikeToArray(r, a);\n var t = {}.toString.call(r).slice(8, -1);\n return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;\n }\n}\n\nvar activeFocusTraps = {\n activateTrap: function activateTrap(trapStack, trap) {\n if (trapStack.length > 0) {\n var activeTrap = trapStack[trapStack.length - 1];\n if (activeTrap !== trap) {\n activeTrap.pause();\n }\n }\n var trapIndex = trapStack.indexOf(trap);\n if (trapIndex === -1) {\n trapStack.push(trap);\n } else {\n // move this existing trap to the front of the queue\n trapStack.splice(trapIndex, 1);\n trapStack.push(trap);\n }\n },\n deactivateTrap: function deactivateTrap(trapStack, trap) {\n var trapIndex = trapStack.indexOf(trap);\n if (trapIndex !== -1) {\n trapStack.splice(trapIndex, 1);\n }\n if (trapStack.length > 0) {\n trapStack[trapStack.length - 1].unpause();\n }\n }\n};\nvar isSelectableInput = function isSelectableInput(node) {\n return node.tagName && node.tagName.toLowerCase() === 'input' && typeof node.select === 'function';\n};\nvar isEscapeEvent = function isEscapeEvent(e) {\n return (e === null || e === void 0 ? void 0 : e.key) === 'Escape' || (e === null || e === void 0 ? void 0 : e.key) === 'Esc' || (e === null || e === void 0 ? void 0 : e.keyCode) === 27;\n};\nvar isTabEvent = function isTabEvent(e) {\n return (e === null || e === void 0 ? void 0 : e.key) === 'Tab' || (e === null || e === void 0 ? void 0 : e.keyCode) === 9;\n};\n\n// checks for TAB by default\nvar isKeyForward = function isKeyForward(e) {\n return isTabEvent(e) && !e.shiftKey;\n};\n\n// checks for SHIFT+TAB by default\nvar isKeyBackward = function isKeyBackward(e) {\n return isTabEvent(e) && e.shiftKey;\n};\nvar delay = function delay(fn) {\n return setTimeout(fn, 0);\n};\n\n// Array.find/findIndex() are not supported on IE; this replicates enough\n// of Array.findIndex() for our needs\nvar findIndex = function findIndex(arr, fn) {\n var idx = -1;\n arr.every(function (value, i) {\n if (fn(value)) {\n idx = i;\n return false; // break\n }\n return true; // next\n });\n return idx;\n};\n\n/**\n * Get an option's value when it could be a plain value, or a handler that provides\n * the value.\n * @param {*} value Option's value to check.\n * @param {...*} [params] Any parameters to pass to the handler, if `value` is a function.\n * @returns {*} The `value`, or the handler's returned value.\n */\nvar valueOrHandler = function valueOrHandler(value) {\n for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n params[_key - 1] = arguments[_key];\n }\n return typeof value === 'function' ? value.apply(void 0, params) : value;\n};\nvar getActualTarget = function getActualTarget(event) {\n // NOTE: If the trap is _inside_ a shadow DOM, event.target will always be the\n // shadow host. However, event.target.composedPath() will be an array of\n // nodes \"clicked\" from inner-most (the actual element inside the shadow) to\n // outer-most (the host HTML document). If we have access to composedPath(),\n // then use its first element; otherwise, fall back to event.target (and\n // this only works for an _open_ shadow DOM; otherwise,\n // composedPath()[0] === event.target always).\n return event.target.shadowRoot && typeof event.composedPath === 'function' ? event.composedPath()[0] : event.target;\n};\n\n// NOTE: this must be _outside_ `createFocusTrap()` to make sure all traps in this\n// current instance use the same stack if `userOptions.trapStack` isn't specified\nvar internalTrapStack = [];\nvar createFocusTrap = function createFocusTrap(elements, userOptions) {\n // SSR: a live trap shouldn't be created in this type of environment so this\n // should be safe code to execute if the `document` option isn't specified\n var doc = (userOptions === null || userOptions === void 0 ? void 0 : userOptions.document) || document;\n var trapStack = (userOptions === null || userOptions === void 0 ? void 0 : userOptions.trapStack) || internalTrapStack;\n var config = _objectSpread2({\n returnFocusOnDeactivate: true,\n escapeDeactivates: true,\n delayInitialFocus: true,\n isKeyForward: isKeyForward,\n isKeyBackward: isKeyBackward\n }, userOptions);\n var state = {\n // containers given to createFocusTrap()\n // @type {Array
}\n containers: [],\n // list of objects identifying tabbable nodes in `containers` in the trap\n // NOTE: it's possible that a group has no tabbable nodes if nodes get removed while the trap\n // is active, but the trap should never get to a state where there isn't at least one group\n // with at least one tabbable node in it (that would lead to an error condition that would\n // result in an error being thrown)\n // @type {Array<{\n // container: HTMLElement,\n // tabbableNodes: Array, // empty if none\n // focusableNodes: Array, // empty if none\n // posTabIndexesFound: boolean,\n // firstTabbableNode: HTMLElement|undefined,\n // lastTabbableNode: HTMLElement|undefined,\n // firstDomTabbableNode: HTMLElement|undefined,\n // lastDomTabbableNode: HTMLElement|undefined,\n // nextTabbableNode: (node: HTMLElement, forward: boolean) => HTMLElement|undefined\n // }>}\n containerGroups: [],\n // same order/length as `containers` list\n\n // references to objects in `containerGroups`, but only those that actually have\n // tabbable nodes in them\n // NOTE: same order as `containers` and `containerGroups`, but __not necessarily__\n // the same length\n tabbableGroups: [],\n nodeFocusedBeforeActivation: null,\n mostRecentlyFocusedNode: null,\n active: false,\n paused: false,\n // timer ID for when delayInitialFocus is true and initial focus in this trap\n // has been delayed during activation\n delayInitialFocusTimer: undefined,\n // the most recent KeyboardEvent for the configured nav key (typically [SHIFT+]TAB), if any\n recentNavEvent: undefined\n };\n var trap; // eslint-disable-line prefer-const -- some private functions reference it, and its methods reference private functions, so we must declare here and define later\n\n /**\n * Gets a configuration option value.\n * @param {Object|undefined} configOverrideOptions If true, and option is defined in this set,\n * value will be taken from this object. Otherwise, value will be taken from base configuration.\n * @param {string} optionName Name of the option whose value is sought.\n * @param {string|undefined} [configOptionName] Name of option to use __instead of__ `optionName`\n * IIF `configOverrideOptions` is not defined. Otherwise, `optionName` is used.\n */\n var getOption = function getOption(configOverrideOptions, optionName, configOptionName) {\n return configOverrideOptions && configOverrideOptions[optionName] !== undefined ? configOverrideOptions[optionName] : config[configOptionName || optionName];\n };\n\n /**\n * Finds the index of the container that contains the element.\n * @param {HTMLElement} element\n * @param {Event} [event] If available, and `element` isn't directly found in any container,\n * the event's composed path is used to see if includes any known trap containers in the\n * case where the element is inside a Shadow DOM.\n * @returns {number} Index of the container in either `state.containers` or\n * `state.containerGroups` (the order/length of these lists are the same); -1\n * if the element isn't found.\n */\n var findContainerIndex = function findContainerIndex(element, event) {\n var composedPath = typeof (event === null || event === void 0 ? void 0 : event.composedPath) === 'function' ? event.composedPath() : undefined;\n // NOTE: search `containerGroups` because it's possible a group contains no tabbable\n // nodes, but still contains focusable nodes (e.g. if they all have `tabindex=-1`)\n // and we still need to find the element in there\n return state.containerGroups.findIndex(function (_ref) {\n var container = _ref.container,\n tabbableNodes = _ref.tabbableNodes;\n return container.contains(element) || (// fall back to explicit tabbable search which will take into consideration any\n // web components if the `tabbableOptions.getShadowRoot` option was used for\n // the trap, enabling shadow DOM support in tabbable (`Node.contains()` doesn't\n // look inside web components even if open)\n composedPath === null || composedPath === void 0 ? void 0 : composedPath.includes(container)) || tabbableNodes.find(function (node) {\n return node === element;\n });\n });\n };\n\n /**\n * Gets the node for the given option, which is expected to be an option that\n * can be either a DOM node, a string that is a selector to get a node, `false`\n * (if a node is explicitly NOT given), or a function that returns any of these\n * values.\n * @param {string} optionName\n * @param {Object} options\n * @param {boolean} [options.hasFallback] True if the option could be a selector string\n * and the option allows for a fallback scenario in the case where the selector is\n * valid but does not match a node (i.e. the queried node doesn't exist in the DOM).\n * @param {Array} [options.params] Params to pass to the option if it's a function.\n * @returns {undefined | null | false | HTMLElement | SVGElement} Returns\n * `undefined` if the option is not specified; `null` if the option didn't resolve\n * to a node but `options.hasFallback=true`, `false` if the option resolved to `false`\n * (node explicitly not given); otherwise, the resolved DOM node.\n * @throws {Error} If the option is set, not `false`, and is not, or does not\n * resolve to a node, unless the option is a selector string and `options.hasFallback=true`.\n */\n var getNodeForOption = function getNodeForOption(optionName) {\n var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},\n _ref2$hasFallback = _ref2.hasFallback,\n hasFallback = _ref2$hasFallback === void 0 ? false : _ref2$hasFallback,\n _ref2$params = _ref2.params,\n params = _ref2$params === void 0 ? [] : _ref2$params;\n var optionValue = config[optionName];\n if (typeof optionValue === 'function') {\n optionValue = optionValue.apply(void 0, _toConsumableArray(params));\n }\n if (optionValue === true) {\n optionValue = undefined; // use default value\n }\n if (!optionValue) {\n if (optionValue === undefined || optionValue === false) {\n return optionValue;\n }\n // else, empty string (invalid), null (invalid), 0 (invalid)\n\n throw new Error(\"`\".concat(optionName, \"` was specified but was not a node, or did not return a node\"));\n }\n var node = optionValue; // could be HTMLElement, SVGElement, or non-empty string at this point\n\n if (typeof optionValue === 'string') {\n try {\n node = doc.querySelector(optionValue); // resolve to node, or null if fails\n } catch (err) {\n throw new Error(\"`\".concat(optionName, \"` appears to be an invalid selector; error=\\\"\").concat(err.message, \"\\\"\"));\n }\n if (!node) {\n if (!hasFallback) {\n throw new Error(\"`\".concat(optionName, \"` as selector refers to no known node\"));\n }\n // else, `node` MUST be `null` because that's what `Document.querySelector()` returns\n // if the selector is valid but doesn't match anything\n }\n }\n return node;\n };\n var getInitialFocusNode = function getInitialFocusNode() {\n var node = getNodeForOption('initialFocus', {\n hasFallback: true\n });\n\n // false explicitly indicates we want no initialFocus at all\n if (node === false) {\n return false;\n }\n if (node === undefined || node && !isFocusable(node, config.tabbableOptions)) {\n // option not specified nor focusable: use fallback options\n if (findContainerIndex(doc.activeElement) >= 0) {\n node = doc.activeElement;\n } else {\n var firstTabbableGroup = state.tabbableGroups[0];\n var firstTabbableNode = firstTabbableGroup && firstTabbableGroup.firstTabbableNode;\n\n // NOTE: `fallbackFocus` option function cannot return `false` (not supported)\n node = firstTabbableNode || getNodeForOption('fallbackFocus');\n }\n } else if (node === null) {\n // option is a VALID selector string that doesn't yield a node: use the `fallbackFocus`\n // option instead of the default behavior when the option isn't specified at all\n node = getNodeForOption('fallbackFocus');\n }\n if (!node) {\n throw new Error('Your focus-trap needs to have at least one focusable element');\n }\n return node;\n };\n var updateTabbableNodes = function updateTabbableNodes() {\n state.containerGroups = state.containers.map(function (container) {\n var tabbableNodes = tabbable(container, config.tabbableOptions);\n\n // NOTE: if we have tabbable nodes, we must have focusable nodes; focusable nodes\n // are a superset of tabbable nodes since nodes with negative `tabindex` attributes\n // are focusable but not tabbable\n var focusableNodes = focusable(container, config.tabbableOptions);\n var firstTabbableNode = tabbableNodes.length > 0 ? tabbableNodes[0] : undefined;\n var lastTabbableNode = tabbableNodes.length > 0 ? tabbableNodes[tabbableNodes.length - 1] : undefined;\n var firstDomTabbableNode = focusableNodes.find(function (node) {\n return isTabbable(node);\n });\n var lastDomTabbableNode = focusableNodes.slice().reverse().find(function (node) {\n return isTabbable(node);\n });\n var posTabIndexesFound = !!tabbableNodes.find(function (node) {\n return getTabIndex(node) > 0;\n });\n return {\n container: container,\n tabbableNodes: tabbableNodes,\n focusableNodes: focusableNodes,\n /** True if at least one node with positive `tabindex` was found in this container. */\n posTabIndexesFound: posTabIndexesFound,\n /** First tabbable node in container, __tabindex__ order; `undefined` if none. */\n firstTabbableNode: firstTabbableNode,\n /** Last tabbable node in container, __tabindex__ order; `undefined` if none. */\n lastTabbableNode: lastTabbableNode,\n // NOTE: DOM order is NOT NECESSARILY \"document position\" order, but figuring that out\n // would require more than just https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition\n // because that API doesn't work with Shadow DOM as well as it should (@see\n // https://github.com/whatwg/dom/issues/320) and since this first/last is only needed, so far,\n // to address an edge case related to positive tabindex support, this seems like a much easier,\n // \"close enough most of the time\" alternative for positive tabindexes which should generally\n // be avoided anyway...\n /** First tabbable node in container, __DOM__ order; `undefined` if none. */\n firstDomTabbableNode: firstDomTabbableNode,\n /** Last tabbable node in container, __DOM__ order; `undefined` if none. */\n lastDomTabbableNode: lastDomTabbableNode,\n /**\n * Finds the __tabbable__ node that follows the given node in the specified direction,\n * in this container, if any.\n * @param {HTMLElement} node\n * @param {boolean} [forward] True if going in forward tab order; false if going\n * in reverse.\n * @returns {HTMLElement|undefined} The next tabbable node, if any.\n */\n nextTabbableNode: function nextTabbableNode(node) {\n var forward = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n var nodeIdx = tabbableNodes.indexOf(node);\n if (nodeIdx < 0) {\n // either not tabbable nor focusable, or was focused but not tabbable (negative tabindex):\n // since `node` should at least have been focusable, we assume that's the case and mimic\n // what browsers do, which is set focus to the next node in __document position order__,\n // regardless of positive tabindexes, if any -- and for reasons explained in the NOTE\n // above related to `firstDomTabbable` and `lastDomTabbable` properties, we fall back to\n // basic DOM order\n if (forward) {\n return focusableNodes.slice(focusableNodes.indexOf(node) + 1).find(function (el) {\n return isTabbable(el);\n });\n }\n return focusableNodes.slice(0, focusableNodes.indexOf(node)).reverse().find(function (el) {\n return isTabbable(el);\n });\n }\n return tabbableNodes[nodeIdx + (forward ? 1 : -1)];\n }\n };\n });\n state.tabbableGroups = state.containerGroups.filter(function (group) {\n return group.tabbableNodes.length > 0;\n });\n\n // throw if no groups have tabbable nodes and we don't have a fallback focus node either\n if (state.tabbableGroups.length <= 0 && !getNodeForOption('fallbackFocus') // returning false not supported for this option\n ) {\n throw new Error('Your focus-trap must have at least one container with at least one tabbable node in it at all times');\n }\n\n // NOTE: Positive tabindexes are only properly supported in single-container traps because\n // doing it across multiple containers where tabindexes could be all over the place\n // would require Tabbable to support multiple containers, would require additional\n // specialized Shadow DOM support, and would require Tabbable's multi-container support\n // to look at those containers in document position order rather than user-provided\n // order (as they are treated in Focus-trap, for legacy reasons). See discussion on\n // https://github.com/focus-trap/focus-trap/issues/375 for more details.\n if (state.containerGroups.find(function (g) {\n return g.posTabIndexesFound;\n }) && state.containerGroups.length > 1) {\n throw new Error(\"At least one node with a positive tabindex was found in one of your focus-trap's multiple containers. Positive tabindexes are only supported in single-container focus-traps.\");\n }\n };\n\n /**\n * Gets the current activeElement. If it's a web-component and has open shadow-root\n * it will recursively search inside shadow roots for the \"true\" activeElement.\n *\n * @param {Document | ShadowRoot} el\n *\n * @returns {HTMLElement} The element that currently has the focus\n **/\n var _getActiveElement = function getActiveElement(el) {\n var activeElement = el.activeElement;\n if (!activeElement) {\n return;\n }\n if (activeElement.shadowRoot && activeElement.shadowRoot.activeElement !== null) {\n return _getActiveElement(activeElement.shadowRoot);\n }\n return activeElement;\n };\n var _tryFocus = function tryFocus(node) {\n if (node === false) {\n return;\n }\n if (node === _getActiveElement(document)) {\n return;\n }\n if (!node || !node.focus) {\n _tryFocus(getInitialFocusNode());\n return;\n }\n node.focus({\n preventScroll: !!config.preventScroll\n });\n // NOTE: focus() API does not trigger focusIn event so set MRU node manually\n state.mostRecentlyFocusedNode = node;\n if (isSelectableInput(node)) {\n node.select();\n }\n };\n var getReturnFocusNode = function getReturnFocusNode(previousActiveElement) {\n var node = getNodeForOption('setReturnFocus', {\n params: [previousActiveElement]\n });\n return node ? node : node === false ? false : previousActiveElement;\n };\n\n /**\n * Finds the next node (in either direction) where focus should move according to a\n * keyboard focus-in event.\n * @param {Object} params\n * @param {Node} [params.target] Known target __from which__ to navigate, if any.\n * @param {KeyboardEvent|FocusEvent} [params.event] Event to use if `target` isn't known (event\n * will be used to determine the `target`). Ignored if `target` is specified.\n * @param {boolean} [params.isBackward] True if focus should move backward.\n * @returns {Node|undefined} The next node, or `undefined` if a next node couldn't be\n * determined given the current state of the trap.\n */\n var findNextNavNode = function findNextNavNode(_ref3) {\n var target = _ref3.target,\n event = _ref3.event,\n _ref3$isBackward = _ref3.isBackward,\n isBackward = _ref3$isBackward === void 0 ? false : _ref3$isBackward;\n target = target || getActualTarget(event);\n updateTabbableNodes();\n var destinationNode = null;\n if (state.tabbableGroups.length > 0) {\n // make sure the target is actually contained in a group\n // NOTE: the target may also be the container itself if it's focusable\n // with tabIndex='-1' and was given initial focus\n var containerIndex = findContainerIndex(target, event);\n var containerGroup = containerIndex >= 0 ? state.containerGroups[containerIndex] : undefined;\n if (containerIndex < 0) {\n // target not found in any group: quite possible focus has escaped the trap,\n // so bring it back into...\n if (isBackward) {\n // ...the last node in the last group\n destinationNode = state.tabbableGroups[state.tabbableGroups.length - 1].lastTabbableNode;\n } else {\n // ...the first node in the first group\n destinationNode = state.tabbableGroups[0].firstTabbableNode;\n }\n } else if (isBackward) {\n // REVERSE\n\n // is the target the first tabbable node in a group?\n var startOfGroupIndex = findIndex(state.tabbableGroups, function (_ref4) {\n var firstTabbableNode = _ref4.firstTabbableNode;\n return target === firstTabbableNode;\n });\n if (startOfGroupIndex < 0 && (containerGroup.container === target || isFocusable(target, config.tabbableOptions) && !isTabbable(target, config.tabbableOptions) && !containerGroup.nextTabbableNode(target, false))) {\n // an exception case where the target is either the container itself, or\n // a non-tabbable node that was given focus (i.e. tabindex is negative\n // and user clicked on it or node was programmatically given focus)\n // and is not followed by any other tabbable node, in which\n // case, we should handle shift+tab as if focus were on the container's\n // first tabbable node, and go to the last tabbable node of the LAST group\n startOfGroupIndex = containerIndex;\n }\n if (startOfGroupIndex >= 0) {\n // YES: then shift+tab should go to the last tabbable node in the\n // previous group (and wrap around to the last tabbable node of\n // the LAST group if it's the first tabbable node of the FIRST group)\n var destinationGroupIndex = startOfGroupIndex === 0 ? state.tabbableGroups.length - 1 : startOfGroupIndex - 1;\n var destinationGroup = state.tabbableGroups[destinationGroupIndex];\n destinationNode = getTabIndex(target) >= 0 ? destinationGroup.lastTabbableNode : destinationGroup.lastDomTabbableNode;\n } else if (!isTabEvent(event)) {\n // user must have customized the nav keys so we have to move focus manually _within_\n // the active group: do this based on the order determined by tabbable()\n destinationNode = containerGroup.nextTabbableNode(target, false);\n }\n } else {\n // FORWARD\n\n // is the target the last tabbable node in a group?\n var lastOfGroupIndex = findIndex(state.tabbableGroups, function (_ref5) {\n var lastTabbableNode = _ref5.lastTabbableNode;\n return target === lastTabbableNode;\n });\n if (lastOfGroupIndex < 0 && (containerGroup.container === target || isFocusable(target, config.tabbableOptions) && !isTabbable(target, config.tabbableOptions) && !containerGroup.nextTabbableNode(target))) {\n // an exception case where the target is the container itself, or\n // a non-tabbable node that was given focus (i.e. tabindex is negative\n // and user clicked on it or node was programmatically given focus)\n // and is not followed by any other tabbable node, in which\n // case, we should handle tab as if focus were on the container's\n // last tabbable node, and go to the first tabbable node of the FIRST group\n lastOfGroupIndex = containerIndex;\n }\n if (lastOfGroupIndex >= 0) {\n // YES: then tab should go to the first tabbable node in the next\n // group (and wrap around to the first tabbable node of the FIRST\n // group if it's the last tabbable node of the LAST group)\n var _destinationGroupIndex = lastOfGroupIndex === state.tabbableGroups.length - 1 ? 0 : lastOfGroupIndex + 1;\n var _destinationGroup = state.tabbableGroups[_destinationGroupIndex];\n destinationNode = getTabIndex(target) >= 0 ? _destinationGroup.firstTabbableNode : _destinationGroup.firstDomTabbableNode;\n } else if (!isTabEvent(event)) {\n // user must have customized the nav keys so we have to move focus manually _within_\n // the active group: do this based on the order determined by tabbable()\n destinationNode = containerGroup.nextTabbableNode(target);\n }\n }\n } else {\n // no groups available\n // NOTE: the fallbackFocus option does not support returning false to opt-out\n destinationNode = getNodeForOption('fallbackFocus');\n }\n return destinationNode;\n };\n\n // This needs to be done on mousedown and touchstart instead of click\n // so that it precedes the focus event.\n var checkPointerDown = function checkPointerDown(e) {\n var target = getActualTarget(e);\n if (findContainerIndex(target, e) >= 0) {\n // allow the click since it ocurred inside the trap\n return;\n }\n if (valueOrHandler(config.clickOutsideDeactivates, e)) {\n // immediately deactivate the trap\n trap.deactivate({\n // NOTE: by setting `returnFocus: false`, deactivate() will do nothing,\n // which will result in the outside click setting focus to the node\n // that was clicked (and if not focusable, to \"nothing\"); by setting\n // `returnFocus: true`, we'll attempt to re-focus the node originally-focused\n // on activation (or the configured `setReturnFocus` node), whether the\n // outside click was on a focusable node or not\n returnFocus: config.returnFocusOnDeactivate\n });\n return;\n }\n\n // This is needed for mobile devices.\n // (If we'll only let `click` events through,\n // then on mobile they will be blocked anyways if `touchstart` is blocked.)\n if (valueOrHandler(config.allowOutsideClick, e)) {\n // allow the click outside the trap to take place\n return;\n }\n\n // otherwise, prevent the click\n e.preventDefault();\n };\n\n // In case focus escapes the trap for some strange reason, pull it back in.\n // NOTE: the focusIn event is NOT cancelable, so if focus escapes, it may cause unexpected\n // scrolling if the node that got focused was out of view; there's nothing we can do to\n // prevent that from happening by the time we discover that focus escaped\n var checkFocusIn = function checkFocusIn(event) {\n var target = getActualTarget(event);\n var targetContained = findContainerIndex(target, event) >= 0;\n\n // In Firefox when you Tab out of an iframe the Document is briefly focused.\n if (targetContained || target instanceof Document) {\n if (targetContained) {\n state.mostRecentlyFocusedNode = target;\n }\n } else {\n // escaped! pull it back in to where it just left\n event.stopImmediatePropagation();\n\n // focus will escape if the MRU node had a positive tab index and user tried to nav forward;\n // it will also escape if the MRU node had a 0 tab index and user tried to nav backward\n // toward a node with a positive tab index\n var nextNode; // next node to focus, if we find one\n var navAcrossContainers = true;\n if (state.mostRecentlyFocusedNode) {\n if (getTabIndex(state.mostRecentlyFocusedNode) > 0) {\n // MRU container index must be >=0 otherwise we wouldn't have it as an MRU node...\n var mruContainerIdx = findContainerIndex(state.mostRecentlyFocusedNode);\n // there MAY not be any tabbable nodes in the container if there are at least 2 containers\n // and the MRU node is focusable but not tabbable (focus-trap requires at least 1 container\n // with at least one tabbable node in order to function, so this could be the other container\n // with nothing tabbable in it)\n var tabbableNodes = state.containerGroups[mruContainerIdx].tabbableNodes;\n if (tabbableNodes.length > 0) {\n // MRU tab index MAY not be found if the MRU node is focusable but not tabbable\n var mruTabIdx = tabbableNodes.findIndex(function (node) {\n return node === state.mostRecentlyFocusedNode;\n });\n if (mruTabIdx >= 0) {\n if (config.isKeyForward(state.recentNavEvent)) {\n if (mruTabIdx + 1 < tabbableNodes.length) {\n nextNode = tabbableNodes[mruTabIdx + 1];\n navAcrossContainers = false;\n }\n // else, don't wrap within the container as focus should move to next/previous\n // container\n } else {\n if (mruTabIdx - 1 >= 0) {\n nextNode = tabbableNodes[mruTabIdx - 1];\n navAcrossContainers = false;\n }\n // else, don't wrap within the container as focus should move to next/previous\n // container\n }\n // else, don't find in container order without considering direction too\n }\n }\n // else, no tabbable nodes in that container (which means we must have at least one other\n // container with at least one tabbable node in it, otherwise focus-trap would've thrown\n // an error the last time updateTabbableNodes() was run): find next node among all known\n // containers\n } else {\n // check to see if there's at least one tabbable node with a positive tab index inside\n // the trap because focus seems to escape when navigating backward from a tabbable node\n // with tabindex=0 when this is the case (instead of wrapping to the tabbable node with\n // the greatest positive tab index like it should)\n if (!state.containerGroups.some(function (g) {\n return g.tabbableNodes.some(function (n) {\n return getTabIndex(n) > 0;\n });\n })) {\n // no containers with tabbable nodes with positive tab indexes which means the focus\n // escaped for some other reason and we should just execute the fallback to the\n // MRU node or initial focus node, if any\n navAcrossContainers = false;\n }\n }\n } else {\n // no MRU node means we're likely in some initial condition when the trap has just\n // been activated and initial focus hasn't been given yet, in which case we should\n // fall through to trying to focus the initial focus node, which is what should\n // happen below at this point in the logic\n navAcrossContainers = false;\n }\n if (navAcrossContainers) {\n nextNode = findNextNavNode({\n // move FROM the MRU node, not event-related node (which will be the node that is\n // outside the trap causing the focus escape we're trying to fix)\n target: state.mostRecentlyFocusedNode,\n isBackward: config.isKeyBackward(state.recentNavEvent)\n });\n }\n if (nextNode) {\n _tryFocus(nextNode);\n } else {\n _tryFocus(state.mostRecentlyFocusedNode || getInitialFocusNode());\n }\n }\n state.recentNavEvent = undefined; // clear\n };\n\n // Hijack key nav events on the first and last focusable nodes of the trap,\n // in order to prevent focus from escaping. If it escapes for even a\n // moment it can end up scrolling the page and causing confusion so we\n // kind of need to capture the action at the keydown phase.\n var checkKeyNav = function checkKeyNav(event) {\n var isBackward = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n state.recentNavEvent = event;\n var destinationNode = findNextNavNode({\n event: event,\n isBackward: isBackward\n });\n if (destinationNode) {\n if (isTabEvent(event)) {\n // since tab natively moves focus, we wouldn't have a destination node unless we\n // were on the edge of a container and had to move to the next/previous edge, in\n // which case we want to prevent default to keep the browser from moving focus\n // to where it normally would\n event.preventDefault();\n }\n _tryFocus(destinationNode);\n }\n // else, let the browser take care of [shift+]tab and move the focus\n };\n var checkTabKey = function checkTabKey(event) {\n if (config.isKeyForward(event) || config.isKeyBackward(event)) {\n checkKeyNav(event, config.isKeyBackward(event));\n }\n };\n\n // we use a different event phase for the Escape key to allow canceling the event and checking for this in escapeDeactivates\n var checkEscapeKey = function checkEscapeKey(event) {\n if (isEscapeEvent(event) && valueOrHandler(config.escapeDeactivates, event) !== false) {\n event.preventDefault();\n trap.deactivate();\n }\n };\n var checkClick = function checkClick(e) {\n var target = getActualTarget(e);\n if (findContainerIndex(target, e) >= 0) {\n return;\n }\n if (valueOrHandler(config.clickOutsideDeactivates, e)) {\n return;\n }\n if (valueOrHandler(config.allowOutsideClick, e)) {\n return;\n }\n e.preventDefault();\n e.stopImmediatePropagation();\n };\n\n //\n // EVENT LISTENERS\n //\n\n var addListeners = function addListeners() {\n if (!state.active) {\n return;\n }\n\n // There can be only one listening focus trap at a time\n activeFocusTraps.activateTrap(trapStack, trap);\n\n // Delay ensures that the focused element doesn't capture the event\n // that caused the focus trap activation.\n state.delayInitialFocusTimer = config.delayInitialFocus ? delay(function () {\n _tryFocus(getInitialFocusNode());\n }) : _tryFocus(getInitialFocusNode());\n doc.addEventListener('focusin', checkFocusIn, true);\n doc.addEventListener('mousedown', checkPointerDown, {\n capture: true,\n passive: false\n });\n doc.addEventListener('touchstart', checkPointerDown, {\n capture: true,\n passive: false\n });\n doc.addEventListener('click', checkClick, {\n capture: true,\n passive: false\n });\n doc.addEventListener('keydown', checkTabKey, {\n capture: true,\n passive: false\n });\n doc.addEventListener('keydown', checkEscapeKey);\n return trap;\n };\n var removeListeners = function removeListeners() {\n if (!state.active) {\n return;\n }\n doc.removeEventListener('focusin', checkFocusIn, true);\n doc.removeEventListener('mousedown', checkPointerDown, true);\n doc.removeEventListener('touchstart', checkPointerDown, true);\n doc.removeEventListener('click', checkClick, true);\n doc.removeEventListener('keydown', checkTabKey, true);\n doc.removeEventListener('keydown', checkEscapeKey);\n return trap;\n };\n\n //\n // MUTATION OBSERVER\n //\n\n var checkDomRemoval = function checkDomRemoval(mutations) {\n var isFocusedNodeRemoved = mutations.some(function (mutation) {\n var removedNodes = Array.from(mutation.removedNodes);\n return removedNodes.some(function (node) {\n return node === state.mostRecentlyFocusedNode;\n });\n });\n\n // If the currently focused is removed then browsers will move focus to the\n // element. If this happens, try to move focus back into the trap.\n if (isFocusedNodeRemoved) {\n _tryFocus(getInitialFocusNode());\n }\n };\n\n // Use MutationObserver - if supported - to detect if focused node is removed\n // from the DOM.\n var mutationObserver = typeof window !== 'undefined' && 'MutationObserver' in window ? new MutationObserver(checkDomRemoval) : undefined;\n var updateObservedNodes = function updateObservedNodes() {\n if (!mutationObserver) {\n return;\n }\n mutationObserver.disconnect();\n if (state.active && !state.paused) {\n state.containers.map(function (container) {\n mutationObserver.observe(container, {\n subtree: true,\n childList: true\n });\n });\n }\n };\n\n //\n // TRAP DEFINITION\n //\n\n trap = {\n get active() {\n return state.active;\n },\n get paused() {\n return state.paused;\n },\n activate: function activate(activateOptions) {\n if (state.active) {\n return this;\n }\n var onActivate = getOption(activateOptions, 'onActivate');\n var onPostActivate = getOption(activateOptions, 'onPostActivate');\n var checkCanFocusTrap = getOption(activateOptions, 'checkCanFocusTrap');\n if (!checkCanFocusTrap) {\n updateTabbableNodes();\n }\n state.active = true;\n state.paused = false;\n state.nodeFocusedBeforeActivation = doc.activeElement;\n onActivate === null || onActivate === void 0 || onActivate();\n var finishActivation = function finishActivation() {\n if (checkCanFocusTrap) {\n updateTabbableNodes();\n }\n addListeners();\n updateObservedNodes();\n onPostActivate === null || onPostActivate === void 0 || onPostActivate();\n };\n if (checkCanFocusTrap) {\n checkCanFocusTrap(state.containers.concat()).then(finishActivation, finishActivation);\n return this;\n }\n finishActivation();\n return this;\n },\n deactivate: function deactivate(deactivateOptions) {\n if (!state.active) {\n return this;\n }\n var options = _objectSpread2({\n onDeactivate: config.onDeactivate,\n onPostDeactivate: config.onPostDeactivate,\n checkCanReturnFocus: config.checkCanReturnFocus\n }, deactivateOptions);\n clearTimeout(state.delayInitialFocusTimer); // noop if undefined\n state.delayInitialFocusTimer = undefined;\n removeListeners();\n state.active = false;\n state.paused = false;\n updateObservedNodes();\n activeFocusTraps.deactivateTrap(trapStack, trap);\n var onDeactivate = getOption(options, 'onDeactivate');\n var onPostDeactivate = getOption(options, 'onPostDeactivate');\n var checkCanReturnFocus = getOption(options, 'checkCanReturnFocus');\n var returnFocus = getOption(options, 'returnFocus', 'returnFocusOnDeactivate');\n onDeactivate === null || onDeactivate === void 0 || onDeactivate();\n var finishDeactivation = function finishDeactivation() {\n delay(function () {\n if (returnFocus) {\n _tryFocus(getReturnFocusNode(state.nodeFocusedBeforeActivation));\n }\n onPostDeactivate === null || onPostDeactivate === void 0 || onPostDeactivate();\n });\n };\n if (returnFocus && checkCanReturnFocus) {\n checkCanReturnFocus(getReturnFocusNode(state.nodeFocusedBeforeActivation)).then(finishDeactivation, finishDeactivation);\n return this;\n }\n finishDeactivation();\n return this;\n },\n pause: function pause(pauseOptions) {\n if (state.paused || !state.active) {\n return this;\n }\n var onPause = getOption(pauseOptions, 'onPause');\n var onPostPause = getOption(pauseOptions, 'onPostPause');\n state.paused = true;\n onPause === null || onPause === void 0 || onPause();\n removeListeners();\n updateObservedNodes();\n onPostPause === null || onPostPause === void 0 || onPostPause();\n return this;\n },\n unpause: function unpause(unpauseOptions) {\n if (!state.paused || !state.active) {\n return this;\n }\n var onUnpause = getOption(unpauseOptions, 'onUnpause');\n var onPostUnpause = getOption(unpauseOptions, 'onPostUnpause');\n state.paused = false;\n onUnpause === null || onUnpause === void 0 || onUnpause();\n updateTabbableNodes();\n addListeners();\n updateObservedNodes();\n onPostUnpause === null || onPostUnpause === void 0 || onPostUnpause();\n return this;\n },\n updateContainerElements: function updateContainerElements(containerElements) {\n var elementsAsArray = [].concat(containerElements).filter(Boolean);\n state.containers = elementsAsArray.map(function (element) {\n return typeof element === 'string' ? doc.querySelector(element) : element;\n });\n if (state.active) {\n updateTabbableNodes();\n }\n updateObservedNodes();\n return this;\n }\n };\n\n // initialize container elements\n trap.updateContainerElements(elements);\n return trap;\n};\n\nexport { createFocusTrap };\n//# sourceMappingURL=focus-trap.esm.js.map\n","'use strict';\n\nvar reactIs = require('react-is');\n\n/**\n * Copyright 2015, Yahoo! Inc.\n * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.\n */\nvar REACT_STATICS = {\n childContextTypes: true,\n contextType: true,\n contextTypes: true,\n defaultProps: true,\n displayName: true,\n getDefaultProps: true,\n getDerivedStateFromError: true,\n getDerivedStateFromProps: true,\n mixins: true,\n propTypes: true,\n type: true\n};\nvar KNOWN_STATICS = {\n name: true,\n length: true,\n prototype: true,\n caller: true,\n callee: true,\n arguments: true,\n arity: true\n};\nvar FORWARD_REF_STATICS = {\n '$$typeof': true,\n render: true,\n defaultProps: true,\n displayName: true,\n propTypes: true\n};\nvar MEMO_STATICS = {\n '$$typeof': true,\n compare: true,\n defaultProps: true,\n displayName: true,\n propTypes: true,\n type: true\n};\nvar TYPE_STATICS = {};\nTYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;\nTYPE_STATICS[reactIs.Memo] = MEMO_STATICS;\n\nfunction getStatics(component) {\n // React v16.11 and below\n if (reactIs.isMemo(component)) {\n return MEMO_STATICS;\n } // React v16.12 and above\n\n\n return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;\n}\n\nvar defineProperty = Object.defineProperty;\nvar getOwnPropertyNames = Object.getOwnPropertyNames;\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nvar getPrototypeOf = Object.getPrototypeOf;\nvar objectPrototype = Object.prototype;\nfunction hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {\n if (typeof sourceComponent !== 'string') {\n // don't hoist over string (html) components\n if (objectPrototype) {\n var inheritedComponent = getPrototypeOf(sourceComponent);\n\n if (inheritedComponent && inheritedComponent !== objectPrototype) {\n hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);\n }\n }\n\n var keys = getOwnPropertyNames(sourceComponent);\n\n if (getOwnPropertySymbols) {\n keys = keys.concat(getOwnPropertySymbols(sourceComponent));\n }\n\n var targetStatics = getStatics(targetComponent);\n var sourceStatics = getStatics(sourceComponent);\n\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n\n if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {\n var descriptor = getOwnPropertyDescriptor(sourceComponent, key);\n\n try {\n // Avoid failures from read-only properties\n defineProperty(targetComponent, key, descriptor);\n } catch (e) {}\n }\n }\n }\n\n return targetComponent;\n}\n\nmodule.exports = hoistNonReactStatics;\n","/*\nCopyright (c) 2014, Yahoo! Inc. All rights reserved.\nCopyrights licensed under the New BSD License.\nSee the accompanying LICENSE file for terms.\n*/\nimport { __assign, __rest, __spreadArray } from \"tslib\";\nimport { memoize, strategies } from '@formatjs/fast-memoize';\nimport { parse, } from '@formatjs/icu-messageformat-parser';\nimport { formatToParts, PART_TYPE, } from './formatters';\n// -- MessageFormat --------------------------------------------------------\nfunction mergeConfig(c1, c2) {\n if (!c2) {\n return c1;\n }\n return __assign(__assign(__assign({}, (c1 || {})), (c2 || {})), Object.keys(c1).reduce(function (all, k) {\n all[k] = __assign(__assign({}, c1[k]), (c2[k] || {}));\n return all;\n }, {}));\n}\nfunction mergeConfigs(defaultConfig, configs) {\n if (!configs) {\n return defaultConfig;\n }\n return Object.keys(defaultConfig).reduce(function (all, k) {\n all[k] = mergeConfig(defaultConfig[k], configs[k]);\n return all;\n }, __assign({}, defaultConfig));\n}\nfunction createFastMemoizeCache(store) {\n return {\n create: function () {\n return {\n get: function (key) {\n return store[key];\n },\n set: function (key, value) {\n store[key] = value;\n },\n };\n },\n };\n}\nfunction createDefaultFormatters(cache) {\n if (cache === void 0) { cache = {\n number: {},\n dateTime: {},\n pluralRules: {},\n }; }\n return {\n getNumberFormat: memoize(function () {\n var _a;\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return new ((_a = Intl.NumberFormat).bind.apply(_a, __spreadArray([void 0], args, false)))();\n }, {\n cache: createFastMemoizeCache(cache.number),\n strategy: strategies.variadic,\n }),\n getDateTimeFormat: memoize(function () {\n var _a;\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return new ((_a = Intl.DateTimeFormat).bind.apply(_a, __spreadArray([void 0], args, false)))();\n }, {\n cache: createFastMemoizeCache(cache.dateTime),\n strategy: strategies.variadic,\n }),\n getPluralRules: memoize(function () {\n var _a;\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return new ((_a = Intl.PluralRules).bind.apply(_a, __spreadArray([void 0], args, false)))();\n }, {\n cache: createFastMemoizeCache(cache.pluralRules),\n strategy: strategies.variadic,\n }),\n };\n}\nvar IntlMessageFormat = /** @class */ (function () {\n function IntlMessageFormat(message, locales, overrideFormats, opts) {\n if (locales === void 0) { locales = IntlMessageFormat.defaultLocale; }\n var _this = this;\n this.formatterCache = {\n number: {},\n dateTime: {},\n pluralRules: {},\n };\n this.format = function (values) {\n var parts = _this.formatToParts(values);\n // Hot path for straight simple msg translations\n if (parts.length === 1) {\n return parts[0].value;\n }\n var result = parts.reduce(function (all, part) {\n if (!all.length ||\n part.type !== PART_TYPE.literal ||\n typeof all[all.length - 1] !== 'string') {\n all.push(part.value);\n }\n else {\n all[all.length - 1] += part.value;\n }\n return all;\n }, []);\n if (result.length <= 1) {\n return result[0] || '';\n }\n return result;\n };\n this.formatToParts = function (values) {\n return formatToParts(_this.ast, _this.locales, _this.formatters, _this.formats, values, undefined, _this.message);\n };\n this.resolvedOptions = function () {\n var _a;\n return ({\n locale: ((_a = _this.resolvedLocale) === null || _a === void 0 ? void 0 : _a.toString()) ||\n Intl.NumberFormat.supportedLocalesOf(_this.locales)[0],\n });\n };\n this.getAst = function () { return _this.ast; };\n // Defined first because it's used to build the format pattern.\n this.locales = locales;\n this.resolvedLocale = IntlMessageFormat.resolveLocale(locales);\n if (typeof message === 'string') {\n this.message = message;\n if (!IntlMessageFormat.__parse) {\n throw new TypeError('IntlMessageFormat.__parse must be set to process `message` of type `string`');\n }\n var _a = opts || {}, formatters = _a.formatters, parseOpts = __rest(_a, [\"formatters\"]);\n // Parse string messages into an AST.\n this.ast = IntlMessageFormat.__parse(message, __assign(__assign({}, parseOpts), { locale: this.resolvedLocale }));\n }\n else {\n this.ast = message;\n }\n if (!Array.isArray(this.ast)) {\n throw new TypeError('A message must be provided as a String or AST.');\n }\n // Creates a new object with the specified `formats` merged with the default\n // formats.\n this.formats = mergeConfigs(IntlMessageFormat.formats, overrideFormats);\n this.formatters =\n (opts && opts.formatters) || createDefaultFormatters(this.formatterCache);\n }\n Object.defineProperty(IntlMessageFormat, \"defaultLocale\", {\n get: function () {\n if (!IntlMessageFormat.memoizedDefaultLocale) {\n IntlMessageFormat.memoizedDefaultLocale =\n new Intl.NumberFormat().resolvedOptions().locale;\n }\n return IntlMessageFormat.memoizedDefaultLocale;\n },\n enumerable: false,\n configurable: true\n });\n IntlMessageFormat.memoizedDefaultLocale = null;\n IntlMessageFormat.resolveLocale = function (locales) {\n if (typeof Intl.Locale === 'undefined') {\n return;\n }\n var supportedLocales = Intl.NumberFormat.supportedLocalesOf(locales);\n if (supportedLocales.length > 0) {\n return new Intl.Locale(supportedLocales[0]);\n }\n return new Intl.Locale(typeof locales === 'string' ? locales : locales[0]);\n };\n IntlMessageFormat.__parse = parse;\n // Default format options used as the prototype of the `formats` provided to the\n // constructor. These are used when constructing the internal Intl.NumberFormat\n // and Intl.DateTimeFormat instances.\n IntlMessageFormat.formats = {\n number: {\n integer: {\n maximumFractionDigits: 0,\n },\n currency: {\n style: 'currency',\n },\n percent: {\n style: 'percent',\n },\n },\n date: {\n short: {\n month: 'numeric',\n day: 'numeric',\n year: '2-digit',\n },\n medium: {\n month: 'short',\n day: 'numeric',\n year: 'numeric',\n },\n long: {\n month: 'long',\n day: 'numeric',\n year: 'numeric',\n },\n full: {\n weekday: 'long',\n month: 'long',\n day: 'numeric',\n year: 'numeric',\n },\n },\n time: {\n short: {\n hour: 'numeric',\n minute: 'numeric',\n },\n medium: {\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n },\n long: {\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n timeZoneName: 'short',\n },\n full: {\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n timeZoneName: 'short',\n },\n },\n };\n return IntlMessageFormat;\n}());\nexport { IntlMessageFormat };\n//# sourceMappingURL=core.js.map","import { __extends } from \"tslib\";\nexport var ErrorCode;\n(function (ErrorCode) {\n // When we have a placeholder but no value to format\n ErrorCode[\"MISSING_VALUE\"] = \"MISSING_VALUE\";\n // When value supplied is invalid\n ErrorCode[\"INVALID_VALUE\"] = \"INVALID_VALUE\";\n // When we need specific Intl API but it's not available\n ErrorCode[\"MISSING_INTL_API\"] = \"MISSING_INTL_API\";\n})(ErrorCode || (ErrorCode = {}));\nvar FormatError = /** @class */ (function (_super) {\n __extends(FormatError, _super);\n function FormatError(msg, code, originalMessage) {\n var _this = _super.call(this, msg) || this;\n _this.code = code;\n _this.originalMessage = originalMessage;\n return _this;\n }\n FormatError.prototype.toString = function () {\n return \"[formatjs Error: \".concat(this.code, \"] \").concat(this.message);\n };\n return FormatError;\n}(Error));\nexport { FormatError };\nvar InvalidValueError = /** @class */ (function (_super) {\n __extends(InvalidValueError, _super);\n function InvalidValueError(variableId, value, options, originalMessage) {\n return _super.call(this, \"Invalid values for \\\"\".concat(variableId, \"\\\": \\\"\").concat(value, \"\\\". Options are \\\"\").concat(Object.keys(options).join('\", \"'), \"\\\"\"), ErrorCode.INVALID_VALUE, originalMessage) || this;\n }\n return InvalidValueError;\n}(FormatError));\nexport { InvalidValueError };\nvar InvalidValueTypeError = /** @class */ (function (_super) {\n __extends(InvalidValueTypeError, _super);\n function InvalidValueTypeError(value, type, originalMessage) {\n return _super.call(this, \"Value for \\\"\".concat(value, \"\\\" must be of type \").concat(type), ErrorCode.INVALID_VALUE, originalMessage) || this;\n }\n return InvalidValueTypeError;\n}(FormatError));\nexport { InvalidValueTypeError };\nvar MissingValueError = /** @class */ (function (_super) {\n __extends(MissingValueError, _super);\n function MissingValueError(variableId, originalMessage) {\n return _super.call(this, \"The intl string context variable \\\"\".concat(variableId, \"\\\" was not provided to the string \\\"\").concat(originalMessage, \"\\\"\"), ErrorCode.MISSING_VALUE, originalMessage) || this;\n }\n return MissingValueError;\n}(FormatError));\nexport { MissingValueError };\n//# sourceMappingURL=error.js.map","import { isArgumentElement, isDateElement, isDateTimeSkeleton, isLiteralElement, isNumberElement, isNumberSkeleton, isPluralElement, isPoundElement, isSelectElement, isTagElement, isTimeElement, } from '@formatjs/icu-messageformat-parser';\nimport { ErrorCode, FormatError, InvalidValueError, InvalidValueTypeError, MissingValueError, } from './error';\nexport var PART_TYPE;\n(function (PART_TYPE) {\n PART_TYPE[PART_TYPE[\"literal\"] = 0] = \"literal\";\n PART_TYPE[PART_TYPE[\"object\"] = 1] = \"object\";\n})(PART_TYPE || (PART_TYPE = {}));\nfunction mergeLiteral(parts) {\n if (parts.length < 2) {\n return parts;\n }\n return parts.reduce(function (all, part) {\n var lastPart = all[all.length - 1];\n if (!lastPart ||\n lastPart.type !== PART_TYPE.literal ||\n part.type !== PART_TYPE.literal) {\n all.push(part);\n }\n else {\n lastPart.value += part.value;\n }\n return all;\n }, []);\n}\nexport function isFormatXMLElementFn(el) {\n return typeof el === 'function';\n}\n// TODO(skeleton): add skeleton support\nexport function formatToParts(els, locales, formatters, formats, values, currentPluralValue, \n// For debugging\noriginalMessage) {\n // Hot path for straight simple msg translations\n if (els.length === 1 && isLiteralElement(els[0])) {\n return [\n {\n type: PART_TYPE.literal,\n value: els[0].value,\n },\n ];\n }\n var result = [];\n for (var _i = 0, els_1 = els; _i < els_1.length; _i++) {\n var el = els_1[_i];\n // Exit early for string parts.\n if (isLiteralElement(el)) {\n result.push({\n type: PART_TYPE.literal,\n value: el.value,\n });\n continue;\n }\n // TODO: should this part be literal type?\n // Replace `#` in plural rules with the actual numeric value.\n if (isPoundElement(el)) {\n if (typeof currentPluralValue === 'number') {\n result.push({\n type: PART_TYPE.literal,\n value: formatters.getNumberFormat(locales).format(currentPluralValue),\n });\n }\n continue;\n }\n var varName = el.value;\n // Enforce that all required values are provided by the caller.\n if (!(values && varName in values)) {\n throw new MissingValueError(varName, originalMessage);\n }\n var value = values[varName];\n if (isArgumentElement(el)) {\n if (!value || typeof value === 'string' || typeof value === 'number') {\n value =\n typeof value === 'string' || typeof value === 'number'\n ? String(value)\n : '';\n }\n result.push({\n type: typeof value === 'string' ? PART_TYPE.literal : PART_TYPE.object,\n value: value,\n });\n continue;\n }\n // Recursively format plural and select parts' option — which can be a\n // nested pattern structure. The choosing of the option to use is\n // abstracted-by and delegated-to the part helper object.\n if (isDateElement(el)) {\n var style = typeof el.style === 'string'\n ? formats.date[el.style]\n : isDateTimeSkeleton(el.style)\n ? el.style.parsedOptions\n : undefined;\n result.push({\n type: PART_TYPE.literal,\n value: formatters\n .getDateTimeFormat(locales, style)\n .format(value),\n });\n continue;\n }\n if (isTimeElement(el)) {\n var style = typeof el.style === 'string'\n ? formats.time[el.style]\n : isDateTimeSkeleton(el.style)\n ? el.style.parsedOptions\n : formats.time.medium;\n result.push({\n type: PART_TYPE.literal,\n value: formatters\n .getDateTimeFormat(locales, style)\n .format(value),\n });\n continue;\n }\n if (isNumberElement(el)) {\n var style = typeof el.style === 'string'\n ? formats.number[el.style]\n : isNumberSkeleton(el.style)\n ? el.style.parsedOptions\n : undefined;\n if (style && style.scale) {\n value =\n value *\n (style.scale || 1);\n }\n result.push({\n type: PART_TYPE.literal,\n value: formatters\n .getNumberFormat(locales, style)\n .format(value),\n });\n continue;\n }\n if (isTagElement(el)) {\n var children = el.children, value_1 = el.value;\n var formatFn = values[value_1];\n if (!isFormatXMLElementFn(formatFn)) {\n throw new InvalidValueTypeError(value_1, 'function', originalMessage);\n }\n var parts = formatToParts(children, locales, formatters, formats, values, currentPluralValue);\n var chunks = formatFn(parts.map(function (p) { return p.value; }));\n if (!Array.isArray(chunks)) {\n chunks = [chunks];\n }\n result.push.apply(result, chunks.map(function (c) {\n return {\n type: typeof c === 'string' ? PART_TYPE.literal : PART_TYPE.object,\n value: c,\n };\n }));\n }\n if (isSelectElement(el)) {\n var opt = el.options[value] || el.options.other;\n if (!opt) {\n throw new InvalidValueError(el.value, value, Object.keys(el.options), originalMessage);\n }\n result.push.apply(result, formatToParts(opt.value, locales, formatters, formats, values));\n continue;\n }\n if (isPluralElement(el)) {\n var opt = el.options[\"=\".concat(value)];\n if (!opt) {\n if (!Intl.PluralRules) {\n throw new FormatError(\"Intl.PluralRules is not available in this environment.\\nTry polyfilling it using \\\"@formatjs/intl-pluralrules\\\"\\n\", ErrorCode.MISSING_INTL_API, originalMessage);\n }\n var rule = formatters\n .getPluralRules(locales, { type: el.pluralType })\n .select(value - (el.offset || 0));\n opt = el.options[rule] || el.options.other;\n }\n if (!opt) {\n throw new InvalidValueError(el.value, value, Object.keys(el.options), originalMessage);\n }\n result.push.apply(result, formatToParts(opt.value, locales, formatters, formats, values, value - (el.offset || 0)));\n continue;\n }\n }\n return mergeLiteral(result);\n}\n//# sourceMappingURL=formatters.js.map","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\n/**\n * Use invariant() to assert state which your program assumes to be true.\n *\n * Provide sprintf-style format (only %s is supported) and arguments\n * to provide information about what broke and what you were\n * expecting.\n *\n * The invariant message will be stripped in production, but the invariant\n * will remain to ensure logic does not differ in production.\n */\n\nvar invariant = function(condition, format, a, b, c, d, e, f) {\n if (process.env.NODE_ENV !== 'production') {\n if (format === undefined) {\n throw new Error('invariant requires an error message argument');\n }\n }\n\n if (!condition) {\n var error;\n if (format === undefined) {\n error = new Error(\n 'Minified exception occurred; use the non-minified dev environment ' +\n 'for the full error message and additional helpful warnings.'\n );\n } else {\n var args = [a, b, c, d, e, f];\n var argIndex = 0;\n error = new Error(\n format.replace(/%s/g, function() { return args[argIndex++]; })\n );\n error.name = 'Invariant Violation';\n }\n\n error.framesToPop = 1; // we don't care about invariant's own frame\n throw error;\n }\n};\n\nmodule.exports = invariant;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView');\n\nmodule.exports = DataView;\n","var hashClear = require('./_hashClear'),\n hashDelete = require('./_hashDelete'),\n hashGet = require('./_hashGet'),\n hashHas = require('./_hashHas'),\n hashSet = require('./_hashSet');\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nmodule.exports = Hash;\n","var listCacheClear = require('./_listCacheClear'),\n listCacheDelete = require('./_listCacheDelete'),\n listCacheGet = require('./_listCacheGet'),\n listCacheHas = require('./_listCacheHas'),\n listCacheSet = require('./_listCacheSet');\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nmodule.exports = ListCache;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nmodule.exports = Map;\n","var mapCacheClear = require('./_mapCacheClear'),\n mapCacheDelete = require('./_mapCacheDelete'),\n mapCacheGet = require('./_mapCacheGet'),\n mapCacheHas = require('./_mapCacheHas'),\n mapCacheSet = require('./_mapCacheSet');\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nmodule.exports = MapCache;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Promise = getNative(root, 'Promise');\n\nmodule.exports = Promise;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nmodule.exports = Set;\n","var MapCache = require('./_MapCache'),\n setCacheAdd = require('./_setCacheAdd'),\n setCacheHas = require('./_setCacheHas');\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\nmodule.exports = SetCache;\n","var ListCache = require('./_ListCache'),\n stackClear = require('./_stackClear'),\n stackDelete = require('./_stackDelete'),\n stackGet = require('./_stackGet'),\n stackHas = require('./_stackHas'),\n stackSet = require('./_stackSet');\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\nmodule.exports = Stack;\n","var root = require('./_root');\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nmodule.exports = Symbol;\n","var root = require('./_root');\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nmodule.exports = Uint8Array;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar WeakMap = getNative(root, 'WeakMap');\n\nmodule.exports = WeakMap;\n","/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nmodule.exports = arrayFilter;\n","var baseTimes = require('./_baseTimes'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray'),\n isBuffer = require('./isBuffer'),\n isIndex = require('./_isIndex'),\n isTypedArray = require('./isTypedArray');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = arrayLikeKeys;\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nmodule.exports = arrayMap;\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nmodule.exports = arrayPush;\n","/**\n * A specialized version of `_.reduce` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initAccum] Specify using the first element of `array` as\n * the initial value.\n * @returns {*} Returns the accumulated value.\n */\nfunction arrayReduce(array, iteratee, accumulator, initAccum) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n if (initAccum && length) {\n accumulator = array[++index];\n }\n while (++index < length) {\n accumulator = iteratee(accumulator, array[index], index, array);\n }\n return accumulator;\n}\n\nmodule.exports = arrayReduce;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nmodule.exports = arraySome;\n","/**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction asciiToArray(string) {\n return string.split('');\n}\n\nmodule.exports = asciiToArray;\n","/** Used to match words composed of alphanumeric characters. */\nvar reAsciiWord = /[^\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7f]+/g;\n\n/**\n * Splits an ASCII `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\nfunction asciiWords(string) {\n return string.match(reAsciiWord) || [];\n}\n\nmodule.exports = asciiWords;\n","var eq = require('./eq');\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\nmodule.exports = assocIndexOf;\n","var defineProperty = require('./_defineProperty');\n\n/**\n * The base implementation of `assignValue` and `assignMergeValue` without\n * value checks.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction baseAssignValue(object, key, value) {\n if (key == '__proto__' && defineProperty) {\n defineProperty(object, key, {\n 'configurable': true,\n 'enumerable': true,\n 'value': value,\n 'writable': true\n });\n } else {\n object[key] = value;\n }\n}\n\nmodule.exports = baseAssignValue;\n","var createBaseFor = require('./_createBaseFor');\n\n/**\n * The base implementation of `baseForOwn` which iterates over `object`\n * properties returned by `keysFunc` and invokes `iteratee` for each property.\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\nvar baseFor = createBaseFor();\n\nmodule.exports = baseFor;\n","var baseFor = require('./_baseFor'),\n keys = require('./keys');\n\n/**\n * The base implementation of `_.forOwn` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\nfunction baseForOwn(object, iteratee) {\n return object && baseFor(object, iteratee, keys);\n}\n\nmodule.exports = baseForOwn;\n","var castPath = require('./_castPath'),\n toKey = require('./_toKey');\n\n/**\n * The base implementation of `_.get` without support for default values.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @returns {*} Returns the resolved value.\n */\nfunction baseGet(object, path) {\n path = castPath(path, object);\n\n var index = 0,\n length = path.length;\n\n while (object != null && index < length) {\n object = object[toKey(path[index++])];\n }\n return (index && index == length) ? object : undefined;\n}\n\nmodule.exports = baseGet;\n","var arrayPush = require('./_arrayPush'),\n isArray = require('./isArray');\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\nmodule.exports = baseGetAllKeys;\n","var Symbol = require('./_Symbol'),\n getRawTag = require('./_getRawTag'),\n objectToString = require('./_objectToString');\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nmodule.exports = baseGetTag;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.has` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHas(object, key) {\n return object != null && hasOwnProperty.call(object, key);\n}\n\nmodule.exports = baseHas;\n","/**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHasIn(object, key) {\n return object != null && key in Object(object);\n}\n\nmodule.exports = baseHasIn;\n","var baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nmodule.exports = baseIsArguments;\n","var baseIsEqualDeep = require('./_baseIsEqualDeep'),\n isObjectLike = require('./isObjectLike');\n\n/**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\nfunction baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n}\n\nmodule.exports = baseIsEqual;\n","var Stack = require('./_Stack'),\n equalArrays = require('./_equalArrays'),\n equalByTag = require('./_equalByTag'),\n equalObjects = require('./_equalObjects'),\n getTag = require('./_getTag'),\n isArray = require('./isArray'),\n isBuffer = require('./isBuffer'),\n isTypedArray = require('./isTypedArray');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n}\n\nmodule.exports = baseIsEqualDeep;\n","var Stack = require('./_Stack'),\n baseIsEqual = require('./_baseIsEqual');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * The base implementation of `_.isMatch` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Array} matchData The property names, values, and compare flags to match.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n */\nfunction baseIsMatch(object, source, matchData, customizer) {\n var index = matchData.length,\n length = index,\n noCustomizer = !customizer;\n\n if (object == null) {\n return !length;\n }\n object = Object(object);\n while (index--) {\n var data = matchData[index];\n if ((noCustomizer && data[2])\n ? data[1] !== object[data[0]]\n : !(data[0] in object)\n ) {\n return false;\n }\n }\n while (++index < length) {\n data = matchData[index];\n var key = data[0],\n objValue = object[key],\n srcValue = data[1];\n\n if (noCustomizer && data[2]) {\n if (objValue === undefined && !(key in object)) {\n return false;\n }\n } else {\n var stack = new Stack;\n if (customizer) {\n var result = customizer(objValue, srcValue, key, object, source, stack);\n }\n if (!(result === undefined\n ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)\n : result\n )) {\n return false;\n }\n }\n }\n return true;\n}\n\nmodule.exports = baseIsMatch;\n","var isFunction = require('./isFunction'),\n isMasked = require('./_isMasked'),\n isObject = require('./isObject'),\n toSource = require('./_toSource');\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\nmodule.exports = baseIsNative;\n","var baseGetTag = require('./_baseGetTag'),\n isLength = require('./isLength'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nmodule.exports = baseIsTypedArray;\n","var baseMatches = require('./_baseMatches'),\n baseMatchesProperty = require('./_baseMatchesProperty'),\n identity = require('./identity'),\n isArray = require('./isArray'),\n property = require('./property');\n\n/**\n * The base implementation of `_.iteratee`.\n *\n * @private\n * @param {*} [value=_.identity] The value to convert to an iteratee.\n * @returns {Function} Returns the iteratee.\n */\nfunction baseIteratee(value) {\n // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.\n // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.\n if (typeof value == 'function') {\n return value;\n }\n if (value == null) {\n return identity;\n }\n if (typeof value == 'object') {\n return isArray(value)\n ? baseMatchesProperty(value[0], value[1])\n : baseMatches(value);\n }\n return property(value);\n}\n\nmodule.exports = baseIteratee;\n","var isPrototype = require('./_isPrototype'),\n nativeKeys = require('./_nativeKeys');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = baseKeys;\n","var baseIsMatch = require('./_baseIsMatch'),\n getMatchData = require('./_getMatchData'),\n matchesStrictComparable = require('./_matchesStrictComparable');\n\n/**\n * The base implementation of `_.matches` which doesn't clone `source`.\n *\n * @private\n * @param {Object} source The object of property values to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction baseMatches(source) {\n var matchData = getMatchData(source);\n if (matchData.length == 1 && matchData[0][2]) {\n return matchesStrictComparable(matchData[0][0], matchData[0][1]);\n }\n return function(object) {\n return object === source || baseIsMatch(object, source, matchData);\n };\n}\n\nmodule.exports = baseMatches;\n","var baseIsEqual = require('./_baseIsEqual'),\n get = require('./get'),\n hasIn = require('./hasIn'),\n isKey = require('./_isKey'),\n isStrictComparable = require('./_isStrictComparable'),\n matchesStrictComparable = require('./_matchesStrictComparable'),\n toKey = require('./_toKey');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.\n *\n * @private\n * @param {string} path The path of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction baseMatchesProperty(path, srcValue) {\n if (isKey(path) && isStrictComparable(srcValue)) {\n return matchesStrictComparable(toKey(path), srcValue);\n }\n return function(object) {\n var objValue = get(object, path);\n return (objValue === undefined && objValue === srcValue)\n ? hasIn(object, path)\n : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);\n };\n}\n\nmodule.exports = baseMatchesProperty;\n","/**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n}\n\nmodule.exports = baseProperty;\n","var baseGet = require('./_baseGet');\n\n/**\n * A specialized version of `baseProperty` which supports deep paths.\n *\n * @private\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction basePropertyDeep(path) {\n return function(object) {\n return baseGet(object, path);\n };\n}\n\nmodule.exports = basePropertyDeep;\n","/**\n * The base implementation of `_.propertyOf` without support for deep paths.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Function} Returns the new accessor function.\n */\nfunction basePropertyOf(object) {\n return function(key) {\n return object == null ? undefined : object[key];\n };\n}\n\nmodule.exports = basePropertyOf;\n","/**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\nfunction baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n}\n\nmodule.exports = baseSlice;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nmodule.exports = baseTimes;\n","var Symbol = require('./_Symbol'),\n arrayMap = require('./_arrayMap'),\n isArray = require('./isArray'),\n isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n/**\n * The base implementation of `_.toString` which doesn't convert nullish\n * values to empty strings.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {string} Returns the string.\n */\nfunction baseToString(value) {\n // Exit early for strings to avoid a performance hit in some environments.\n if (typeof value == 'string') {\n return value;\n }\n if (isArray(value)) {\n // Recursively convert values (susceptible to call stack limits).\n return arrayMap(value, baseToString) + '';\n }\n if (isSymbol(value)) {\n return symbolToString ? symbolToString.call(value) : '';\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nmodule.exports = baseToString;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nmodule.exports = baseUnary;\n","/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nmodule.exports = cacheHas;\n","var isArray = require('./isArray'),\n isKey = require('./_isKey'),\n stringToPath = require('./_stringToPath'),\n toString = require('./toString');\n\n/**\n * Casts `value` to a path array if it's not one.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {Object} [object] The object to query keys on.\n * @returns {Array} Returns the cast property path array.\n */\nfunction castPath(value, object) {\n if (isArray(value)) {\n return value;\n }\n return isKey(value, object) ? [value] : stringToPath(toString(value));\n}\n\nmodule.exports = castPath;\n","var baseSlice = require('./_baseSlice');\n\n/**\n * Casts `array` to a slice if it's needed.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {number} start The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the cast slice.\n */\nfunction castSlice(array, start, end) {\n var length = array.length;\n end = end === undefined ? length : end;\n return (!start && end >= length) ? array : baseSlice(array, start, end);\n}\n\nmodule.exports = castSlice;\n","var root = require('./_root');\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nmodule.exports = coreJsData;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nmodule.exports = createBaseFor;\n","var castSlice = require('./_castSlice'),\n hasUnicode = require('./_hasUnicode'),\n stringToArray = require('./_stringToArray'),\n toString = require('./toString');\n\n/**\n * Creates a function like `_.lowerFirst`.\n *\n * @private\n * @param {string} methodName The name of the `String` case method to use.\n * @returns {Function} Returns the new case function.\n */\nfunction createCaseFirst(methodName) {\n return function(string) {\n string = toString(string);\n\n var strSymbols = hasUnicode(string)\n ? stringToArray(string)\n : undefined;\n\n var chr = strSymbols\n ? strSymbols[0]\n : string.charAt(0);\n\n var trailing = strSymbols\n ? castSlice(strSymbols, 1).join('')\n : string.slice(1);\n\n return chr[methodName]() + trailing;\n };\n}\n\nmodule.exports = createCaseFirst;\n","var arrayReduce = require('./_arrayReduce'),\n deburr = require('./deburr'),\n words = require('./words');\n\n/** Used to compose unicode capture groups. */\nvar rsApos = \"['\\u2019]\";\n\n/** Used to match apostrophes. */\nvar reApos = RegExp(rsApos, 'g');\n\n/**\n * Creates a function like `_.camelCase`.\n *\n * @private\n * @param {Function} callback The function to combine each word.\n * @returns {Function} Returns the new compounder function.\n */\nfunction createCompounder(callback) {\n return function(string) {\n return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');\n };\n}\n\nmodule.exports = createCompounder;\n","var basePropertyOf = require('./_basePropertyOf');\n\n/** Used to map Latin Unicode letters to basic Latin letters. */\nvar deburredLetters = {\n // Latin-1 Supplement block.\n '\\xc0': 'A', '\\xc1': 'A', '\\xc2': 'A', '\\xc3': 'A', '\\xc4': 'A', '\\xc5': 'A',\n '\\xe0': 'a', '\\xe1': 'a', '\\xe2': 'a', '\\xe3': 'a', '\\xe4': 'a', '\\xe5': 'a',\n '\\xc7': 'C', '\\xe7': 'c',\n '\\xd0': 'D', '\\xf0': 'd',\n '\\xc8': 'E', '\\xc9': 'E', '\\xca': 'E', '\\xcb': 'E',\n '\\xe8': 'e', '\\xe9': 'e', '\\xea': 'e', '\\xeb': 'e',\n '\\xcc': 'I', '\\xcd': 'I', '\\xce': 'I', '\\xcf': 'I',\n '\\xec': 'i', '\\xed': 'i', '\\xee': 'i', '\\xef': 'i',\n '\\xd1': 'N', '\\xf1': 'n',\n '\\xd2': 'O', '\\xd3': 'O', '\\xd4': 'O', '\\xd5': 'O', '\\xd6': 'O', '\\xd8': 'O',\n '\\xf2': 'o', '\\xf3': 'o', '\\xf4': 'o', '\\xf5': 'o', '\\xf6': 'o', '\\xf8': 'o',\n '\\xd9': 'U', '\\xda': 'U', '\\xdb': 'U', '\\xdc': 'U',\n '\\xf9': 'u', '\\xfa': 'u', '\\xfb': 'u', '\\xfc': 'u',\n '\\xdd': 'Y', '\\xfd': 'y', '\\xff': 'y',\n '\\xc6': 'Ae', '\\xe6': 'ae',\n '\\xde': 'Th', '\\xfe': 'th',\n '\\xdf': 'ss',\n // Latin Extended-A block.\n '\\u0100': 'A', '\\u0102': 'A', '\\u0104': 'A',\n '\\u0101': 'a', '\\u0103': 'a', '\\u0105': 'a',\n '\\u0106': 'C', '\\u0108': 'C', '\\u010a': 'C', '\\u010c': 'C',\n '\\u0107': 'c', '\\u0109': 'c', '\\u010b': 'c', '\\u010d': 'c',\n '\\u010e': 'D', '\\u0110': 'D', '\\u010f': 'd', '\\u0111': 'd',\n '\\u0112': 'E', '\\u0114': 'E', '\\u0116': 'E', '\\u0118': 'E', '\\u011a': 'E',\n '\\u0113': 'e', '\\u0115': 'e', '\\u0117': 'e', '\\u0119': 'e', '\\u011b': 'e',\n '\\u011c': 'G', '\\u011e': 'G', '\\u0120': 'G', '\\u0122': 'G',\n '\\u011d': 'g', '\\u011f': 'g', '\\u0121': 'g', '\\u0123': 'g',\n '\\u0124': 'H', '\\u0126': 'H', '\\u0125': 'h', '\\u0127': 'h',\n '\\u0128': 'I', '\\u012a': 'I', '\\u012c': 'I', '\\u012e': 'I', '\\u0130': 'I',\n '\\u0129': 'i', '\\u012b': 'i', '\\u012d': 'i', '\\u012f': 'i', '\\u0131': 'i',\n '\\u0134': 'J', '\\u0135': 'j',\n '\\u0136': 'K', '\\u0137': 'k', '\\u0138': 'k',\n '\\u0139': 'L', '\\u013b': 'L', '\\u013d': 'L', '\\u013f': 'L', '\\u0141': 'L',\n '\\u013a': 'l', '\\u013c': 'l', '\\u013e': 'l', '\\u0140': 'l', '\\u0142': 'l',\n '\\u0143': 'N', '\\u0145': 'N', '\\u0147': 'N', '\\u014a': 'N',\n '\\u0144': 'n', '\\u0146': 'n', '\\u0148': 'n', '\\u014b': 'n',\n '\\u014c': 'O', '\\u014e': 'O', '\\u0150': 'O',\n '\\u014d': 'o', '\\u014f': 'o', '\\u0151': 'o',\n '\\u0154': 'R', '\\u0156': 'R', '\\u0158': 'R',\n '\\u0155': 'r', '\\u0157': 'r', '\\u0159': 'r',\n '\\u015a': 'S', '\\u015c': 'S', '\\u015e': 'S', '\\u0160': 'S',\n '\\u015b': 's', '\\u015d': 's', '\\u015f': 's', '\\u0161': 's',\n '\\u0162': 'T', '\\u0164': 'T', '\\u0166': 'T',\n '\\u0163': 't', '\\u0165': 't', '\\u0167': 't',\n '\\u0168': 'U', '\\u016a': 'U', '\\u016c': 'U', '\\u016e': 'U', '\\u0170': 'U', '\\u0172': 'U',\n '\\u0169': 'u', '\\u016b': 'u', '\\u016d': 'u', '\\u016f': 'u', '\\u0171': 'u', '\\u0173': 'u',\n '\\u0174': 'W', '\\u0175': 'w',\n '\\u0176': 'Y', '\\u0177': 'y', '\\u0178': 'Y',\n '\\u0179': 'Z', '\\u017b': 'Z', '\\u017d': 'Z',\n '\\u017a': 'z', '\\u017c': 'z', '\\u017e': 'z',\n '\\u0132': 'IJ', '\\u0133': 'ij',\n '\\u0152': 'Oe', '\\u0153': 'oe',\n '\\u0149': \"'n\", '\\u017f': 's'\n};\n\n/**\n * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A\n * letters to basic Latin letters.\n *\n * @private\n * @param {string} letter The matched letter to deburr.\n * @returns {string} Returns the deburred letter.\n */\nvar deburrLetter = basePropertyOf(deburredLetters);\n\nmodule.exports = deburrLetter;\n","var getNative = require('./_getNative');\n\nvar defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n}());\n\nmodule.exports = defineProperty;\n","var SetCache = require('./_SetCache'),\n arraySome = require('./_arraySome'),\n cacheHas = require('./_cacheHas');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\nfunction equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Check that cyclic values are equal.\n var arrStacked = stack.get(array);\n var othStacked = stack.get(other);\n if (arrStacked && othStacked) {\n return arrStacked == other && othStacked == array;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n}\n\nmodule.exports = equalArrays;\n","var Symbol = require('./_Symbol'),\n Uint8Array = require('./_Uint8Array'),\n eq = require('./eq'),\n equalArrays = require('./_equalArrays'),\n mapToArray = require('./_mapToArray'),\n setToArray = require('./_setToArray');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n}\n\nmodule.exports = equalByTag;\n","var getAllKeys = require('./_getAllKeys');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Check that cyclic values are equal.\n var objStacked = stack.get(object);\n var othStacked = stack.get(other);\n if (objStacked && othStacked) {\n return objStacked == other && othStacked == object;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n}\n\nmodule.exports = equalObjects;\n","/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nmodule.exports = freeGlobal;\n","var baseGetAllKeys = require('./_baseGetAllKeys'),\n getSymbols = require('./_getSymbols'),\n keys = require('./keys');\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\nmodule.exports = getAllKeys;\n","var isKeyable = require('./_isKeyable');\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nmodule.exports = getMapData;\n","var isStrictComparable = require('./_isStrictComparable'),\n keys = require('./keys');\n\n/**\n * Gets the property names, values, and compare flags of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the match data of `object`.\n */\nfunction getMatchData(object) {\n var result = keys(object),\n length = result.length;\n\n while (length--) {\n var key = result[length],\n value = object[key];\n\n result[length] = [key, value, isStrictComparable(value)];\n }\n return result;\n}\n\nmodule.exports = getMatchData;\n","var baseIsNative = require('./_baseIsNative'),\n getValue = require('./_getValue');\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nmodule.exports = getNative;\n","var Symbol = require('./_Symbol');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nmodule.exports = getRawTag;\n","var arrayFilter = require('./_arrayFilter'),\n stubArray = require('./stubArray');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n};\n\nmodule.exports = getSymbols;\n","var DataView = require('./_DataView'),\n Map = require('./_Map'),\n Promise = require('./_Promise'),\n Set = require('./_Set'),\n WeakMap = require('./_WeakMap'),\n baseGetTag = require('./_baseGetTag'),\n toSource = require('./_toSource');\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n setTag = '[object Set]',\n weakMapTag = '[object WeakMap]';\n\nvar dataViewTag = '[object DataView]';\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\nmodule.exports = getTag;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nmodule.exports = getValue;\n","var castPath = require('./_castPath'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray'),\n isIndex = require('./_isIndex'),\n isLength = require('./isLength'),\n toKey = require('./_toKey');\n\n/**\n * Checks if `path` exists on `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @param {Function} hasFunc The function to check properties.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n */\nfunction hasPath(object, path, hasFunc) {\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n result = false;\n\n while (++index < length) {\n var key = toKey(path[index]);\n if (!(result = object != null && hasFunc(object, key))) {\n break;\n }\n object = object[key];\n }\n if (result || ++index != length) {\n return result;\n }\n length = object == null ? 0 : object.length;\n return !!length && isLength(length) && isIndex(key, length) &&\n (isArray(object) || isArguments(object));\n}\n\nmodule.exports = hasPath;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsZWJ = '\\\\u200d';\n\n/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\nvar reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n/**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\nfunction hasUnicode(string) {\n return reHasUnicode.test(string);\n}\n\nmodule.exports = hasUnicode;\n","/** Used to detect strings that need a more robust regexp to match words. */\nvar reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;\n\n/**\n * Checks if `string` contains a word composed of Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a word is found, else `false`.\n */\nfunction hasUnicodeWord(string) {\n return reHasUnicodeWord.test(string);\n}\n\nmodule.exports = hasUnicodeWord;\n","var nativeCreate = require('./_nativeCreate');\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\nmodule.exports = hashClear;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nmodule.exports = hashDelete;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\nmodule.exports = hashGet;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nmodule.exports = hashHas;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\nmodule.exports = hashSet;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nmodule.exports = isIndex;\n","var isArray = require('./isArray'),\n isSymbol = require('./isSymbol');\n\n/** Used to match property names within property paths. */\nvar reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,\n reIsPlainProp = /^\\w*$/;\n\n/**\n * Checks if `value` is a property name and not a property path.\n *\n * @private\n * @param {*} value The value to check.\n * @param {Object} [object] The object to query keys on.\n * @returns {boolean} Returns `true` if `value` is a property name, else `false`.\n */\nfunction isKey(value, object) {\n if (isArray(value)) {\n return false;\n }\n var type = typeof value;\n if (type == 'number' || type == 'symbol' || type == 'boolean' ||\n value == null || isSymbol(value)) {\n return true;\n }\n return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||\n (object != null && value in Object(object));\n}\n\nmodule.exports = isKey;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nmodule.exports = isKeyable;\n","var coreJsData = require('./_coreJsData');\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\nmodule.exports = isMasked;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nmodule.exports = isPrototype;\n","var isObject = require('./isObject');\n\n/**\n * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` if suitable for strict\n * equality comparisons, else `false`.\n */\nfunction isStrictComparable(value) {\n return value === value && !isObject(value);\n}\n\nmodule.exports = isStrictComparable;\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nmodule.exports = listCacheClear;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\nmodule.exports = listCacheDelete;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\nmodule.exports = listCacheGet;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\nmodule.exports = listCacheHas;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\nmodule.exports = listCacheSet;\n","var Hash = require('./_Hash'),\n ListCache = require('./_ListCache'),\n Map = require('./_Map');\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\nmodule.exports = mapCacheClear;\n","var getMapData = require('./_getMapData');\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\nmodule.exports = mapCacheDelete;\n","var getMapData = require('./_getMapData');\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\nmodule.exports = mapCacheGet;\n","var getMapData = require('./_getMapData');\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\nmodule.exports = mapCacheHas;\n","var getMapData = require('./_getMapData');\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\nmodule.exports = mapCacheSet;\n","/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nmodule.exports = mapToArray;\n","/**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n}\n\nmodule.exports = matchesStrictComparable;\n","var memoize = require('./memoize');\n\n/** Used as the maximum memoize cache size. */\nvar MAX_MEMOIZE_SIZE = 500;\n\n/**\n * A specialized version of `_.memoize` which clears the memoized function's\n * cache when it exceeds `MAX_MEMOIZE_SIZE`.\n *\n * @private\n * @param {Function} func The function to have its output memoized.\n * @returns {Function} Returns the new memoized function.\n */\nfunction memoizeCapped(func) {\n var result = memoize(func, function(key) {\n if (cache.size === MAX_MEMOIZE_SIZE) {\n cache.clear();\n }\n return key;\n });\n\n var cache = result.cache;\n return result;\n}\n\nmodule.exports = memoizeCapped;\n","var getNative = require('./_getNative');\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nmodule.exports = nativeCreate;\n","var overArg = require('./_overArg');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nmodule.exports = nativeKeys;\n","var freeGlobal = require('./_freeGlobal');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\nmodule.exports = nodeUtil;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nmodule.exports = objectToString;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nmodule.exports = overArg;\n","var freeGlobal = require('./_freeGlobal');\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nmodule.exports = root;\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nmodule.exports = setCacheAdd;\n","/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nmodule.exports = setCacheHas;\n","/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nmodule.exports = setToArray;\n","var ListCache = require('./_ListCache');\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\nmodule.exports = stackClear;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nmodule.exports = stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nmodule.exports = stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nmodule.exports = stackHas;\n","var ListCache = require('./_ListCache'),\n Map = require('./_Map'),\n MapCache = require('./_MapCache');\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\nmodule.exports = stackSet;\n","var asciiToArray = require('./_asciiToArray'),\n hasUnicode = require('./_hasUnicode'),\n unicodeToArray = require('./_unicodeToArray');\n\n/**\n * Converts `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction stringToArray(string) {\n return hasUnicode(string)\n ? unicodeToArray(string)\n : asciiToArray(string);\n}\n\nmodule.exports = stringToArray;\n","var memoizeCapped = require('./_memoizeCapped');\n\n/** Used to match property names within property paths. */\nvar rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g;\n\n/** Used to match backslashes in property paths. */\nvar reEscapeChar = /\\\\(\\\\)?/g;\n\n/**\n * Converts `string` to a property path array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the property path array.\n */\nvar stringToPath = memoizeCapped(function(string) {\n var result = [];\n if (string.charCodeAt(0) === 46 /* . */) {\n result.push('');\n }\n string.replace(rePropName, function(match, number, quote, subString) {\n result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));\n });\n return result;\n});\n\nmodule.exports = stringToPath;\n","var isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/**\n * Converts `value` to a string key if it's not a string or symbol.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {string|symbol} Returns the key.\n */\nfunction toKey(value) {\n if (typeof value == 'string' || isSymbol(value)) {\n return value;\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nmodule.exports = toKey;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nmodule.exports = toSource;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction unicodeToArray(string) {\n return string.match(reUnicode) || [];\n}\n\nmodule.exports = unicodeToArray;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsDingbatRange = '\\\\u2700-\\\\u27bf',\n rsLowerRange = 'a-z\\\\xdf-\\\\xf6\\\\xf8-\\\\xff',\n rsMathOpRange = '\\\\xac\\\\xb1\\\\xd7\\\\xf7',\n rsNonCharRange = '\\\\x00-\\\\x2f\\\\x3a-\\\\x40\\\\x5b-\\\\x60\\\\x7b-\\\\xbf',\n rsPunctuationRange = '\\\\u2000-\\\\u206f',\n rsSpaceRange = ' \\\\t\\\\x0b\\\\f\\\\xa0\\\\ufeff\\\\n\\\\r\\\\u2028\\\\u2029\\\\u1680\\\\u180e\\\\u2000\\\\u2001\\\\u2002\\\\u2003\\\\u2004\\\\u2005\\\\u2006\\\\u2007\\\\u2008\\\\u2009\\\\u200a\\\\u202f\\\\u205f\\\\u3000',\n rsUpperRange = 'A-Z\\\\xc0-\\\\xd6\\\\xd8-\\\\xde',\n rsVarRange = '\\\\ufe0e\\\\ufe0f',\n rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;\n\n/** Used to compose unicode capture groups. */\nvar rsApos = \"['\\u2019]\",\n rsBreak = '[' + rsBreakRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsDigits = '\\\\d+',\n rsDingbat = '[' + rsDingbatRange + ']',\n rsLower = '[' + rsLowerRange + ']',\n rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsUpper = '[' + rsUpperRange + ']',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',\n rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',\n rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',\n rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',\n reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsOrdLower = '\\\\d*(?:1st|2nd|3rd|(?![123])\\\\dth)(?=\\\\b|[A-Z_])',\n rsOrdUpper = '\\\\d*(?:1ST|2ND|3RD|(?![123])\\\\dTH)(?=\\\\b|[a-z_])',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq;\n\n/** Used to match complex or compound words. */\nvar reUnicodeWord = RegExp([\n rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',\n rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',\n rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,\n rsUpper + '+' + rsOptContrUpper,\n rsOrdUpper,\n rsOrdLower,\n rsDigits,\n rsEmoji\n].join('|'), 'g');\n\n/**\n * Splits a Unicode `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\nfunction unicodeWords(string) {\n return string.match(reUnicodeWord) || [];\n}\n\nmodule.exports = unicodeWords;\n","var capitalize = require('./capitalize'),\n createCompounder = require('./_createCompounder');\n\n/**\n * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the camel cased string.\n * @example\n *\n * _.camelCase('Foo Bar');\n * // => 'fooBar'\n *\n * _.camelCase('--foo-bar--');\n * // => 'fooBar'\n *\n * _.camelCase('__FOO_BAR__');\n * // => 'fooBar'\n */\nvar camelCase = createCompounder(function(result, word, index) {\n word = word.toLowerCase();\n return result + (index ? capitalize(word) : word);\n});\n\nmodule.exports = camelCase;\n","var toString = require('./toString'),\n upperFirst = require('./upperFirst');\n\n/**\n * Converts the first character of `string` to upper case and the remaining\n * to lower case.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to capitalize.\n * @returns {string} Returns the capitalized string.\n * @example\n *\n * _.capitalize('FRED');\n * // => 'Fred'\n */\nfunction capitalize(string) {\n return upperFirst(toString(string).toLowerCase());\n}\n\nmodule.exports = capitalize;\n","var deburrLetter = require('./_deburrLetter'),\n toString = require('./toString');\n\n/** Used to match Latin Unicode letters (excluding mathematical operators). */\nvar reLatin = /[\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\xff\\u0100-\\u017f]/g;\n\n/** Used to compose unicode character classes. */\nvar rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange;\n\n/** Used to compose unicode capture groups. */\nvar rsCombo = '[' + rsComboRange + ']';\n\n/**\n * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and\n * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).\n */\nvar reComboMark = RegExp(rsCombo, 'g');\n\n/**\n * Deburrs `string` by converting\n * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)\n * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)\n * letters to basic Latin letters and removing\n * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to deburr.\n * @returns {string} Returns the deburred string.\n * @example\n *\n * _.deburr('déjà vu');\n * // => 'deja vu'\n */\nfunction deburr(string) {\n string = toString(string);\n return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');\n}\n\nmodule.exports = deburr;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nmodule.exports = eq;\n","var baseGet = require('./_baseGet');\n\n/**\n * Gets the value at `path` of `object`. If the resolved value is\n * `undefined`, the `defaultValue` is returned in its place.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.get(object, 'a[0].b.c');\n * // => 3\n *\n * _.get(object, ['a', '0', 'b', 'c']);\n * // => 3\n *\n * _.get(object, 'a.b.c', 'default');\n * // => 'default'\n */\nfunction get(object, path, defaultValue) {\n var result = object == null ? undefined : baseGet(object, path);\n return result === undefined ? defaultValue : result;\n}\n\nmodule.exports = get;\n","var baseHas = require('./_baseHas'),\n hasPath = require('./_hasPath');\n\n/**\n * Checks if `path` is a direct property of `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = { 'a': { 'b': 2 } };\n * var other = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.has(object, 'a');\n * // => true\n *\n * _.has(object, 'a.b');\n * // => true\n *\n * _.has(object, ['a', 'b']);\n * // => true\n *\n * _.has(other, 'a');\n * // => false\n */\nfunction has(object, path) {\n return object != null && hasPath(object, path, baseHas);\n}\n\nmodule.exports = has;\n","var baseHasIn = require('./_baseHasIn'),\n hasPath = require('./_hasPath');\n\n/**\n * Checks if `path` is a direct or inherited property of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.hasIn(object, 'a');\n * // => true\n *\n * _.hasIn(object, 'a.b');\n * // => true\n *\n * _.hasIn(object, ['a', 'b']);\n * // => true\n *\n * _.hasIn(object, 'b');\n * // => false\n */\nfunction hasIn(object, path) {\n return object != null && hasPath(object, path, baseHasIn);\n}\n\nmodule.exports = hasIn;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nmodule.exports = identity;\n","var baseIsArguments = require('./_baseIsArguments'),\n isObjectLike = require('./isObjectLike');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\nmodule.exports = isArguments;\n","/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nmodule.exports = isArray;\n","var isFunction = require('./isFunction'),\n isLength = require('./isLength');\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nmodule.exports = isArrayLike;\n","var root = require('./_root'),\n stubFalse = require('./stubFalse');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nmodule.exports = isBuffer;\n","var baseGetTag = require('./_baseGetTag'),\n isObject = require('./isObject');\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nmodule.exports = isFunction;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nmodule.exports = isLength;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nmodule.exports = isObject;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nmodule.exports = isObjectLike;\n","var baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n}\n\nmodule.exports = isSymbol;\n","var baseIsTypedArray = require('./_baseIsTypedArray'),\n baseUnary = require('./_baseUnary'),\n nodeUtil = require('./_nodeUtil');\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\nmodule.exports = isTypedArray;\n","var arrayLikeKeys = require('./_arrayLikeKeys'),\n baseKeys = require('./_baseKeys'),\n isArrayLike = require('./isArrayLike');\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\nmodule.exports = keys;\n","var baseAssignValue = require('./_baseAssignValue'),\n baseForOwn = require('./_baseForOwn'),\n baseIteratee = require('./_baseIteratee');\n\n/**\n * The opposite of `_.mapValues`; this method creates an object with the\n * same values as `object` and keys generated by running each own enumerable\n * string keyed property of `object` thru `iteratee`. The iteratee is invoked\n * with three arguments: (value, key, object).\n *\n * @static\n * @memberOf _\n * @since 3.8.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns the new mapped object.\n * @see _.mapValues\n * @example\n *\n * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {\n * return key + value;\n * });\n * // => { 'a1': 1, 'b2': 2 }\n */\nfunction mapKeys(object, iteratee) {\n var result = {};\n iteratee = baseIteratee(iteratee, 3);\n\n baseForOwn(object, function(value, key, object) {\n baseAssignValue(result, iteratee(value, key, object), value);\n });\n return result;\n}\n\nmodule.exports = mapKeys;\n","var baseAssignValue = require('./_baseAssignValue'),\n baseForOwn = require('./_baseForOwn'),\n baseIteratee = require('./_baseIteratee');\n\n/**\n * Creates an object with the same keys as `object` and values generated\n * by running each own enumerable string keyed property of `object` thru\n * `iteratee`. The iteratee is invoked with three arguments:\n * (value, key, object).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns the new mapped object.\n * @see _.mapKeys\n * @example\n *\n * var users = {\n * 'fred': { 'user': 'fred', 'age': 40 },\n * 'pebbles': { 'user': 'pebbles', 'age': 1 }\n * };\n *\n * _.mapValues(users, function(o) { return o.age; });\n * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n *\n * // The `_.property` iteratee shorthand.\n * _.mapValues(users, 'age');\n * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n */\nfunction mapValues(object, iteratee) {\n var result = {};\n iteratee = baseIteratee(iteratee, 3);\n\n baseForOwn(object, function(value, key, object) {\n baseAssignValue(result, key, iteratee(value, key, object));\n });\n return result;\n}\n\nmodule.exports = mapValues;\n","var MapCache = require('./_MapCache');\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that memoizes the result of `func`. If `resolver` is\n * provided, it determines the cache key for storing the result based on the\n * arguments provided to the memoized function. By default, the first argument\n * provided to the memoized function is used as the map cache key. The `func`\n * is invoked with the `this` binding of the memoized function.\n *\n * **Note:** The cache is exposed as the `cache` property on the memoized\n * function. Its creation may be customized by replacing the `_.memoize.Cache`\n * constructor with one whose instances implement the\n * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)\n * method interface of `clear`, `delete`, `get`, `has`, and `set`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to have its output memoized.\n * @param {Function} [resolver] The function to resolve the cache key.\n * @returns {Function} Returns the new memoized function.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n * var other = { 'c': 3, 'd': 4 };\n *\n * var values = _.memoize(_.values);\n * values(object);\n * // => [1, 2]\n *\n * values(other);\n * // => [3, 4]\n *\n * object.a = 2;\n * values(object);\n * // => [1, 2]\n *\n * // Modify the result cache.\n * values.cache.set(object, ['a', 'b']);\n * values(object);\n * // => ['a', 'b']\n *\n * // Replace `_.memoize.Cache`.\n * _.memoize.Cache = WeakMap;\n */\nfunction memoize(func, resolver) {\n if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var memoized = function() {\n var args = arguments,\n key = resolver ? resolver.apply(this, args) : args[0],\n cache = memoized.cache;\n\n if (cache.has(key)) {\n return cache.get(key);\n }\n var result = func.apply(this, args);\n memoized.cache = cache.set(key, result) || cache;\n return result;\n };\n memoized.cache = new (memoize.Cache || MapCache);\n return memoized;\n}\n\n// Expose `MapCache`.\nmemoize.Cache = MapCache;\n\nmodule.exports = memoize;\n","var baseProperty = require('./_baseProperty'),\n basePropertyDeep = require('./_basePropertyDeep'),\n isKey = require('./_isKey'),\n toKey = require('./_toKey');\n\n/**\n * Creates a function that returns the value at `path` of a given object.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n * @example\n *\n * var objects = [\n * { 'a': { 'b': 2 } },\n * { 'a': { 'b': 1 } }\n * ];\n *\n * _.map(objects, _.property('a.b'));\n * // => [2, 1]\n *\n * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');\n * // => [1, 2]\n */\nfunction property(path) {\n return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);\n}\n\nmodule.exports = property;\n","var createCompounder = require('./_createCompounder');\n\n/**\n * Converts `string` to\n * [snake case](https://en.wikipedia.org/wiki/Snake_case).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the snake cased string.\n * @example\n *\n * _.snakeCase('Foo Bar');\n * // => 'foo_bar'\n *\n * _.snakeCase('fooBar');\n * // => 'foo_bar'\n *\n * _.snakeCase('--FOO-BAR--');\n * // => 'foo_bar'\n */\nvar snakeCase = createCompounder(function(result, word, index) {\n return result + (index ? '_' : '') + word.toLowerCase();\n});\n\nmodule.exports = snakeCase;\n","/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nmodule.exports = stubArray;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nmodule.exports = stubFalse;\n","var baseToString = require('./_baseToString');\n\n/**\n * Converts `value` to a string. An empty string is returned for `null`\n * and `undefined` values. The sign of `-0` is preserved.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.toString(null);\n * // => ''\n *\n * _.toString(-0);\n * // => '-0'\n *\n * _.toString([1, 2, 3]);\n * // => '1,2,3'\n */\nfunction toString(value) {\n return value == null ? '' : baseToString(value);\n}\n\nmodule.exports = toString;\n","var createCaseFirst = require('./_createCaseFirst');\n\n/**\n * Converts the first character of `string` to upper case.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.upperFirst('fred');\n * // => 'Fred'\n *\n * _.upperFirst('FRED');\n * // => 'FRED'\n */\nvar upperFirst = createCaseFirst('toUpperCase');\n\nmodule.exports = upperFirst;\n","var asciiWords = require('./_asciiWords'),\n hasUnicodeWord = require('./_hasUnicodeWord'),\n toString = require('./toString'),\n unicodeWords = require('./_unicodeWords');\n\n/**\n * Splits `string` into an array of its words.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to inspect.\n * @param {RegExp|string} [pattern] The pattern to match words.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the words of `string`.\n * @example\n *\n * _.words('fred, barney, & pebbles');\n * // => ['fred', 'barney', 'pebbles']\n *\n * _.words('fred, barney, & pebbles', /[^, ]+/g);\n * // => ['fred', 'barney', '&', 'pebbles']\n */\nfunction words(string, pattern, guard) {\n string = toString(string);\n pattern = guard ? undefined : pattern;\n\n if (pattern === undefined) {\n return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);\n }\n return string.match(pattern) || [];\n}\n\nmodule.exports = words;\n","var NodeType;\r\n(function (NodeType) {\r\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\r\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\r\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\r\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\r\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\r\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\r\n})(NodeType || (NodeType = {}));\n\nfunction isElement(n) {\r\n return n.nodeType === n.ELEMENT_NODE;\r\n}\r\nfunction isShadowRoot(n) {\r\n const host = n === null || n === void 0 ? void 0 : n.host;\r\n return Boolean((host === null || host === void 0 ? void 0 : host.shadowRoot) === n);\r\n}\r\nfunction isNativeShadowDom(shadowRoot) {\r\n return Object.prototype.toString.call(shadowRoot) === '[object ShadowRoot]';\r\n}\r\nfunction fixBrowserCompatibilityIssuesInCSS(cssText) {\r\n if (cssText.includes(' background-clip: text;') &&\r\n !cssText.includes(' -webkit-background-clip: text;')) {\r\n cssText = cssText.replace(' background-clip: text;', ' -webkit-background-clip: text; background-clip: text;');\r\n }\r\n return cssText;\r\n}\r\nfunction escapeImportStatement(rule) {\r\n const { cssText } = rule;\r\n if (cssText.split('\"').length < 3)\r\n return cssText;\r\n const statement = ['@import', `url(${JSON.stringify(rule.href)})`];\r\n if (rule.layerName === '') {\r\n statement.push(`layer`);\r\n }\r\n else if (rule.layerName) {\r\n statement.push(`layer(${rule.layerName})`);\r\n }\r\n if (rule.supportsText) {\r\n statement.push(`supports(${rule.supportsText})`);\r\n }\r\n if (rule.media.length) {\r\n statement.push(rule.media.mediaText);\r\n }\r\n return statement.join(' ') + ';';\r\n}\r\nfunction stringifyStylesheet(s) {\r\n try {\r\n const rules = s.rules || s.cssRules;\r\n return rules\r\n ? fixBrowserCompatibilityIssuesInCSS(Array.from(rules, stringifyRule).join(''))\r\n : null;\r\n }\r\n catch (error) {\r\n return null;\r\n }\r\n}\r\nfunction stringifyRule(rule) {\r\n let importStringified;\r\n if (isCSSImportRule(rule)) {\r\n try {\r\n importStringified =\r\n stringifyStylesheet(rule.styleSheet) ||\r\n escapeImportStatement(rule);\r\n }\r\n catch (error) {\r\n }\r\n }\r\n else if (isCSSStyleRule(rule) && rule.selectorText.includes(':')) {\r\n return fixSafariColons(rule.cssText);\r\n }\r\n return importStringified || rule.cssText;\r\n}\r\nfunction fixSafariColons(cssStringified) {\r\n const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\r\n return cssStringified.replace(regex, '$1\\\\$2');\r\n}\r\nfunction isCSSImportRule(rule) {\r\n return 'styleSheet' in rule;\r\n}\r\nfunction isCSSStyleRule(rule) {\r\n return 'selectorText' in rule;\r\n}\r\nclass Mirror {\r\n constructor() {\r\n this.idNodeMap = new Map();\r\n this.nodeMetaMap = new WeakMap();\r\n }\r\n getId(n) {\r\n var _a;\r\n if (!n)\r\n return -1;\r\n const id = (_a = this.getMeta(n)) === null || _a === void 0 ? void 0 : _a.id;\r\n return id !== null && id !== void 0 ? id : -1;\r\n }\r\n getNode(id) {\r\n return this.idNodeMap.get(id) || null;\r\n }\r\n getIds() {\r\n return Array.from(this.idNodeMap.keys());\r\n }\r\n getMeta(n) {\r\n return this.nodeMetaMap.get(n) || null;\r\n }\r\n removeNodeFromMap(n) {\r\n const id = this.getId(n);\r\n this.idNodeMap.delete(id);\r\n if (n.childNodes) {\r\n n.childNodes.forEach((childNode) => this.removeNodeFromMap(childNode));\r\n }\r\n }\r\n has(id) {\r\n return this.idNodeMap.has(id);\r\n }\r\n hasNode(node) {\r\n return this.nodeMetaMap.has(node);\r\n }\r\n add(n, meta) {\r\n const id = meta.id;\r\n this.idNodeMap.set(id, n);\r\n this.nodeMetaMap.set(n, meta);\r\n }\r\n replace(id, n) {\r\n const oldNode = this.getNode(id);\r\n if (oldNode) {\r\n const meta = this.nodeMetaMap.get(oldNode);\r\n if (meta)\r\n this.nodeMetaMap.set(n, meta);\r\n }\r\n this.idNodeMap.set(id, n);\r\n }\r\n reset() {\r\n this.idNodeMap = new Map();\r\n this.nodeMetaMap = new WeakMap();\r\n }\r\n}\r\nfunction createMirror() {\r\n return new Mirror();\r\n}\r\nfunction maskInputValue({ element, maskInputOptions, tagName, type, value, maskInputFn, }) {\r\n let text = value || '';\r\n const actualType = type && toLowerCase(type);\r\n if (maskInputOptions[tagName.toLowerCase()] ||\r\n (actualType && maskInputOptions[actualType])) {\r\n if (maskInputFn) {\r\n text = maskInputFn(text, element);\r\n }\r\n else {\r\n text = '*'.repeat(text.length);\r\n }\r\n }\r\n return text;\r\n}\r\nfunction toLowerCase(str) {\r\n return str.toLowerCase();\r\n}\r\nconst ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';\r\nfunction is2DCanvasBlank(canvas) {\r\n const ctx = canvas.getContext('2d');\r\n if (!ctx)\r\n return true;\r\n const chunkSize = 50;\r\n for (let x = 0; x < canvas.width; x += chunkSize) {\r\n for (let y = 0; y < canvas.height; y += chunkSize) {\r\n const getImageData = ctx.getImageData;\r\n const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData\r\n ? getImageData[ORIGINAL_ATTRIBUTE_NAME]\r\n : getImageData;\r\n const pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);\r\n if (pixelBuffer.some((pixel) => pixel !== 0))\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction getInputType(element) {\r\n const type = element.type;\r\n return element.hasAttribute('data-rr-is-password')\r\n ? 'password'\r\n : type\r\n ?\r\n toLowerCase(type)\r\n : null;\r\n}\r\nfunction extractFileExtension(path, baseURL) {\r\n var _a;\r\n let url;\r\n try {\r\n url = new URL(path, baseURL !== null && baseURL !== void 0 ? baseURL : window.location.href);\r\n }\r\n catch (err) {\r\n return null;\r\n }\r\n const regex = /\\.([0-9a-z]+)(?:$)/i;\r\n const match = url.pathname.match(regex);\r\n return (_a = match === null || match === void 0 ? void 0 : match[1]) !== null && _a !== void 0 ? _a : null;\r\n}\n\nlet _id = 1;\r\nconst tagNameRegex = new RegExp('[^a-z0-9-_:]');\r\nconst IGNORED_NODE = -2;\r\nfunction genId() {\r\n return _id++;\r\n}\r\nfunction getValidTagName(element) {\r\n if (element instanceof HTMLFormElement) {\r\n return 'form';\r\n }\r\n const processedTagName = toLowerCase(element.tagName);\r\n if (tagNameRegex.test(processedTagName)) {\r\n return 'div';\r\n }\r\n return processedTagName;\r\n}\r\nfunction extractOrigin(url) {\r\n let origin = '';\r\n if (url.indexOf('//') > -1) {\r\n origin = url.split('/').slice(0, 3).join('/');\r\n }\r\n else {\r\n origin = url.split('/')[0];\r\n }\r\n origin = origin.split('?')[0];\r\n return origin;\r\n}\r\nlet canvasService;\r\nlet canvasCtx;\r\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\r\nconst URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\\/\\//i;\r\nconst URL_WWW_MATCH = /^www\\..*/i;\r\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\r\nfunction absoluteToStylesheet(cssText, href) {\r\n return (cssText || '').replace(URL_IN_CSS_REF, (origin, quote1, path1, quote2, path2, path3) => {\r\n const filePath = path1 || path2 || path3;\r\n const maybeQuote = quote1 || quote2 || '';\r\n if (!filePath) {\r\n return origin;\r\n }\r\n if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {\r\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\r\n }\r\n if (DATA_URI.test(filePath)) {\r\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\r\n }\r\n if (filePath[0] === '/') {\r\n return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\r\n }\r\n const stack = href.split('/');\r\n const parts = filePath.split('/');\r\n stack.pop();\r\n for (const part of parts) {\r\n if (part === '.') {\r\n continue;\r\n }\r\n else if (part === '..') {\r\n stack.pop();\r\n }\r\n else {\r\n stack.push(part);\r\n }\r\n }\r\n return `url(${maybeQuote}${stack.join('/')}${maybeQuote})`;\r\n });\r\n}\r\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\r\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\r\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\r\n if (attributeValue.trim() === '') {\r\n return attributeValue;\r\n }\r\n let pos = 0;\r\n function collectCharacters(regEx) {\r\n let chars;\r\n const match = regEx.exec(attributeValue.substring(pos));\r\n if (match) {\r\n chars = match[0];\r\n pos += chars.length;\r\n return chars;\r\n }\r\n return '';\r\n }\r\n const output = [];\r\n while (true) {\r\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\r\n if (pos >= attributeValue.length) {\r\n break;\r\n }\r\n let url = collectCharacters(SRCSET_NOT_SPACES);\r\n if (url.slice(-1) === ',') {\r\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\r\n output.push(url);\r\n }\r\n else {\r\n let descriptorsStr = '';\r\n url = absoluteToDoc(doc, url);\r\n let inParens = false;\r\n while (true) {\r\n const c = attributeValue.charAt(pos);\r\n if (c === '') {\r\n output.push((url + descriptorsStr).trim());\r\n break;\r\n }\r\n else if (!inParens) {\r\n if (c === ',') {\r\n pos += 1;\r\n output.push((url + descriptorsStr).trim());\r\n break;\r\n }\r\n else if (c === '(') {\r\n inParens = true;\r\n }\r\n }\r\n else {\r\n if (c === ')') {\r\n inParens = false;\r\n }\r\n }\r\n descriptorsStr += c;\r\n pos += 1;\r\n }\r\n }\r\n }\r\n return output.join(', ');\r\n}\r\nfunction absoluteToDoc(doc, attributeValue) {\r\n if (!attributeValue || attributeValue.trim() === '') {\r\n return attributeValue;\r\n }\r\n const a = doc.createElement('a');\r\n a.href = attributeValue;\r\n return a.href;\r\n}\r\nfunction isSVGElement(el) {\r\n return Boolean(el.tagName === 'svg' || el.ownerSVGElement);\r\n}\r\nfunction getHref() {\r\n const a = document.createElement('a');\r\n a.href = '';\r\n return a.href;\r\n}\r\nfunction transformAttribute(doc, tagName, name, value) {\r\n if (!value) {\r\n return value;\r\n }\r\n if (name === 'src' ||\r\n (name === 'href' && !(tagName === 'use' && value[0] === '#'))) {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'xlink:href' && value[0] !== '#') {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'background' &&\r\n (tagName === 'table' || tagName === 'td' || tagName === 'th')) {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'srcset') {\r\n return getAbsoluteSrcsetString(doc, value);\r\n }\r\n else if (name === 'style') {\r\n return absoluteToStylesheet(value, getHref());\r\n }\r\n else if (tagName === 'object' && name === 'data') {\r\n return absoluteToDoc(doc, value);\r\n }\r\n return value;\r\n}\r\nfunction ignoreAttribute(tagName, name, _value) {\r\n return (tagName === 'video' || tagName === 'audio') && name === 'autoplay';\r\n}\r\nfunction _isBlockedElement(element, blockClass, blockSelector) {\r\n try {\r\n if (typeof blockClass === 'string') {\r\n if (element.classList.contains(blockClass)) {\r\n return true;\r\n }\r\n }\r\n else {\r\n for (let eIndex = element.classList.length; eIndex--;) {\r\n const className = element.classList[eIndex];\r\n if (blockClass.test(className)) {\r\n return true;\r\n }\r\n }\r\n }\r\n if (blockSelector) {\r\n return element.matches(blockSelector);\r\n }\r\n }\r\n catch (e) {\r\n }\r\n return false;\r\n}\r\nfunction classMatchesRegex(node, regex, checkAncestors) {\r\n if (!node)\r\n return false;\r\n if (node.nodeType !== node.ELEMENT_NODE) {\r\n if (!checkAncestors)\r\n return false;\r\n return classMatchesRegex(node.parentNode, regex, checkAncestors);\r\n }\r\n for (let eIndex = node.classList.length; eIndex--;) {\r\n const className = node.classList[eIndex];\r\n if (regex.test(className)) {\r\n return true;\r\n }\r\n }\r\n if (!checkAncestors)\r\n return false;\r\n return classMatchesRegex(node.parentNode, regex, checkAncestors);\r\n}\r\nfunction needMaskingText(node, maskTextClass, maskTextSelector, checkAncestors) {\r\n try {\r\n const el = node.nodeType === node.ELEMENT_NODE\r\n ? node\r\n : node.parentElement;\r\n if (el === null)\r\n return false;\r\n if (typeof maskTextClass === 'string') {\r\n if (checkAncestors) {\r\n if (el.closest(`.${maskTextClass}`))\r\n return true;\r\n }\r\n else {\r\n if (el.classList.contains(maskTextClass))\r\n return true;\r\n }\r\n }\r\n else {\r\n if (classMatchesRegex(el, maskTextClass, checkAncestors))\r\n return true;\r\n }\r\n if (maskTextSelector) {\r\n if (checkAncestors) {\r\n if (el.closest(maskTextSelector))\r\n return true;\r\n }\r\n else {\r\n if (el.matches(maskTextSelector))\r\n return true;\r\n }\r\n }\r\n }\r\n catch (e) {\r\n }\r\n return false;\r\n}\r\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\r\n const win = iframeEl.contentWindow;\r\n if (!win) {\r\n return;\r\n }\r\n let fired = false;\r\n let readyState;\r\n try {\r\n readyState = win.document.readyState;\r\n }\r\n catch (error) {\r\n return;\r\n }\r\n if (readyState !== 'complete') {\r\n const timer = setTimeout(() => {\r\n if (!fired) {\r\n listener();\r\n fired = true;\r\n }\r\n }, iframeLoadTimeout);\r\n iframeEl.addEventListener('load', () => {\r\n clearTimeout(timer);\r\n fired = true;\r\n listener();\r\n });\r\n return;\r\n }\r\n const blankUrl = 'about:blank';\r\n if (win.location.href !== blankUrl ||\r\n iframeEl.src === blankUrl ||\r\n iframeEl.src === '') {\r\n setTimeout(listener, 0);\r\n return iframeEl.addEventListener('load', listener);\r\n }\r\n iframeEl.addEventListener('load', listener);\r\n}\r\nfunction onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {\r\n let fired = false;\r\n let styleSheetLoaded;\r\n try {\r\n styleSheetLoaded = link.sheet;\r\n }\r\n catch (error) {\r\n return;\r\n }\r\n if (styleSheetLoaded)\r\n return;\r\n const timer = setTimeout(() => {\r\n if (!fired) {\r\n listener();\r\n fired = true;\r\n }\r\n }, styleSheetLoadTimeout);\r\n link.addEventListener('load', () => {\r\n clearTimeout(timer);\r\n fired = true;\r\n listener();\r\n });\r\n}\r\nfunction serializeNode(n, options) {\r\n const { doc, mirror, blockClass, blockSelector, needsMask, inlineStylesheet, maskInputOptions = {}, maskTextFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, } = options;\r\n const rootId = getRootId(doc, mirror);\r\n switch (n.nodeType) {\r\n case n.DOCUMENT_NODE:\r\n if (n.compatMode !== 'CSS1Compat') {\r\n return {\r\n type: NodeType.Document,\r\n childNodes: [],\r\n compatMode: n.compatMode,\r\n };\r\n }\r\n else {\r\n return {\r\n type: NodeType.Document,\r\n childNodes: [],\r\n };\r\n }\r\n case n.DOCUMENT_TYPE_NODE:\r\n return {\r\n type: NodeType.DocumentType,\r\n name: n.name,\r\n publicId: n.publicId,\r\n systemId: n.systemId,\r\n rootId,\r\n };\r\n case n.ELEMENT_NODE:\r\n return serializeElementNode(n, {\r\n doc,\r\n blockClass,\r\n blockSelector,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskInputFn,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n keepIframeSrcFn,\r\n newlyAddedElement,\r\n rootId,\r\n });\r\n case n.TEXT_NODE:\r\n return serializeTextNode(n, {\r\n needsMask,\r\n maskTextFn,\r\n rootId,\r\n });\r\n case n.CDATA_SECTION_NODE:\r\n return {\r\n type: NodeType.CDATA,\r\n textContent: '',\r\n rootId,\r\n };\r\n case n.COMMENT_NODE:\r\n return {\r\n type: NodeType.Comment,\r\n textContent: n.textContent || '',\r\n rootId,\r\n };\r\n default:\r\n return false;\r\n }\r\n}\r\nfunction getRootId(doc, mirror) {\r\n if (!mirror.hasNode(doc))\r\n return undefined;\r\n const docId = mirror.getId(doc);\r\n return docId === 1 ? undefined : docId;\r\n}\r\nfunction serializeTextNode(n, options) {\r\n var _a;\r\n const { needsMask, maskTextFn, rootId } = options;\r\n const parentTagName = n.parentNode && n.parentNode.tagName;\r\n let textContent = n.textContent;\r\n const isStyle = parentTagName === 'STYLE' ? true : undefined;\r\n const isScript = parentTagName === 'SCRIPT' ? true : undefined;\r\n if (isStyle && textContent) {\r\n try {\r\n if (n.nextSibling || n.previousSibling) {\r\n }\r\n else if ((_a = n.parentNode.sheet) === null || _a === void 0 ? void 0 : _a.cssRules) {\r\n textContent = stringifyStylesheet(n.parentNode.sheet);\r\n }\r\n }\r\n catch (err) {\r\n console.warn(`Cannot get CSS styles from text's parentNode. Error: ${err}`, n);\r\n }\r\n textContent = absoluteToStylesheet(textContent, getHref());\r\n }\r\n if (isScript) {\r\n textContent = 'SCRIPT_PLACEHOLDER';\r\n }\r\n if (!isStyle && !isScript && textContent && needsMask) {\r\n textContent = maskTextFn\r\n ? maskTextFn(textContent, n.parentElement)\r\n : textContent.replace(/[\\S]/g, '*');\r\n }\r\n return {\r\n type: NodeType.Text,\r\n textContent: textContent || '',\r\n isStyle,\r\n rootId,\r\n };\r\n}\r\nfunction serializeElementNode(n, options) {\r\n const { doc, blockClass, blockSelector, inlineStylesheet, maskInputOptions = {}, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, rootId, } = options;\r\n const needBlock = _isBlockedElement(n, blockClass, blockSelector);\r\n const tagName = getValidTagName(n);\r\n let attributes = {};\r\n const len = n.attributes.length;\r\n for (let i = 0; i < len; i++) {\r\n const attr = n.attributes[i];\r\n if (!ignoreAttribute(tagName, attr.name, attr.value)) {\r\n attributes[attr.name] = transformAttribute(doc, tagName, toLowerCase(attr.name), attr.value);\r\n }\r\n }\r\n if (tagName === 'link' && inlineStylesheet) {\r\n const stylesheet = Array.from(doc.styleSheets).find((s) => {\r\n return s.href === n.href;\r\n });\r\n let cssText = null;\r\n if (stylesheet) {\r\n cssText = stringifyStylesheet(stylesheet);\r\n }\r\n if (cssText) {\r\n delete attributes.rel;\r\n delete attributes.href;\r\n attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);\r\n }\r\n }\r\n if (tagName === 'style' &&\r\n n.sheet &&\r\n !(n.innerText || n.textContent || '').trim().length) {\r\n const cssText = stringifyStylesheet(n.sheet);\r\n if (cssText) {\r\n attributes._cssText = absoluteToStylesheet(cssText, getHref());\r\n }\r\n }\r\n if (tagName === 'input' || tagName === 'textarea' || tagName === 'select') {\r\n const value = n.value;\r\n const checked = n.checked;\r\n if (attributes.type !== 'radio' &&\r\n attributes.type !== 'checkbox' &&\r\n attributes.type !== 'submit' &&\r\n attributes.type !== 'button' &&\r\n value) {\r\n attributes.value = maskInputValue({\r\n element: n,\r\n type: getInputType(n),\r\n tagName,\r\n value,\r\n maskInputOptions,\r\n maskInputFn,\r\n });\r\n }\r\n else if (checked) {\r\n attributes.checked = checked;\r\n }\r\n }\r\n if (tagName === 'option') {\r\n if (n.selected && !maskInputOptions['select']) {\r\n attributes.selected = true;\r\n }\r\n else {\r\n delete attributes.selected;\r\n }\r\n }\r\n if (tagName === 'canvas' && recordCanvas) {\r\n if (n.__context === '2d') {\r\n if (!is2DCanvasBlank(n)) {\r\n attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n }\r\n }\r\n else if (!('__context' in n)) {\r\n const canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n const blankCanvas = document.createElement('canvas');\r\n blankCanvas.width = n.width;\r\n blankCanvas.height = n.height;\r\n const blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n if (canvasDataURL !== blankCanvasDataURL) {\r\n attributes.rr_dataURL = canvasDataURL;\r\n }\r\n }\r\n }\r\n if (tagName === 'img' && inlineImages) {\r\n if (!canvasService) {\r\n canvasService = doc.createElement('canvas');\r\n canvasCtx = canvasService.getContext('2d');\r\n }\r\n const image = n;\r\n const oldValue = image.crossOrigin;\r\n image.crossOrigin = 'anonymous';\r\n const recordInlineImage = () => {\r\n image.removeEventListener('load', recordInlineImage);\r\n try {\r\n canvasService.width = image.naturalWidth;\r\n canvasService.height = image.naturalHeight;\r\n canvasCtx.drawImage(image, 0, 0);\r\n attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n }\r\n catch (err) {\r\n console.warn(`Cannot inline img src=${image.currentSrc}! Error: ${err}`);\r\n }\r\n oldValue\r\n ? (attributes.crossOrigin = oldValue)\r\n : image.removeAttribute('crossorigin');\r\n };\r\n if (image.complete && image.naturalWidth !== 0)\r\n recordInlineImage();\r\n else\r\n image.addEventListener('load', recordInlineImage);\r\n }\r\n if (tagName === 'audio' || tagName === 'video') {\r\n const mediaAttributes = attributes;\r\n mediaAttributes.rr_mediaState = n.paused\r\n ? 'paused'\r\n : 'played';\r\n mediaAttributes.rr_mediaCurrentTime = n.currentTime;\r\n mediaAttributes.rr_mediaPlaybackRate = n.playbackRate;\r\n mediaAttributes.rr_mediaMuted = n.muted;\r\n mediaAttributes.rr_mediaLoop = n.loop;\r\n mediaAttributes.rr_mediaVolume = n.volume;\r\n }\r\n if (!newlyAddedElement) {\r\n if (n.scrollLeft) {\r\n attributes.rr_scrollLeft = n.scrollLeft;\r\n }\r\n if (n.scrollTop) {\r\n attributes.rr_scrollTop = n.scrollTop;\r\n }\r\n }\r\n if (needBlock) {\r\n const { width, height } = n.getBoundingClientRect();\r\n attributes = {\r\n class: attributes.class,\r\n rr_width: `${width}px`,\r\n rr_height: `${height}px`,\r\n };\r\n }\r\n if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src)) {\r\n if (!n.contentDocument) {\r\n attributes.rr_src = attributes.src;\r\n }\r\n delete attributes.src;\r\n }\r\n let isCustomElement;\r\n try {\r\n if (customElements.get(tagName))\r\n isCustomElement = true;\r\n }\r\n catch (e) {\r\n }\r\n return {\r\n type: NodeType.Element,\r\n tagName,\r\n attributes,\r\n childNodes: [],\r\n isSVG: isSVGElement(n) || undefined,\r\n needBlock,\r\n rootId,\r\n isCustom: isCustomElement,\r\n };\r\n}\r\nfunction lowerIfExists(maybeAttr) {\r\n if (maybeAttr === undefined || maybeAttr === null) {\r\n return '';\r\n }\r\n else {\r\n return maybeAttr.toLowerCase();\r\n }\r\n}\r\nfunction slimDOMExcluded(sn, slimDOMOptions) {\r\n if (slimDOMOptions.comment && sn.type === NodeType.Comment) {\r\n return true;\r\n }\r\n else if (sn.type === NodeType.Element) {\r\n if (slimDOMOptions.script &&\r\n (sn.tagName === 'script' ||\r\n (sn.tagName === 'link' &&\r\n (sn.attributes.rel === 'preload' ||\r\n sn.attributes.rel === 'modulepreload') &&\r\n sn.attributes.as === 'script') ||\r\n (sn.tagName === 'link' &&\r\n sn.attributes.rel === 'prefetch' &&\r\n typeof sn.attributes.href === 'string' &&\r\n extractFileExtension(sn.attributes.href) === 'js'))) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headFavicon &&\r\n ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||\r\n (sn.tagName === 'meta' &&\r\n (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) ||\r\n lowerIfExists(sn.attributes.name) === 'application-name' ||\r\n lowerIfExists(sn.attributes.rel) === 'icon' ||\r\n lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||\r\n lowerIfExists(sn.attributes.rel) === 'shortcut icon')))) {\r\n return true;\r\n }\r\n else if (sn.tagName === 'meta') {\r\n if (slimDOMOptions.headMetaDescKeywords &&\r\n lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaSocial &&\r\n (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) ||\r\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||\r\n lowerIfExists(sn.attributes.name) === 'pinterest')) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaRobots &&\r\n (lowerIfExists(sn.attributes.name) === 'robots' ||\r\n lowerIfExists(sn.attributes.name) === 'googlebot' ||\r\n lowerIfExists(sn.attributes.name) === 'bingbot')) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaHttpEquiv &&\r\n sn.attributes['http-equiv'] !== undefined) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaAuthorship &&\r\n (lowerIfExists(sn.attributes.name) === 'author' ||\r\n lowerIfExists(sn.attributes.name) === 'generator' ||\r\n lowerIfExists(sn.attributes.name) === 'framework' ||\r\n lowerIfExists(sn.attributes.name) === 'publisher' ||\r\n lowerIfExists(sn.attributes.name) === 'progid' ||\r\n lowerIfExists(sn.attributes.property).match(/^article:/) ||\r\n lowerIfExists(sn.attributes.property).match(/^product:/))) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaVerification &&\r\n (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||\r\n lowerIfExists(sn.attributes.name) === 'yandex-verification' ||\r\n lowerIfExists(sn.attributes.name) === 'csrf-token' ||\r\n lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||\r\n lowerIfExists(sn.attributes.name) === 'verify-v1' ||\r\n lowerIfExists(sn.attributes.name) === 'verification' ||\r\n lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n}\r\nfunction serializeNodeWithId(n, options) {\r\n const { doc, mirror, blockClass, blockSelector, maskTextClass, maskTextSelector, skipChild = false, inlineStylesheet = true, maskInputOptions = {}, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions = {}, inlineImages = false, recordCanvas = false, onSerialize, onIframeLoad, iframeLoadTimeout = 5000, onStylesheetLoad, stylesheetLoadTimeout = 5000, keepIframeSrcFn = () => false, newlyAddedElement = false, } = options;\r\n let { needsMask } = options;\r\n let { preserveWhiteSpace = true } = options;\r\n if (!needsMask &&\r\n n.childNodes) {\r\n const checkAncestors = needsMask === undefined;\r\n needsMask = needMaskingText(n, maskTextClass, maskTextSelector, checkAncestors);\r\n }\r\n const _serializedNode = serializeNode(n, {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n needsMask,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskTextFn,\r\n maskInputFn,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n keepIframeSrcFn,\r\n newlyAddedElement,\r\n });\r\n if (!_serializedNode) {\r\n console.warn(n, 'not serialized');\r\n return null;\r\n }\r\n let id;\r\n if (mirror.hasNode(n)) {\r\n id = mirror.getId(n);\r\n }\r\n else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||\r\n (!preserveWhiteSpace &&\r\n _serializedNode.type === NodeType.Text &&\r\n !_serializedNode.isStyle &&\r\n !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, '').length)) {\r\n id = IGNORED_NODE;\r\n }\r\n else {\r\n id = genId();\r\n }\r\n const serializedNode = Object.assign(_serializedNode, { id });\r\n mirror.add(n, serializedNode);\r\n if (id === IGNORED_NODE) {\r\n return null;\r\n }\r\n if (onSerialize) {\r\n onSerialize(n);\r\n }\r\n let recordChild = !skipChild;\r\n if (serializedNode.type === NodeType.Element) {\r\n recordChild = recordChild && !serializedNode.needBlock;\r\n delete serializedNode.needBlock;\r\n const shadowRoot = n.shadowRoot;\r\n if (shadowRoot && isNativeShadowDom(shadowRoot))\r\n serializedNode.isShadowHost = true;\r\n }\r\n if ((serializedNode.type === NodeType.Document ||\r\n serializedNode.type === NodeType.Element) &&\r\n recordChild) {\r\n if (slimDOMOptions.headWhitespace &&\r\n serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'head') {\r\n preserveWhiteSpace = false;\r\n }\r\n const bypassOptions = {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n needsMask,\r\n maskTextClass,\r\n maskTextSelector,\r\n skipChild,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n };\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'textarea' &&\r\n serializedNode.attributes.value !== undefined) ;\r\n else {\r\n for (const childN of Array.from(n.childNodes)) {\r\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\r\n if (serializedChildNode) {\r\n serializedNode.childNodes.push(serializedChildNode);\r\n }\r\n }\r\n }\r\n if (isElement(n) && n.shadowRoot) {\r\n for (const childN of Array.from(n.shadowRoot.childNodes)) {\r\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\r\n if (serializedChildNode) {\r\n isNativeShadowDom(n.shadowRoot) &&\r\n (serializedChildNode.isShadow = true);\r\n serializedNode.childNodes.push(serializedChildNode);\r\n }\r\n }\r\n }\r\n }\r\n if (n.parentNode &&\r\n isShadowRoot(n.parentNode) &&\r\n isNativeShadowDom(n.parentNode)) {\r\n serializedNode.isShadow = true;\r\n }\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'iframe') {\r\n onceIframeLoaded(n, () => {\r\n const iframeDoc = n.contentDocument;\r\n if (iframeDoc && onIframeLoad) {\r\n const serializedIframeNode = serializeNodeWithId(iframeDoc, {\r\n doc: iframeDoc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n needsMask,\r\n maskTextClass,\r\n maskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n });\r\n if (serializedIframeNode) {\r\n onIframeLoad(n, serializedIframeNode);\r\n }\r\n }\r\n }, iframeLoadTimeout);\r\n }\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'link' &&\r\n typeof serializedNode.attributes.rel === 'string' &&\r\n (serializedNode.attributes.rel === 'stylesheet' ||\r\n (serializedNode.attributes.rel === 'preload' &&\r\n typeof serializedNode.attributes.href === 'string' &&\r\n extractFileExtension(serializedNode.attributes.href) === 'css'))) {\r\n onceStylesheetLoaded(n, () => {\r\n if (onStylesheetLoad) {\r\n const serializedLinkNode = serializeNodeWithId(n, {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n needsMask,\r\n maskTextClass,\r\n maskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n });\r\n if (serializedLinkNode) {\r\n onStylesheetLoad(n, serializedLinkNode);\r\n }\r\n }\r\n }, stylesheetLoadTimeout);\r\n }\r\n return serializedNode;\r\n}\r\nfunction snapshot(n, options) {\r\n const { mirror = new Mirror(), blockClass = 'rr-block', blockSelector = null, maskTextClass = 'rr-mask', maskTextSelector = null, inlineStylesheet = true, inlineImages = false, recordCanvas = false, maskAllInputs = false, maskTextFn, maskInputFn, slimDOM = false, dataURLOptions, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, onStylesheetLoad, stylesheetLoadTimeout, keepIframeSrcFn = () => false, } = options || {};\r\n const maskInputOptions = maskAllInputs === true\r\n ? {\r\n color: true,\r\n date: true,\r\n 'datetime-local': true,\r\n email: true,\r\n month: true,\r\n number: true,\r\n range: true,\r\n search: true,\r\n tel: true,\r\n text: true,\r\n time: true,\r\n url: true,\r\n week: true,\r\n textarea: true,\r\n select: true,\r\n password: true,\r\n }\r\n : maskAllInputs === false\r\n ? {\r\n password: true,\r\n }\r\n : maskAllInputs;\r\n const slimDOMOptions = slimDOM === true || slimDOM === 'all'\r\n ?\r\n {\r\n script: true,\r\n comment: true,\r\n headFavicon: true,\r\n headWhitespace: true,\r\n headMetaDescKeywords: slimDOM === 'all',\r\n headMetaSocial: true,\r\n headMetaRobots: true,\r\n headMetaHttpEquiv: true,\r\n headMetaAuthorship: true,\r\n headMetaVerification: true,\r\n }\r\n : slimDOM === false\r\n ? {}\r\n : slimDOM;\r\n return serializeNodeWithId(n, {\r\n doc: n,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n maskTextClass,\r\n maskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n newlyAddedElement: false,\r\n });\r\n}\n\nfunction on(type, fn, target = document) {\r\n const options = { capture: true, passive: true };\r\n target.addEventListener(type, fn, options);\r\n return () => target.removeEventListener(type, fn, options);\r\n}\r\nconst DEPARTED_MIRROR_ACCESS_WARNING = 'Please stop import mirror directly. Instead of that,' +\r\n '\\r\\n' +\r\n 'now you can use replayer.getMirror() to access the mirror instance of a replayer,' +\r\n '\\r\\n' +\r\n 'or you can use record.mirror to access the mirror instance during recording.';\r\nlet _mirror = {\r\n map: {},\r\n getId() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n return -1;\r\n },\r\n getNode() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n return null;\r\n },\r\n removeNodeFromMap() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n },\r\n has() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n return false;\r\n },\r\n reset() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n },\r\n};\r\nif (typeof window !== 'undefined' && window.Proxy && window.Reflect) {\r\n _mirror = new Proxy(_mirror, {\r\n get(target, prop, receiver) {\r\n if (prop === 'map') {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n }\r\n return Reflect.get(target, prop, receiver);\r\n },\r\n });\r\n}\r\nfunction throttle(func, wait, options = {}) {\r\n let timeout = null;\r\n let previous = 0;\r\n return function (...args) {\r\n const now = Date.now();\r\n if (!previous && options.leading === false) {\r\n previous = now;\r\n }\r\n const remaining = wait - (now - previous);\r\n const context = this;\r\n if (remaining <= 0 || remaining > wait) {\r\n if (timeout) {\r\n clearTimeout(timeout);\r\n timeout = null;\r\n }\r\n previous = now;\r\n func.apply(context, args);\r\n }\r\n else if (!timeout && options.trailing !== false) {\r\n timeout = setTimeout(() => {\r\n previous = options.leading === false ? 0 : Date.now();\r\n timeout = null;\r\n func.apply(context, args);\r\n }, remaining);\r\n }\r\n };\r\n}\r\nfunction hookSetter(target, key, d, isRevoked, win = window) {\r\n const original = win.Object.getOwnPropertyDescriptor(target, key);\r\n win.Object.defineProperty(target, key, isRevoked\r\n ? d\r\n : {\r\n set(value) {\r\n setTimeout(() => {\r\n d.set.call(this, value);\r\n }, 0);\r\n if (original && original.set) {\r\n original.set.call(this, value);\r\n }\r\n },\r\n });\r\n return () => hookSetter(target, key, original || {}, true);\r\n}\r\nfunction patch(source, name, replacement) {\r\n try {\r\n if (!(name in source)) {\r\n return () => {\r\n };\r\n }\r\n const original = source[name];\r\n const wrapped = replacement(original);\r\n if (typeof wrapped === 'function') {\r\n wrapped.prototype = wrapped.prototype || {};\r\n Object.defineProperties(wrapped, {\r\n __rrweb_original__: {\r\n enumerable: false,\r\n value: original,\r\n },\r\n });\r\n }\r\n source[name] = wrapped;\r\n return () => {\r\n source[name] = original;\r\n };\r\n }\r\n catch (_a) {\r\n return () => {\r\n };\r\n }\r\n}\r\nlet nowTimestamp = Date.now;\r\nif (!(/[1-9][0-9]{12}/.test(Date.now().toString()))) {\r\n nowTimestamp = () => new Date().getTime();\r\n}\r\nfunction getWindowScroll(win) {\r\n var _a, _b, _c, _d, _e, _f;\r\n const doc = win.document;\r\n return {\r\n left: doc.scrollingElement\r\n ? doc.scrollingElement.scrollLeft\r\n : win.pageXOffset !== undefined\r\n ? win.pageXOffset\r\n : (doc === null || doc === void 0 ? void 0 : doc.documentElement.scrollLeft) ||\r\n ((_b = (_a = doc === null || doc === void 0 ? void 0 : doc.body) === null || _a === void 0 ? void 0 : _a.parentElement) === null || _b === void 0 ? void 0 : _b.scrollLeft) ||\r\n ((_c = doc === null || doc === void 0 ? void 0 : doc.body) === null || _c === void 0 ? void 0 : _c.scrollLeft) ||\r\n 0,\r\n top: doc.scrollingElement\r\n ? doc.scrollingElement.scrollTop\r\n : win.pageYOffset !== undefined\r\n ? win.pageYOffset\r\n : (doc === null || doc === void 0 ? void 0 : doc.documentElement.scrollTop) ||\r\n ((_e = (_d = doc === null || doc === void 0 ? void 0 : doc.body) === null || _d === void 0 ? void 0 : _d.parentElement) === null || _e === void 0 ? void 0 : _e.scrollTop) ||\r\n ((_f = doc === null || doc === void 0 ? void 0 : doc.body) === null || _f === void 0 ? void 0 : _f.scrollTop) ||\r\n 0,\r\n };\r\n}\r\nfunction getWindowHeight() {\r\n return (window.innerHeight ||\r\n (document.documentElement && document.documentElement.clientHeight) ||\r\n (document.body && document.body.clientHeight));\r\n}\r\nfunction getWindowWidth() {\r\n return (window.innerWidth ||\r\n (document.documentElement && document.documentElement.clientWidth) ||\r\n (document.body && document.body.clientWidth));\r\n}\r\nfunction closestElementOfNode(node) {\r\n if (!node) {\r\n return null;\r\n }\r\n const el = node.nodeType === node.ELEMENT_NODE\r\n ? node\r\n : node.parentElement;\r\n return el;\r\n}\r\nfunction isBlocked(node, blockClass, blockSelector, checkAncestors) {\r\n if (!node) {\r\n return false;\r\n }\r\n const el = closestElementOfNode(node);\r\n if (!el) {\r\n return false;\r\n }\r\n try {\r\n if (typeof blockClass === 'string') {\r\n if (el.classList.contains(blockClass))\r\n return true;\r\n if (checkAncestors && el.closest('.' + blockClass) !== null)\r\n return true;\r\n }\r\n else {\r\n if (classMatchesRegex(el, blockClass, checkAncestors))\r\n return true;\r\n }\r\n }\r\n catch (e) {\r\n }\r\n if (blockSelector) {\r\n if (el.matches(blockSelector))\r\n return true;\r\n if (checkAncestors && el.closest(blockSelector) !== null)\r\n return true;\r\n }\r\n return false;\r\n}\r\nfunction isSerialized(n, mirror) {\r\n return mirror.getId(n) !== -1;\r\n}\r\nfunction isIgnored(n, mirror) {\r\n return mirror.getId(n) === IGNORED_NODE;\r\n}\r\nfunction isAncestorRemoved(target, mirror) {\r\n if (isShadowRoot(target)) {\r\n return false;\r\n }\r\n const id = mirror.getId(target);\r\n if (!mirror.has(id)) {\r\n return true;\r\n }\r\n if (target.parentNode &&\r\n target.parentNode.nodeType === target.DOCUMENT_NODE) {\r\n return false;\r\n }\r\n if (!target.parentNode) {\r\n return true;\r\n }\r\n return isAncestorRemoved(target.parentNode, mirror);\r\n}\r\nfunction legacy_isTouchEvent(event) {\r\n return Boolean(event.changedTouches);\r\n}\r\nfunction polyfill(win = window) {\r\n if ('NodeList' in win && !win.NodeList.prototype.forEach) {\r\n win.NodeList.prototype.forEach = Array.prototype\r\n .forEach;\r\n }\r\n if ('DOMTokenList' in win && !win.DOMTokenList.prototype.forEach) {\r\n win.DOMTokenList.prototype.forEach = Array.prototype\r\n .forEach;\r\n }\r\n if (!Node.prototype.contains) {\r\n Node.prototype.contains = (...args) => {\r\n let node = args[0];\r\n if (!(0 in args)) {\r\n throw new TypeError('1 argument is required');\r\n }\r\n do {\r\n if (this === node) {\r\n return true;\r\n }\r\n } while ((node = node && node.parentNode));\r\n return false;\r\n };\r\n }\r\n}\r\nfunction isSerializedIframe(n, mirror) {\r\n return Boolean(n.nodeName === 'IFRAME' && mirror.getMeta(n));\r\n}\r\nfunction isSerializedStylesheet(n, mirror) {\r\n return Boolean(n.nodeName === 'LINK' &&\r\n n.nodeType === n.ELEMENT_NODE &&\r\n n.getAttribute &&\r\n n.getAttribute('rel') === 'stylesheet' &&\r\n mirror.getMeta(n));\r\n}\r\nfunction hasShadowRoot(n) {\r\n return Boolean(n === null || n === void 0 ? void 0 : n.shadowRoot);\r\n}\r\nclass StyleSheetMirror {\r\n constructor() {\r\n this.id = 1;\r\n this.styleIDMap = new WeakMap();\r\n this.idStyleMap = new Map();\r\n }\r\n getId(stylesheet) {\r\n var _a;\r\n return (_a = this.styleIDMap.get(stylesheet)) !== null && _a !== void 0 ? _a : -1;\r\n }\r\n has(stylesheet) {\r\n return this.styleIDMap.has(stylesheet);\r\n }\r\n add(stylesheet, id) {\r\n if (this.has(stylesheet))\r\n return this.getId(stylesheet);\r\n let newId;\r\n if (id === undefined) {\r\n newId = this.id++;\r\n }\r\n else\r\n newId = id;\r\n this.styleIDMap.set(stylesheet, newId);\r\n this.idStyleMap.set(newId, stylesheet);\r\n return newId;\r\n }\r\n getStyle(id) {\r\n return this.idStyleMap.get(id) || null;\r\n }\r\n reset() {\r\n this.styleIDMap = new WeakMap();\r\n this.idStyleMap = new Map();\r\n this.id = 1;\r\n }\r\n generateId() {\r\n return this.id++;\r\n }\r\n}\r\nfunction getShadowHost(n) {\r\n var _a, _b;\r\n let shadowHost = null;\r\n if (((_b = (_a = n.getRootNode) === null || _a === void 0 ? void 0 : _a.call(n)) === null || _b === void 0 ? void 0 : _b.nodeType) === Node.DOCUMENT_FRAGMENT_NODE &&\r\n n.getRootNode().host)\r\n shadowHost = n.getRootNode().host;\r\n return shadowHost;\r\n}\r\nfunction getRootShadowHost(n) {\r\n let rootShadowHost = n;\r\n let shadowHost;\r\n while ((shadowHost = getShadowHost(rootShadowHost)))\r\n rootShadowHost = shadowHost;\r\n return rootShadowHost;\r\n}\r\nfunction shadowHostInDom(n) {\r\n const doc = n.ownerDocument;\r\n if (!doc)\r\n return false;\r\n const shadowHost = getRootShadowHost(n);\r\n return doc.contains(shadowHost);\r\n}\r\nfunction inDom(n) {\r\n const doc = n.ownerDocument;\r\n if (!doc)\r\n return false;\r\n return doc.contains(n) || shadowHostInDom(n);\r\n}\n\nvar EventType$1 = /* @__PURE__ */ ((EventType2) => {\n EventType2[EventType2[\"DomContentLoaded\"] = 0] = \"DomContentLoaded\";\n EventType2[EventType2[\"Load\"] = 1] = \"Load\";\n EventType2[EventType2[\"FullSnapshot\"] = 2] = \"FullSnapshot\";\n EventType2[EventType2[\"IncrementalSnapshot\"] = 3] = \"IncrementalSnapshot\";\n EventType2[EventType2[\"Meta\"] = 4] = \"Meta\";\n EventType2[EventType2[\"Custom\"] = 5] = \"Custom\";\n EventType2[EventType2[\"Plugin\"] = 6] = \"Plugin\";\n return EventType2;\n})(EventType$1 || {});\nvar IncrementalSource$1 = /* @__PURE__ */ ((IncrementalSource2) => {\n IncrementalSource2[IncrementalSource2[\"Mutation\"] = 0] = \"Mutation\";\n IncrementalSource2[IncrementalSource2[\"MouseMove\"] = 1] = \"MouseMove\";\n IncrementalSource2[IncrementalSource2[\"MouseInteraction\"] = 2] = \"MouseInteraction\";\n IncrementalSource2[IncrementalSource2[\"Scroll\"] = 3] = \"Scroll\";\n IncrementalSource2[IncrementalSource2[\"ViewportResize\"] = 4] = \"ViewportResize\";\n IncrementalSource2[IncrementalSource2[\"Input\"] = 5] = \"Input\";\n IncrementalSource2[IncrementalSource2[\"TouchMove\"] = 6] = \"TouchMove\";\n IncrementalSource2[IncrementalSource2[\"MediaInteraction\"] = 7] = \"MediaInteraction\";\n IncrementalSource2[IncrementalSource2[\"StyleSheetRule\"] = 8] = \"StyleSheetRule\";\n IncrementalSource2[IncrementalSource2[\"CanvasMutation\"] = 9] = \"CanvasMutation\";\n IncrementalSource2[IncrementalSource2[\"Font\"] = 10] = \"Font\";\n IncrementalSource2[IncrementalSource2[\"Log\"] = 11] = \"Log\";\n IncrementalSource2[IncrementalSource2[\"Drag\"] = 12] = \"Drag\";\n IncrementalSource2[IncrementalSource2[\"StyleDeclaration\"] = 13] = \"StyleDeclaration\";\n IncrementalSource2[IncrementalSource2[\"Selection\"] = 14] = \"Selection\";\n IncrementalSource2[IncrementalSource2[\"AdoptedStyleSheet\"] = 15] = \"AdoptedStyleSheet\";\n IncrementalSource2[IncrementalSource2[\"CustomElement\"] = 16] = \"CustomElement\";\n return IncrementalSource2;\n})(IncrementalSource$1 || {});\nvar MouseInteractions = /* @__PURE__ */ ((MouseInteractions2) => {\n MouseInteractions2[MouseInteractions2[\"MouseUp\"] = 0] = \"MouseUp\";\n MouseInteractions2[MouseInteractions2[\"MouseDown\"] = 1] = \"MouseDown\";\n MouseInteractions2[MouseInteractions2[\"Click\"] = 2] = \"Click\";\n MouseInteractions2[MouseInteractions2[\"ContextMenu\"] = 3] = \"ContextMenu\";\n MouseInteractions2[MouseInteractions2[\"DblClick\"] = 4] = \"DblClick\";\n MouseInteractions2[MouseInteractions2[\"Focus\"] = 5] = \"Focus\";\n MouseInteractions2[MouseInteractions2[\"Blur\"] = 6] = \"Blur\";\n MouseInteractions2[MouseInteractions2[\"TouchStart\"] = 7] = \"TouchStart\";\n MouseInteractions2[MouseInteractions2[\"TouchMove_Departed\"] = 8] = \"TouchMove_Departed\";\n MouseInteractions2[MouseInteractions2[\"TouchEnd\"] = 9] = \"TouchEnd\";\n MouseInteractions2[MouseInteractions2[\"TouchCancel\"] = 10] = \"TouchCancel\";\n return MouseInteractions2;\n})(MouseInteractions || {});\nvar PointerTypes = /* @__PURE__ */ ((PointerTypes2) => {\n PointerTypes2[PointerTypes2[\"Mouse\"] = 0] = \"Mouse\";\n PointerTypes2[PointerTypes2[\"Pen\"] = 1] = \"Pen\";\n PointerTypes2[PointerTypes2[\"Touch\"] = 2] = \"Touch\";\n return PointerTypes2;\n})(PointerTypes || {});\nvar CanvasContext = /* @__PURE__ */ ((CanvasContext2) => {\n CanvasContext2[CanvasContext2[\"2D\"] = 0] = \"2D\";\n CanvasContext2[CanvasContext2[\"WebGL\"] = 1] = \"WebGL\";\n CanvasContext2[CanvasContext2[\"WebGL2\"] = 2] = \"WebGL2\";\n return CanvasContext2;\n})(CanvasContext || {});\n\nfunction isNodeInLinkedList(n) {\r\n return '__ln' in n;\r\n}\r\nclass DoubleLinkedList {\r\n constructor() {\r\n this.length = 0;\r\n this.head = null;\r\n this.tail = null;\r\n }\r\n get(position) {\r\n if (position >= this.length) {\r\n throw new Error('Position outside of list range');\r\n }\r\n let current = this.head;\r\n for (let index = 0; index < position; index++) {\r\n current = (current === null || current === void 0 ? void 0 : current.next) || null;\r\n }\r\n return current;\r\n }\r\n addNode(n) {\r\n const node = {\r\n value: n,\r\n previous: null,\r\n next: null,\r\n };\r\n n.__ln = node;\r\n if (n.previousSibling && isNodeInLinkedList(n.previousSibling)) {\r\n const current = n.previousSibling.__ln.next;\r\n node.next = current;\r\n node.previous = n.previousSibling.__ln;\r\n n.previousSibling.__ln.next = node;\r\n if (current) {\r\n current.previous = node;\r\n }\r\n }\r\n else if (n.nextSibling &&\r\n isNodeInLinkedList(n.nextSibling) &&\r\n n.nextSibling.__ln.previous) {\r\n const current = n.nextSibling.__ln.previous;\r\n node.previous = current;\r\n node.next = n.nextSibling.__ln;\r\n n.nextSibling.__ln.previous = node;\r\n if (current) {\r\n current.next = node;\r\n }\r\n }\r\n else {\r\n if (this.head) {\r\n this.head.previous = node;\r\n }\r\n node.next = this.head;\r\n this.head = node;\r\n }\r\n if (node.next === null) {\r\n this.tail = node;\r\n }\r\n this.length++;\r\n }\r\n removeNode(n) {\r\n const current = n.__ln;\r\n if (!this.head) {\r\n return;\r\n }\r\n if (!current.previous) {\r\n this.head = current.next;\r\n if (this.head) {\r\n this.head.previous = null;\r\n }\r\n else {\r\n this.tail = null;\r\n }\r\n }\r\n else {\r\n current.previous.next = current.next;\r\n if (current.next) {\r\n current.next.previous = current.previous;\r\n }\r\n else {\r\n this.tail = current.previous;\r\n }\r\n }\r\n if (n.__ln) {\r\n delete n.__ln;\r\n }\r\n this.length--;\r\n }\r\n}\r\nconst moveKey = (id, parentId) => `${id}@${parentId}`;\r\nclass MutationBuffer {\r\n constructor() {\r\n this.frozen = false;\r\n this.locked = false;\r\n this.texts = [];\r\n this.attributes = [];\r\n this.attributeMap = new WeakMap();\r\n this.removes = [];\r\n this.mapRemoves = [];\r\n this.movedMap = {};\r\n this.addedSet = new Set();\r\n this.movedSet = new Set();\r\n this.droppedSet = new Set();\r\n this.processMutations = (mutations) => {\r\n mutations.forEach(this.processMutation);\r\n this.emit();\r\n };\r\n this.emit = () => {\r\n if (this.frozen || this.locked) {\r\n return;\r\n }\r\n const adds = [];\r\n const addedIds = new Set();\r\n const addList = new DoubleLinkedList();\r\n const getNextId = (n) => {\r\n let ns = n;\r\n let nextId = IGNORED_NODE;\r\n while (nextId === IGNORED_NODE) {\r\n ns = ns && ns.nextSibling;\r\n nextId = ns && this.mirror.getId(ns);\r\n }\r\n return nextId;\r\n };\r\n const pushAdd = (n) => {\r\n if (!n.parentNode ||\r\n !inDom(n) ||\r\n n.parentNode.tagName === 'TEXTAREA') {\r\n return;\r\n }\r\n const parentId = isShadowRoot(n.parentNode)\r\n ? this.mirror.getId(getShadowHost(n))\r\n : this.mirror.getId(n.parentNode);\r\n const nextId = getNextId(n);\r\n if (parentId === -1 || nextId === -1) {\r\n return addList.addNode(n);\r\n }\r\n const sn = serializeNodeWithId(n, {\r\n doc: this.doc,\r\n mirror: this.mirror,\r\n blockClass: this.blockClass,\r\n blockSelector: this.blockSelector,\r\n maskTextClass: this.maskTextClass,\r\n maskTextSelector: this.maskTextSelector,\r\n skipChild: true,\r\n newlyAddedElement: true,\r\n inlineStylesheet: this.inlineStylesheet,\r\n maskInputOptions: this.maskInputOptions,\r\n maskTextFn: this.maskTextFn,\r\n maskInputFn: this.maskInputFn,\r\n slimDOMOptions: this.slimDOMOptions,\r\n dataURLOptions: this.dataURLOptions,\r\n recordCanvas: this.recordCanvas,\r\n inlineImages: this.inlineImages,\r\n onSerialize: (currentN) => {\r\n if (isSerializedIframe(currentN, this.mirror)) {\r\n this.iframeManager.addIframe(currentN);\r\n }\r\n if (isSerializedStylesheet(currentN, this.mirror)) {\r\n this.stylesheetManager.trackLinkElement(currentN);\r\n }\r\n if (hasShadowRoot(n)) {\r\n this.shadowDomManager.addShadowRoot(n.shadowRoot, this.doc);\r\n }\r\n },\r\n onIframeLoad: (iframe, childSn) => {\r\n this.iframeManager.attachIframe(iframe, childSn);\r\n this.shadowDomManager.observeAttachShadow(iframe);\r\n },\r\n onStylesheetLoad: (link, childSn) => {\r\n this.stylesheetManager.attachLinkElement(link, childSn);\r\n },\r\n });\r\n if (sn) {\r\n adds.push({\r\n parentId,\r\n nextId,\r\n node: sn,\r\n });\r\n addedIds.add(sn.id);\r\n }\r\n };\r\n while (this.mapRemoves.length) {\r\n this.mirror.removeNodeFromMap(this.mapRemoves.shift());\r\n }\r\n for (const n of this.movedSet) {\r\n if (isParentRemoved(this.removes, n, this.mirror) &&\r\n !this.movedSet.has(n.parentNode)) {\r\n continue;\r\n }\r\n pushAdd(n);\r\n }\r\n for (const n of this.addedSet) {\r\n if (!isAncestorInSet(this.droppedSet, n) &&\r\n !isParentRemoved(this.removes, n, this.mirror)) {\r\n pushAdd(n);\r\n }\r\n else if (isAncestorInSet(this.movedSet, n)) {\r\n pushAdd(n);\r\n }\r\n else {\r\n this.droppedSet.add(n);\r\n }\r\n }\r\n let candidate = null;\r\n while (addList.length) {\r\n let node = null;\r\n if (candidate) {\r\n const parentId = this.mirror.getId(candidate.value.parentNode);\r\n const nextId = getNextId(candidate.value);\r\n if (parentId !== -1 && nextId !== -1) {\r\n node = candidate;\r\n }\r\n }\r\n if (!node) {\r\n let tailNode = addList.tail;\r\n while (tailNode) {\r\n const _node = tailNode;\r\n tailNode = tailNode.previous;\r\n if (_node) {\r\n const parentId = this.mirror.getId(_node.value.parentNode);\r\n const nextId = getNextId(_node.value);\r\n if (nextId === -1)\r\n continue;\r\n else if (parentId !== -1) {\r\n node = _node;\r\n break;\r\n }\r\n else {\r\n const unhandledNode = _node.value;\r\n if (unhandledNode.parentNode &&\r\n unhandledNode.parentNode.nodeType ===\r\n Node.DOCUMENT_FRAGMENT_NODE) {\r\n const shadowHost = unhandledNode.parentNode\r\n .host;\r\n const parentId = this.mirror.getId(shadowHost);\r\n if (parentId !== -1) {\r\n node = _node;\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n if (!node) {\r\n while (addList.head) {\r\n addList.removeNode(addList.head.value);\r\n }\r\n break;\r\n }\r\n candidate = node.previous;\r\n addList.removeNode(node.value);\r\n pushAdd(node.value);\r\n }\r\n const payload = {\r\n texts: this.texts\r\n .map((text) => {\r\n const n = text.node;\r\n if (n.parentNode &&\r\n n.parentNode.tagName === 'TEXTAREA') {\r\n this.genTextAreaValueMutation(n.parentNode);\r\n }\r\n return {\r\n id: this.mirror.getId(n),\r\n value: text.value,\r\n };\r\n })\r\n .filter((text) => !addedIds.has(text.id))\r\n .filter((text) => this.mirror.has(text.id)),\r\n attributes: this.attributes\r\n .map((attribute) => {\r\n const { attributes } = attribute;\r\n if (typeof attributes.style === 'string') {\r\n const diffAsStr = JSON.stringify(attribute.styleDiff);\r\n const unchangedAsStr = JSON.stringify(attribute._unchangedStyles);\r\n if (diffAsStr.length < attributes.style.length) {\r\n if ((diffAsStr + unchangedAsStr).split('var(').length ===\r\n attributes.style.split('var(').length) {\r\n attributes.style = attribute.styleDiff;\r\n }\r\n }\r\n }\r\n return {\r\n id: this.mirror.getId(attribute.node),\r\n attributes: attributes,\r\n };\r\n })\r\n .filter((attribute) => !addedIds.has(attribute.id))\r\n .filter((attribute) => this.mirror.has(attribute.id)),\r\n removes: this.removes,\r\n adds,\r\n };\r\n if (!payload.texts.length &&\r\n !payload.attributes.length &&\r\n !payload.removes.length &&\r\n !payload.adds.length) {\r\n return;\r\n }\r\n this.texts = [];\r\n this.attributes = [];\r\n this.attributeMap = new WeakMap();\r\n this.removes = [];\r\n this.addedSet = new Set();\r\n this.movedSet = new Set();\r\n this.droppedSet = new Set();\r\n this.movedMap = {};\r\n this.mutationCb(payload);\r\n };\r\n this.genTextAreaValueMutation = (textarea) => {\r\n let item = this.attributeMap.get(textarea);\r\n if (!item) {\r\n item = {\r\n node: textarea,\r\n attributes: {},\r\n styleDiff: {},\r\n _unchangedStyles: {},\r\n };\r\n this.attributes.push(item);\r\n this.attributeMap.set(textarea, item);\r\n }\r\n item.attributes.value = Array.from(textarea.childNodes, (cn) => cn.textContent || '').join('');\r\n };\r\n this.processMutation = (m) => {\r\n if (isIgnored(m.target, this.mirror)) {\r\n return;\r\n }\r\n switch (m.type) {\r\n case 'characterData': {\r\n const value = m.target.textContent;\r\n if (!isBlocked(m.target, this.blockClass, this.blockSelector, false) &&\r\n value !== m.oldValue) {\r\n this.texts.push({\r\n value: needMaskingText(m.target, this.maskTextClass, this.maskTextSelector, true) && value\r\n ? this.maskTextFn\r\n ? this.maskTextFn(value, closestElementOfNode(m.target))\r\n : value.replace(/[\\S]/g, '*')\r\n : value,\r\n node: m.target,\r\n });\r\n }\r\n break;\r\n }\r\n case 'attributes': {\r\n const target = m.target;\r\n let attributeName = m.attributeName;\r\n let value = m.target.getAttribute(attributeName);\r\n if (attributeName === 'value') {\r\n const type = getInputType(target);\r\n value = maskInputValue({\r\n element: target,\r\n maskInputOptions: this.maskInputOptions,\r\n tagName: target.tagName,\r\n type,\r\n value,\r\n maskInputFn: this.maskInputFn,\r\n });\r\n }\r\n if (isBlocked(m.target, this.blockClass, this.blockSelector, false) ||\r\n value === m.oldValue) {\r\n return;\r\n }\r\n let item = this.attributeMap.get(m.target);\r\n if (target.tagName === 'IFRAME' &&\r\n attributeName === 'src' &&\r\n !this.keepIframeSrcFn(value)) {\r\n if (!target.contentDocument) {\r\n attributeName = 'rr_src';\r\n }\r\n else {\r\n return;\r\n }\r\n }\r\n if (!item) {\r\n item = {\r\n node: m.target,\r\n attributes: {},\r\n styleDiff: {},\r\n _unchangedStyles: {},\r\n };\r\n this.attributes.push(item);\r\n this.attributeMap.set(m.target, item);\r\n }\r\n if (attributeName === 'type' &&\r\n target.tagName === 'INPUT' &&\r\n (m.oldValue || '').toLowerCase() === 'password') {\r\n target.setAttribute('data-rr-is-password', 'true');\r\n }\r\n if (!ignoreAttribute(target.tagName, attributeName)) {\r\n item.attributes[attributeName] = transformAttribute(this.doc, toLowerCase(target.tagName), toLowerCase(attributeName), value);\r\n if (attributeName === 'style') {\r\n if (!this.unattachedDoc) {\r\n try {\r\n this.unattachedDoc =\r\n document.implementation.createHTMLDocument();\r\n }\r\n catch (e) {\r\n this.unattachedDoc = this.doc;\r\n }\r\n }\r\n const old = this.unattachedDoc.createElement('span');\r\n if (m.oldValue) {\r\n old.setAttribute('style', m.oldValue);\r\n }\r\n for (const pname of Array.from(target.style)) {\r\n const newValue = target.style.getPropertyValue(pname);\r\n const newPriority = target.style.getPropertyPriority(pname);\r\n if (newValue !== old.style.getPropertyValue(pname) ||\r\n newPriority !== old.style.getPropertyPriority(pname)) {\r\n if (newPriority === '') {\r\n item.styleDiff[pname] = newValue;\r\n }\r\n else {\r\n item.styleDiff[pname] = [newValue, newPriority];\r\n }\r\n }\r\n else {\r\n item._unchangedStyles[pname] = [newValue, newPriority];\r\n }\r\n }\r\n for (const pname of Array.from(old.style)) {\r\n if (target.style.getPropertyValue(pname) === '') {\r\n item.styleDiff[pname] = false;\r\n }\r\n }\r\n }\r\n }\r\n break;\r\n }\r\n case 'childList': {\r\n if (isBlocked(m.target, this.blockClass, this.blockSelector, true))\r\n return;\r\n if (m.target.tagName === 'TEXTAREA') {\r\n this.genTextAreaValueMutation(m.target);\r\n return;\r\n }\r\n m.addedNodes.forEach((n) => this.genAdds(n, m.target));\r\n m.removedNodes.forEach((n) => {\r\n const nodeId = this.mirror.getId(n);\r\n const parentId = isShadowRoot(m.target)\r\n ? this.mirror.getId(m.target.host)\r\n : this.mirror.getId(m.target);\r\n if (isBlocked(m.target, this.blockClass, this.blockSelector, false) ||\r\n isIgnored(n, this.mirror) ||\r\n !isSerialized(n, this.mirror)) {\r\n return;\r\n }\r\n if (this.addedSet.has(n)) {\r\n deepDelete(this.addedSet, n);\r\n this.droppedSet.add(n);\r\n }\r\n else if (this.addedSet.has(m.target) && nodeId === -1) ;\r\n else if (isAncestorRemoved(m.target, this.mirror)) ;\r\n else if (this.movedSet.has(n) &&\r\n this.movedMap[moveKey(nodeId, parentId)]) {\r\n deepDelete(this.movedSet, n);\r\n }\r\n else {\r\n this.removes.push({\r\n parentId,\r\n id: nodeId,\r\n isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target)\r\n ? true\r\n : undefined,\r\n });\r\n }\r\n this.mapRemoves.push(n);\r\n });\r\n break;\r\n }\r\n }\r\n };\r\n this.genAdds = (n, target) => {\r\n if (this.processedNodeManager.inOtherBuffer(n, this))\r\n return;\r\n if (this.addedSet.has(n) || this.movedSet.has(n))\r\n return;\r\n if (this.mirror.hasNode(n)) {\r\n if (isIgnored(n, this.mirror)) {\r\n return;\r\n }\r\n this.movedSet.add(n);\r\n let targetId = null;\r\n if (target && this.mirror.hasNode(target)) {\r\n targetId = this.mirror.getId(target);\r\n }\r\n if (targetId && targetId !== -1) {\r\n this.movedMap[moveKey(this.mirror.getId(n), targetId)] = true;\r\n }\r\n }\r\n else {\r\n this.addedSet.add(n);\r\n this.droppedSet.delete(n);\r\n }\r\n if (!isBlocked(n, this.blockClass, this.blockSelector, false)) {\r\n n.childNodes.forEach((childN) => this.genAdds(childN));\r\n if (hasShadowRoot(n)) {\r\n n.shadowRoot.childNodes.forEach((childN) => {\r\n this.processedNodeManager.add(childN, this);\r\n this.genAdds(childN, n);\r\n });\r\n }\r\n }\r\n };\r\n }\r\n init(options) {\r\n [\r\n 'mutationCb',\r\n 'blockClass',\r\n 'blockSelector',\r\n 'maskTextClass',\r\n 'maskTextSelector',\r\n 'inlineStylesheet',\r\n 'maskInputOptions',\r\n 'maskTextFn',\r\n 'maskInputFn',\r\n 'keepIframeSrcFn',\r\n 'recordCanvas',\r\n 'inlineImages',\r\n 'slimDOMOptions',\r\n 'dataURLOptions',\r\n 'doc',\r\n 'mirror',\r\n 'iframeManager',\r\n 'stylesheetManager',\r\n 'shadowDomManager',\r\n 'canvasManager',\r\n 'processedNodeManager',\r\n ].forEach((key) => {\r\n this[key] = options[key];\r\n });\r\n }\r\n freeze() {\r\n this.frozen = true;\r\n this.canvasManager.freeze();\r\n }\r\n unfreeze() {\r\n this.frozen = false;\r\n this.canvasManager.unfreeze();\r\n this.emit();\r\n }\r\n isFrozen() {\r\n return this.frozen;\r\n }\r\n lock() {\r\n this.locked = true;\r\n this.canvasManager.lock();\r\n }\r\n unlock() {\r\n this.locked = false;\r\n this.canvasManager.unlock();\r\n this.emit();\r\n }\r\n reset() {\r\n this.shadowDomManager.reset();\r\n this.canvasManager.reset();\r\n }\r\n}\r\nfunction deepDelete(addsSet, n) {\r\n addsSet.delete(n);\r\n n.childNodes.forEach((childN) => deepDelete(addsSet, childN));\r\n}\r\nfunction isParentRemoved(removes, n, mirror) {\r\n if (removes.length === 0)\r\n return false;\r\n return _isParentRemoved(removes, n, mirror);\r\n}\r\nfunction _isParentRemoved(removes, n, mirror) {\r\n const { parentNode } = n;\r\n if (!parentNode) {\r\n return false;\r\n }\r\n const parentId = mirror.getId(parentNode);\r\n if (removes.some((r) => r.id === parentId)) {\r\n return true;\r\n }\r\n return _isParentRemoved(removes, parentNode, mirror);\r\n}\r\nfunction isAncestorInSet(set, n) {\r\n if (set.size === 0)\r\n return false;\r\n return _isAncestorInSet(set, n);\r\n}\r\nfunction _isAncestorInSet(set, n) {\r\n const { parentNode } = n;\r\n if (!parentNode) {\r\n return false;\r\n }\r\n if (set.has(parentNode)) {\r\n return true;\r\n }\r\n return _isAncestorInSet(set, parentNode);\r\n}\n\nlet errorHandler;\r\nfunction registerErrorHandler(handler) {\r\n errorHandler = handler;\r\n}\r\nfunction unregisterErrorHandler() {\r\n errorHandler = undefined;\r\n}\r\nconst callbackWrapper = (cb) => {\r\n if (!errorHandler) {\r\n return cb;\r\n }\r\n const rrwebWrapped = ((...rest) => {\r\n try {\r\n return cb(...rest);\r\n }\r\n catch (error) {\r\n if (errorHandler && errorHandler(error) === true) {\r\n return;\r\n }\r\n throw error;\r\n }\r\n });\r\n return rrwebWrapped;\r\n};\n\nconst mutationBuffers = [];\r\nfunction getEventTarget(event) {\r\n try {\r\n if ('composedPath' in event) {\r\n const path = event.composedPath();\r\n if (path.length) {\r\n return path[0];\r\n }\r\n }\r\n else if ('path' in event && event.path.length) {\r\n return event.path[0];\r\n }\r\n }\r\n catch (_a) {\r\n }\r\n return event && event.target;\r\n}\r\nfunction initMutationObserver(options, rootEl) {\r\n var _a, _b;\r\n const mutationBuffer = new MutationBuffer();\r\n mutationBuffers.push(mutationBuffer);\r\n mutationBuffer.init(options);\r\n let mutationObserverCtor = window.MutationObserver ||\r\n window.__rrMutationObserver;\r\n const angularZoneSymbol = (_b = (_a = window === null || window === void 0 ? void 0 : window.Zone) === null || _a === void 0 ? void 0 : _a.__symbol__) === null || _b === void 0 ? void 0 : _b.call(_a, 'MutationObserver');\r\n if (angularZoneSymbol &&\r\n window[angularZoneSymbol]) {\r\n mutationObserverCtor = window[angularZoneSymbol];\r\n }\r\n const observer = new mutationObserverCtor(callbackWrapper(mutationBuffer.processMutations.bind(mutationBuffer)));\r\n observer.observe(rootEl, {\r\n attributes: true,\r\n attributeOldValue: true,\r\n characterData: true,\r\n characterDataOldValue: true,\r\n childList: true,\r\n subtree: true,\r\n });\r\n return observer;\r\n}\r\nfunction initMoveObserver({ mousemoveCb, sampling, doc, mirror, }) {\r\n if (sampling.mousemove === false) {\r\n return () => {\r\n };\r\n }\r\n const threshold = typeof sampling.mousemove === 'number' ? sampling.mousemove : 50;\r\n const callbackThreshold = typeof sampling.mousemoveCallback === 'number'\r\n ? sampling.mousemoveCallback\r\n : 500;\r\n let positions = [];\r\n let timeBaseline;\r\n const wrappedCb = throttle(callbackWrapper((source) => {\r\n const totalOffset = Date.now() - timeBaseline;\r\n mousemoveCb(positions.map((p) => {\r\n p.timeOffset -= totalOffset;\r\n return p;\r\n }), source);\r\n positions = [];\r\n timeBaseline = null;\r\n }), callbackThreshold);\r\n const updatePosition = callbackWrapper(throttle(callbackWrapper((evt) => {\r\n const target = getEventTarget(evt);\r\n const { clientX, clientY } = legacy_isTouchEvent(evt)\r\n ? evt.changedTouches[0]\r\n : evt;\r\n if (!timeBaseline) {\r\n timeBaseline = nowTimestamp();\r\n }\r\n positions.push({\r\n x: clientX,\r\n y: clientY,\r\n id: mirror.getId(target),\r\n timeOffset: nowTimestamp() - timeBaseline,\r\n });\r\n wrappedCb(typeof DragEvent !== 'undefined' && evt instanceof DragEvent\r\n ? IncrementalSource$1.Drag\r\n : evt instanceof MouseEvent\r\n ? IncrementalSource$1.MouseMove\r\n : IncrementalSource$1.TouchMove);\r\n }), threshold, {\r\n trailing: false,\r\n }));\r\n const handlers = [\r\n on('mousemove', updatePosition, doc),\r\n on('touchmove', updatePosition, doc),\r\n on('drag', updatePosition, doc),\r\n ];\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initMouseInteractionObserver({ mouseInteractionCb, doc, mirror, blockClass, blockSelector, sampling, }) {\r\n if (sampling.mouseInteraction === false) {\r\n return () => {\r\n };\r\n }\r\n const disableMap = sampling.mouseInteraction === true ||\r\n sampling.mouseInteraction === undefined\r\n ? {}\r\n : sampling.mouseInteraction;\r\n const handlers = [];\r\n let currentPointerType = null;\r\n const getHandler = (eventKey) => {\r\n return (event) => {\r\n const target = getEventTarget(event);\r\n if (isBlocked(target, blockClass, blockSelector, true)) {\r\n return;\r\n }\r\n let pointerType = null;\r\n let thisEventKey = eventKey;\r\n if ('pointerType' in event) {\r\n switch (event.pointerType) {\r\n case 'mouse':\r\n pointerType = PointerTypes.Mouse;\r\n break;\r\n case 'touch':\r\n pointerType = PointerTypes.Touch;\r\n break;\r\n case 'pen':\r\n pointerType = PointerTypes.Pen;\r\n break;\r\n }\r\n if (pointerType === PointerTypes.Touch) {\r\n if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) {\r\n thisEventKey = 'TouchStart';\r\n }\r\n else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) {\r\n thisEventKey = 'TouchEnd';\r\n }\r\n }\r\n else if (pointerType === PointerTypes.Pen) ;\r\n }\r\n else if (legacy_isTouchEvent(event)) {\r\n pointerType = PointerTypes.Touch;\r\n }\r\n if (pointerType !== null) {\r\n currentPointerType = pointerType;\r\n if ((thisEventKey.startsWith('Touch') &&\r\n pointerType === PointerTypes.Touch) ||\r\n (thisEventKey.startsWith('Mouse') &&\r\n pointerType === PointerTypes.Mouse)) {\r\n pointerType = null;\r\n }\r\n }\r\n else if (MouseInteractions[eventKey] === MouseInteractions.Click) {\r\n pointerType = currentPointerType;\r\n currentPointerType = null;\r\n }\r\n const e = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;\r\n if (!e) {\r\n return;\r\n }\r\n const id = mirror.getId(target);\r\n const { clientX, clientY } = e;\r\n callbackWrapper(mouseInteractionCb)(Object.assign({ type: MouseInteractions[thisEventKey], id, x: clientX, y: clientY }, (pointerType !== null && { pointerType })));\r\n };\r\n };\r\n Object.keys(MouseInteractions)\r\n .filter((key) => Number.isNaN(Number(key)) &&\r\n !key.endsWith('_Departed') &&\r\n disableMap[key] !== false)\r\n .forEach((eventKey) => {\r\n let eventName = toLowerCase(eventKey);\r\n const handler = getHandler(eventKey);\r\n if (window.PointerEvent) {\r\n switch (MouseInteractions[eventKey]) {\r\n case MouseInteractions.MouseDown:\r\n case MouseInteractions.MouseUp:\r\n eventName = eventName.replace('mouse', 'pointer');\r\n break;\r\n case MouseInteractions.TouchStart:\r\n case MouseInteractions.TouchEnd:\r\n return;\r\n }\r\n }\r\n handlers.push(on(eventName, handler, doc));\r\n });\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initScrollObserver({ scrollCb, doc, mirror, blockClass, blockSelector, sampling, }) {\r\n const updatePosition = callbackWrapper(throttle(callbackWrapper((evt) => {\r\n const target = getEventTarget(evt);\r\n if (!target ||\r\n isBlocked(target, blockClass, blockSelector, true)) {\r\n return;\r\n }\r\n const id = mirror.getId(target);\r\n if (target === doc && doc.defaultView) {\r\n const scrollLeftTop = getWindowScroll(doc.defaultView);\r\n scrollCb({\r\n id,\r\n x: scrollLeftTop.left,\r\n y: scrollLeftTop.top,\r\n });\r\n }\r\n else {\r\n scrollCb({\r\n id,\r\n x: target.scrollLeft,\r\n y: target.scrollTop,\r\n });\r\n }\r\n }), sampling.scroll || 100));\r\n return on('scroll', updatePosition, doc);\r\n}\r\nfunction initViewportResizeObserver({ viewportResizeCb }, { win }) {\r\n let lastH = -1;\r\n let lastW = -1;\r\n const updateDimension = callbackWrapper(throttle(callbackWrapper(() => {\r\n const height = getWindowHeight();\r\n const width = getWindowWidth();\r\n if (lastH !== height || lastW !== width) {\r\n viewportResizeCb({\r\n width: Number(width),\r\n height: Number(height),\r\n });\r\n lastH = height;\r\n lastW = width;\r\n }\r\n }), 200));\r\n return on('resize', updateDimension, win);\r\n}\r\nconst INPUT_TAGS = ['INPUT', 'TEXTAREA', 'SELECT'];\r\nconst lastInputValueMap = new WeakMap();\r\nfunction initInputObserver({ inputCb, doc, mirror, blockClass, blockSelector, ignoreClass, ignoreSelector, maskInputOptions, maskInputFn, sampling, userTriggeredOnInput, }) {\r\n function eventHandler(event) {\r\n let target = getEventTarget(event);\r\n const userTriggered = event.isTrusted;\r\n const tagName = target && target.tagName;\r\n if (target && tagName === 'OPTION') {\r\n target = target.parentElement;\r\n }\r\n if (!target ||\r\n !tagName ||\r\n INPUT_TAGS.indexOf(tagName) < 0 ||\r\n isBlocked(target, blockClass, blockSelector, true)) {\r\n return;\r\n }\r\n if (target.classList.contains(ignoreClass) ||\r\n (ignoreSelector && target.matches(ignoreSelector))) {\r\n return;\r\n }\r\n let text = target.value;\r\n let isChecked = false;\r\n const type = getInputType(target) || '';\r\n if (type === 'radio' || type === 'checkbox') {\r\n isChecked = target.checked;\r\n }\r\n else if (maskInputOptions[tagName.toLowerCase()] ||\r\n maskInputOptions[type]) {\r\n text = maskInputValue({\r\n element: target,\r\n maskInputOptions,\r\n tagName,\r\n type,\r\n value: text,\r\n maskInputFn,\r\n });\r\n }\r\n cbWithDedup(target, userTriggeredOnInput\r\n ? { text, isChecked, userTriggered }\r\n : { text, isChecked });\r\n const name = target.name;\r\n if (type === 'radio' && name && isChecked) {\r\n doc\r\n .querySelectorAll(`input[type=\"radio\"][name=\"${name}\"]`)\r\n .forEach((el) => {\r\n if (el !== target) {\r\n const text = el.value;\r\n cbWithDedup(el, userTriggeredOnInput\r\n ? { text, isChecked: !isChecked, userTriggered: false }\r\n : { text, isChecked: !isChecked });\r\n }\r\n });\r\n }\r\n }\r\n function cbWithDedup(target, v) {\r\n const lastInputValue = lastInputValueMap.get(target);\r\n if (!lastInputValue ||\r\n lastInputValue.text !== v.text ||\r\n lastInputValue.isChecked !== v.isChecked) {\r\n lastInputValueMap.set(target, v);\r\n const id = mirror.getId(target);\r\n callbackWrapper(inputCb)(Object.assign(Object.assign({}, v), { id }));\r\n }\r\n }\r\n const events = sampling.input === 'last' ? ['change'] : ['input', 'change'];\r\n const handlers = events.map((eventName) => on(eventName, callbackWrapper(eventHandler), doc));\r\n const currentWindow = doc.defaultView;\r\n if (!currentWindow) {\r\n return () => {\r\n handlers.forEach((h) => h());\r\n };\r\n }\r\n const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype, 'value');\r\n const hookProperties = [\r\n [currentWindow.HTMLInputElement.prototype, 'value'],\r\n [currentWindow.HTMLInputElement.prototype, 'checked'],\r\n [currentWindow.HTMLSelectElement.prototype, 'value'],\r\n [currentWindow.HTMLTextAreaElement.prototype, 'value'],\r\n [currentWindow.HTMLSelectElement.prototype, 'selectedIndex'],\r\n [currentWindow.HTMLOptionElement.prototype, 'selected'],\r\n ];\r\n if (propertyDescriptor && propertyDescriptor.set) {\r\n handlers.push(...hookProperties.map((p) => hookSetter(p[0], p[1], {\r\n set() {\r\n callbackWrapper(eventHandler)({\r\n target: this,\r\n isTrusted: false,\r\n });\r\n },\r\n }, false, currentWindow)));\r\n }\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction getNestedCSSRulePositions(rule) {\r\n const positions = [];\r\n function recurse(childRule, pos) {\r\n if ((hasNestedCSSRule('CSSGroupingRule') &&\r\n childRule.parentRule instanceof CSSGroupingRule) ||\r\n (hasNestedCSSRule('CSSMediaRule') &&\r\n childRule.parentRule instanceof CSSMediaRule) ||\r\n (hasNestedCSSRule('CSSSupportsRule') &&\r\n childRule.parentRule instanceof CSSSupportsRule) ||\r\n (hasNestedCSSRule('CSSConditionRule') &&\r\n childRule.parentRule instanceof CSSConditionRule)) {\r\n const rules = Array.from(childRule.parentRule.cssRules);\r\n const index = rules.indexOf(childRule);\r\n pos.unshift(index);\r\n }\r\n else if (childRule.parentStyleSheet) {\r\n const rules = Array.from(childRule.parentStyleSheet.cssRules);\r\n const index = rules.indexOf(childRule);\r\n pos.unshift(index);\r\n }\r\n return pos;\r\n }\r\n return recurse(rule, positions);\r\n}\r\nfunction getIdAndStyleId(sheet, mirror, styleMirror) {\r\n let id, styleId;\r\n if (!sheet)\r\n return {};\r\n if (sheet.ownerNode)\r\n id = mirror.getId(sheet.ownerNode);\r\n else\r\n styleId = styleMirror.getId(sheet);\r\n return {\r\n styleId,\r\n id,\r\n };\r\n}\r\nfunction initStyleSheetObserver({ styleSheetRuleCb, mirror, stylesheetManager }, { win }) {\r\n if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {\r\n return () => {\r\n };\r\n }\r\n const insertRule = win.CSSStyleSheet.prototype.insertRule;\r\n win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [rule, index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n adds: [{ rule, index }],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n const deleteRule = win.CSSStyleSheet.prototype.deleteRule;\r\n win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n removes: [{ index }],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n let replace;\r\n if (win.CSSStyleSheet.prototype.replace) {\r\n replace = win.CSSStyleSheet.prototype.replace;\r\n win.CSSStyleSheet.prototype.replace = new Proxy(replace, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [text] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n replace: text,\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n }\r\n let replaceSync;\r\n if (win.CSSStyleSheet.prototype.replaceSync) {\r\n replaceSync = win.CSSStyleSheet.prototype.replaceSync;\r\n win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [text] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n replaceSync: text,\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n }\r\n const supportedNestedCSSRuleTypes = {};\r\n if (canMonkeyPatchNestedCSSRule('CSSGroupingRule')) {\r\n supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;\r\n }\r\n else {\r\n if (canMonkeyPatchNestedCSSRule('CSSMediaRule')) {\r\n supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;\r\n }\r\n if (canMonkeyPatchNestedCSSRule('CSSConditionRule')) {\r\n supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;\r\n }\r\n if (canMonkeyPatchNestedCSSRule('CSSSupportsRule')) {\r\n supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;\r\n }\r\n }\r\n const unmodifiedFunctions = {};\r\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\r\n unmodifiedFunctions[typeKey] = {\r\n insertRule: type.prototype.insertRule,\r\n deleteRule: type.prototype.deleteRule,\r\n };\r\n type.prototype.insertRule = new Proxy(unmodifiedFunctions[typeKey].insertRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [rule, index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n adds: [\r\n {\r\n rule,\r\n index: [\r\n ...getNestedCSSRulePositions(thisArg),\r\n index || 0,\r\n ],\r\n },\r\n ],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n type.prototype.deleteRule = new Proxy(unmodifiedFunctions[typeKey].deleteRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n removes: [\r\n { index: [...getNestedCSSRulePositions(thisArg), index] },\r\n ],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n });\r\n return callbackWrapper(() => {\r\n win.CSSStyleSheet.prototype.insertRule = insertRule;\r\n win.CSSStyleSheet.prototype.deleteRule = deleteRule;\r\n replace && (win.CSSStyleSheet.prototype.replace = replace);\r\n replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);\r\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\r\n type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;\r\n type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;\r\n });\r\n });\r\n}\r\nfunction initAdoptedStyleSheetObserver({ mirror, stylesheetManager, }, host) {\r\n var _a, _b, _c;\r\n let hostId = null;\r\n if (host.nodeName === '#document')\r\n hostId = mirror.getId(host);\r\n else\r\n hostId = mirror.getId(host.host);\r\n const patchTarget = host.nodeName === '#document'\r\n ? (_a = host.defaultView) === null || _a === void 0 ? void 0 : _a.Document\r\n : (_c = (_b = host.ownerDocument) === null || _b === void 0 ? void 0 : _b.defaultView) === null || _c === void 0 ? void 0 : _c.ShadowRoot;\r\n const originalPropertyDescriptor = (patchTarget === null || patchTarget === void 0 ? void 0 : patchTarget.prototype)\r\n ? Object.getOwnPropertyDescriptor(patchTarget === null || patchTarget === void 0 ? void 0 : patchTarget.prototype, 'adoptedStyleSheets')\r\n : undefined;\r\n if (hostId === null ||\r\n hostId === -1 ||\r\n !patchTarget ||\r\n !originalPropertyDescriptor)\r\n return () => {\r\n };\r\n Object.defineProperty(host, 'adoptedStyleSheets', {\r\n configurable: originalPropertyDescriptor.configurable,\r\n enumerable: originalPropertyDescriptor.enumerable,\r\n get() {\r\n var _a;\r\n return (_a = originalPropertyDescriptor.get) === null || _a === void 0 ? void 0 : _a.call(this);\r\n },\r\n set(sheets) {\r\n var _a;\r\n const result = (_a = originalPropertyDescriptor.set) === null || _a === void 0 ? void 0 : _a.call(this, sheets);\r\n if (hostId !== null && hostId !== -1) {\r\n try {\r\n stylesheetManager.adoptStyleSheets(sheets, hostId);\r\n }\r\n catch (e) {\r\n }\r\n }\r\n return result;\r\n },\r\n });\r\n return callbackWrapper(() => {\r\n Object.defineProperty(host, 'adoptedStyleSheets', {\r\n configurable: originalPropertyDescriptor.configurable,\r\n enumerable: originalPropertyDescriptor.enumerable,\r\n get: originalPropertyDescriptor.get,\r\n set: originalPropertyDescriptor.set,\r\n });\r\n });\r\n}\r\nfunction initStyleDeclarationObserver({ styleDeclarationCb, mirror, ignoreCSSAttributes, stylesheetManager, }, { win }) {\r\n const setProperty = win.CSSStyleDeclaration.prototype.setProperty;\r\n win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n var _a;\r\n const [property, value, priority] = argumentsList;\r\n if (ignoreCSSAttributes.has(property)) {\r\n return setProperty.apply(thisArg, [property, value, priority]);\r\n }\r\n const { id, styleId } = getIdAndStyleId((_a = thisArg.parentRule) === null || _a === void 0 ? void 0 : _a.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleDeclarationCb({\r\n id,\r\n styleId,\r\n set: {\r\n property,\r\n value,\r\n priority,\r\n },\r\n index: getNestedCSSRulePositions(thisArg.parentRule),\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;\r\n win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n var _a;\r\n const [property] = argumentsList;\r\n if (ignoreCSSAttributes.has(property)) {\r\n return removeProperty.apply(thisArg, [property]);\r\n }\r\n const { id, styleId } = getIdAndStyleId((_a = thisArg.parentRule) === null || _a === void 0 ? void 0 : _a.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleDeclarationCb({\r\n id,\r\n styleId,\r\n remove: {\r\n property,\r\n },\r\n index: getNestedCSSRulePositions(thisArg.parentRule),\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n return callbackWrapper(() => {\r\n win.CSSStyleDeclaration.prototype.setProperty = setProperty;\r\n win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;\r\n });\r\n}\r\nfunction initMediaInteractionObserver({ mediaInteractionCb, blockClass, blockSelector, mirror, sampling, doc, }) {\r\n const handler = callbackWrapper((type) => throttle(callbackWrapper((event) => {\r\n const target = getEventTarget(event);\r\n if (!target ||\r\n isBlocked(target, blockClass, blockSelector, true)) {\r\n return;\r\n }\r\n const { currentTime, volume, muted, playbackRate, loop } = target;\r\n mediaInteractionCb({\r\n type,\r\n id: mirror.getId(target),\r\n currentTime,\r\n volume,\r\n muted,\r\n playbackRate,\r\n loop,\r\n });\r\n }), sampling.media || 500));\r\n const handlers = [\r\n on('play', handler(0), doc),\r\n on('pause', handler(1), doc),\r\n on('seeked', handler(2), doc),\r\n on('volumechange', handler(3), doc),\r\n on('ratechange', handler(4), doc),\r\n ];\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initFontObserver({ fontCb, doc }) {\r\n const win = doc.defaultView;\r\n if (!win) {\r\n return () => {\r\n };\r\n }\r\n const handlers = [];\r\n const fontMap = new WeakMap();\r\n const originalFontFace = win.FontFace;\r\n win.FontFace = function FontFace(family, source, descriptors) {\r\n const fontFace = new originalFontFace(family, source, descriptors);\r\n fontMap.set(fontFace, {\r\n family,\r\n buffer: typeof source !== 'string',\r\n descriptors,\r\n fontSource: typeof source === 'string'\r\n ? source\r\n : JSON.stringify(Array.from(new Uint8Array(source))),\r\n });\r\n return fontFace;\r\n };\r\n const restoreHandler = patch(doc.fonts, 'add', function (original) {\r\n return function (fontFace) {\r\n setTimeout(callbackWrapper(() => {\r\n const p = fontMap.get(fontFace);\r\n if (p) {\r\n fontCb(p);\r\n fontMap.delete(fontFace);\r\n }\r\n }), 0);\r\n return original.apply(this, [fontFace]);\r\n };\r\n });\r\n handlers.push(() => {\r\n win.FontFace = originalFontFace;\r\n });\r\n handlers.push(restoreHandler);\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initSelectionObserver(param) {\r\n const { doc, mirror, blockClass, blockSelector, selectionCb } = param;\r\n let collapsed = true;\r\n const updateSelection = callbackWrapper(() => {\r\n const selection = doc.getSelection();\r\n if (!selection || (collapsed && (selection === null || selection === void 0 ? void 0 : selection.isCollapsed)))\r\n return;\r\n collapsed = selection.isCollapsed || false;\r\n const ranges = [];\r\n const count = selection.rangeCount || 0;\r\n for (let i = 0; i < count; i++) {\r\n const range = selection.getRangeAt(i);\r\n const { startContainer, startOffset, endContainer, endOffset } = range;\r\n const blocked = isBlocked(startContainer, blockClass, blockSelector, true) ||\r\n isBlocked(endContainer, blockClass, blockSelector, true);\r\n if (blocked)\r\n continue;\r\n ranges.push({\r\n start: mirror.getId(startContainer),\r\n startOffset,\r\n end: mirror.getId(endContainer),\r\n endOffset,\r\n });\r\n }\r\n selectionCb({ ranges });\r\n });\r\n updateSelection();\r\n return on('selectionchange', updateSelection);\r\n}\r\nfunction initCustomElementObserver({ doc, customElementCb, }) {\r\n const win = doc.defaultView;\r\n if (!win || !win.customElements)\r\n return () => { };\r\n const restoreHandler = patch(win.customElements, 'define', function (original) {\r\n return function (name, constructor, options) {\r\n try {\r\n customElementCb({\r\n define: {\r\n name,\r\n },\r\n });\r\n }\r\n catch (e) {\r\n console.warn(`Custom element callback failed for ${name}`);\r\n }\r\n return original.apply(this, [name, constructor, options]);\r\n };\r\n });\r\n return restoreHandler;\r\n}\r\nfunction mergeHooks(o, hooks) {\r\n const { mutationCb, mousemoveCb, mouseInteractionCb, scrollCb, viewportResizeCb, inputCb, mediaInteractionCb, styleSheetRuleCb, styleDeclarationCb, canvasMutationCb, fontCb, selectionCb, customElementCb, } = o;\r\n o.mutationCb = (...p) => {\r\n if (hooks.mutation) {\r\n hooks.mutation(...p);\r\n }\r\n mutationCb(...p);\r\n };\r\n o.mousemoveCb = (...p) => {\r\n if (hooks.mousemove) {\r\n hooks.mousemove(...p);\r\n }\r\n mousemoveCb(...p);\r\n };\r\n o.mouseInteractionCb = (...p) => {\r\n if (hooks.mouseInteraction) {\r\n hooks.mouseInteraction(...p);\r\n }\r\n mouseInteractionCb(...p);\r\n };\r\n o.scrollCb = (...p) => {\r\n if (hooks.scroll) {\r\n hooks.scroll(...p);\r\n }\r\n scrollCb(...p);\r\n };\r\n o.viewportResizeCb = (...p) => {\r\n if (hooks.viewportResize) {\r\n hooks.viewportResize(...p);\r\n }\r\n viewportResizeCb(...p);\r\n };\r\n o.inputCb = (...p) => {\r\n if (hooks.input) {\r\n hooks.input(...p);\r\n }\r\n inputCb(...p);\r\n };\r\n o.mediaInteractionCb = (...p) => {\r\n if (hooks.mediaInteaction) {\r\n hooks.mediaInteaction(...p);\r\n }\r\n mediaInteractionCb(...p);\r\n };\r\n o.styleSheetRuleCb = (...p) => {\r\n if (hooks.styleSheetRule) {\r\n hooks.styleSheetRule(...p);\r\n }\r\n styleSheetRuleCb(...p);\r\n };\r\n o.styleDeclarationCb = (...p) => {\r\n if (hooks.styleDeclaration) {\r\n hooks.styleDeclaration(...p);\r\n }\r\n styleDeclarationCb(...p);\r\n };\r\n o.canvasMutationCb = (...p) => {\r\n if (hooks.canvasMutation) {\r\n hooks.canvasMutation(...p);\r\n }\r\n canvasMutationCb(...p);\r\n };\r\n o.fontCb = (...p) => {\r\n if (hooks.font) {\r\n hooks.font(...p);\r\n }\r\n fontCb(...p);\r\n };\r\n o.selectionCb = (...p) => {\r\n if (hooks.selection) {\r\n hooks.selection(...p);\r\n }\r\n selectionCb(...p);\r\n };\r\n o.customElementCb = (...c) => {\r\n if (hooks.customElement) {\r\n hooks.customElement(...c);\r\n }\r\n customElementCb(...c);\r\n };\r\n}\r\nfunction initObservers(o, hooks = {}) {\r\n const currentWindow = o.doc.defaultView;\r\n if (!currentWindow) {\r\n return () => {\r\n };\r\n }\r\n mergeHooks(o, hooks);\r\n let mutationObserver;\r\n if (o.recordDOM) {\r\n mutationObserver = initMutationObserver(o, o.doc);\r\n }\r\n const mousemoveHandler = initMoveObserver(o);\r\n const mouseInteractionHandler = initMouseInteractionObserver(o);\r\n const scrollHandler = initScrollObserver(o);\r\n const viewportResizeHandler = initViewportResizeObserver(o, {\r\n win: currentWindow,\r\n });\r\n const inputHandler = initInputObserver(o);\r\n const mediaInteractionHandler = initMediaInteractionObserver(o);\r\n let styleSheetObserver = () => { };\r\n let adoptedStyleSheetObserver = () => { };\r\n let styleDeclarationObserver = () => { };\r\n let fontObserver = () => { };\r\n if (o.recordDOM) {\r\n styleSheetObserver = initStyleSheetObserver(o, { win: currentWindow });\r\n adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o, o.doc);\r\n styleDeclarationObserver = initStyleDeclarationObserver(o, {\r\n win: currentWindow,\r\n });\r\n if (o.collectFonts) {\r\n fontObserver = initFontObserver(o);\r\n }\r\n }\r\n const selectionObserver = initSelectionObserver(o);\r\n const customElementObserver = initCustomElementObserver(o);\r\n const pluginHandlers = [];\r\n for (const plugin of o.plugins) {\r\n pluginHandlers.push(plugin.observer(plugin.callback, currentWindow, plugin.options));\r\n }\r\n return callbackWrapper(() => {\r\n mutationBuffers.forEach((b) => b.reset());\r\n mutationObserver === null || mutationObserver === void 0 ? void 0 : mutationObserver.disconnect();\r\n mousemoveHandler();\r\n mouseInteractionHandler();\r\n scrollHandler();\r\n viewportResizeHandler();\r\n inputHandler();\r\n mediaInteractionHandler();\r\n styleSheetObserver();\r\n adoptedStyleSheetObserver();\r\n styleDeclarationObserver();\r\n fontObserver();\r\n selectionObserver();\r\n customElementObserver();\r\n pluginHandlers.forEach((h) => h());\r\n });\r\n}\r\nfunction hasNestedCSSRule(prop) {\r\n return typeof window[prop] !== 'undefined';\r\n}\r\nfunction canMonkeyPatchNestedCSSRule(prop) {\r\n return Boolean(typeof window[prop] !== 'undefined' &&\r\n window[prop].prototype &&\r\n 'insertRule' in window[prop].prototype &&\r\n 'deleteRule' in window[prop].prototype);\r\n}\n\nclass CrossOriginIframeMirror {\r\n constructor(generateIdFn) {\r\n this.generateIdFn = generateIdFn;\r\n this.iframeIdToRemoteIdMap = new WeakMap();\r\n this.iframeRemoteIdToIdMap = new WeakMap();\r\n }\r\n getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {\r\n const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);\r\n const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);\r\n let id = idToRemoteIdMap.get(remoteId);\r\n if (!id) {\r\n id = this.generateIdFn();\r\n idToRemoteIdMap.set(remoteId, id);\r\n remoteIdToIdMap.set(id, remoteId);\r\n }\r\n return id;\r\n }\r\n getIds(iframe, remoteId) {\r\n const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);\r\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\r\n return remoteId.map((id) => this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap));\r\n }\r\n getRemoteId(iframe, id, map) {\r\n const remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);\r\n if (typeof id !== 'number')\r\n return id;\r\n const remoteId = remoteIdToIdMap.get(id);\r\n if (!remoteId)\r\n return -1;\r\n return remoteId;\r\n }\r\n getRemoteIds(iframe, ids) {\r\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\r\n return ids.map((id) => this.getRemoteId(iframe, id, remoteIdToIdMap));\r\n }\r\n reset(iframe) {\r\n if (!iframe) {\r\n this.iframeIdToRemoteIdMap = new WeakMap();\r\n this.iframeRemoteIdToIdMap = new WeakMap();\r\n return;\r\n }\r\n this.iframeIdToRemoteIdMap.delete(iframe);\r\n this.iframeRemoteIdToIdMap.delete(iframe);\r\n }\r\n getIdToRemoteIdMap(iframe) {\r\n let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);\r\n if (!idToRemoteIdMap) {\r\n idToRemoteIdMap = new Map();\r\n this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);\r\n }\r\n return idToRemoteIdMap;\r\n }\r\n getRemoteIdToIdMap(iframe) {\r\n let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);\r\n if (!remoteIdToIdMap) {\r\n remoteIdToIdMap = new Map();\r\n this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);\r\n }\r\n return remoteIdToIdMap;\r\n }\r\n}\n\nclass IframeManager {\r\n constructor(options) {\r\n this.iframes = new WeakMap();\r\n this.crossOriginIframeMap = new WeakMap();\r\n this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);\r\n this.crossOriginIframeRootIdMap = new WeakMap();\r\n this.mutationCb = options.mutationCb;\r\n this.wrappedEmit = options.wrappedEmit;\r\n this.stylesheetManager = options.stylesheetManager;\r\n this.recordCrossOriginIframes = options.recordCrossOriginIframes;\r\n this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror));\r\n this.mirror = options.mirror;\r\n if (this.recordCrossOriginIframes) {\r\n window.addEventListener('message', this.handleMessage.bind(this));\r\n }\r\n }\r\n addIframe(iframeEl) {\r\n this.iframes.set(iframeEl, true);\r\n if (iframeEl.contentWindow)\r\n this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);\r\n }\r\n addLoadListener(cb) {\r\n this.loadListener = cb;\r\n }\r\n attachIframe(iframeEl, childSn) {\r\n var _a;\r\n this.mutationCb({\r\n adds: [\r\n {\r\n parentId: this.mirror.getId(iframeEl),\r\n nextId: null,\r\n node: childSn,\r\n },\r\n ],\r\n removes: [],\r\n texts: [],\r\n attributes: [],\r\n isAttachIframe: true,\r\n });\r\n (_a = this.loadListener) === null || _a === void 0 ? void 0 : _a.call(this, iframeEl);\r\n if (iframeEl.contentDocument &&\r\n iframeEl.contentDocument.adoptedStyleSheets &&\r\n iframeEl.contentDocument.adoptedStyleSheets.length > 0)\r\n this.stylesheetManager.adoptStyleSheets(iframeEl.contentDocument.adoptedStyleSheets, this.mirror.getId(iframeEl.contentDocument));\r\n }\r\n handleMessage(message) {\r\n const crossOriginMessageEvent = message;\r\n if (crossOriginMessageEvent.data.type !== 'rrweb' ||\r\n crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin)\r\n return;\r\n const iframeSourceWindow = message.source;\r\n if (!iframeSourceWindow)\r\n return;\r\n const iframeEl = this.crossOriginIframeMap.get(message.source);\r\n if (!iframeEl)\r\n return;\r\n const transformedEvent = this.transformCrossOriginEvent(iframeEl, crossOriginMessageEvent.data.event);\r\n if (transformedEvent)\r\n this.wrappedEmit(transformedEvent, crossOriginMessageEvent.data.isCheckout);\r\n }\r\n transformCrossOriginEvent(iframeEl, e) {\r\n var _a;\r\n switch (e.type) {\r\n case EventType$1.FullSnapshot: {\r\n this.crossOriginIframeMirror.reset(iframeEl);\r\n this.crossOriginIframeStyleMirror.reset(iframeEl);\r\n this.replaceIdOnNode(e.data.node, iframeEl);\r\n const rootId = e.data.node.id;\r\n this.crossOriginIframeRootIdMap.set(iframeEl, rootId);\r\n this.patchRootIdOnNode(e.data.node, rootId);\r\n return {\r\n timestamp: e.timestamp,\r\n type: EventType$1.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource$1.Mutation,\r\n adds: [\r\n {\r\n parentId: this.mirror.getId(iframeEl),\r\n nextId: null,\r\n node: e.data.node,\r\n },\r\n ],\r\n removes: [],\r\n texts: [],\r\n attributes: [],\r\n isAttachIframe: true,\r\n },\r\n };\r\n }\r\n case EventType$1.Meta:\r\n case EventType$1.Load:\r\n case EventType$1.DomContentLoaded: {\r\n return false;\r\n }\r\n case EventType$1.Plugin: {\r\n return e;\r\n }\r\n case EventType$1.Custom: {\r\n this.replaceIds(e.data.payload, iframeEl, ['id', 'parentId', 'previousId', 'nextId']);\r\n return e;\r\n }\r\n case EventType$1.IncrementalSnapshot: {\r\n switch (e.data.source) {\r\n case IncrementalSource$1.Mutation: {\r\n e.data.adds.forEach((n) => {\r\n this.replaceIds(n, iframeEl, [\r\n 'parentId',\r\n 'nextId',\r\n 'previousId',\r\n ]);\r\n this.replaceIdOnNode(n.node, iframeEl);\r\n const rootId = this.crossOriginIframeRootIdMap.get(iframeEl);\r\n rootId && this.patchRootIdOnNode(n.node, rootId);\r\n });\r\n e.data.removes.forEach((n) => {\r\n this.replaceIds(n, iframeEl, ['parentId', 'id']);\r\n });\r\n e.data.attributes.forEach((n) => {\r\n this.replaceIds(n, iframeEl, ['id']);\r\n });\r\n e.data.texts.forEach((n) => {\r\n this.replaceIds(n, iframeEl, ['id']);\r\n });\r\n return e;\r\n }\r\n case IncrementalSource$1.Drag:\r\n case IncrementalSource$1.TouchMove:\r\n case IncrementalSource$1.MouseMove: {\r\n e.data.positions.forEach((p) => {\r\n this.replaceIds(p, iframeEl, ['id']);\r\n });\r\n return e;\r\n }\r\n case IncrementalSource$1.ViewportResize: {\r\n return false;\r\n }\r\n case IncrementalSource$1.MediaInteraction:\r\n case IncrementalSource$1.MouseInteraction:\r\n case IncrementalSource$1.Scroll:\r\n case IncrementalSource$1.CanvasMutation:\r\n case IncrementalSource$1.Input: {\r\n this.replaceIds(e.data, iframeEl, ['id']);\r\n return e;\r\n }\r\n case IncrementalSource$1.StyleSheetRule:\r\n case IncrementalSource$1.StyleDeclaration: {\r\n this.replaceIds(e.data, iframeEl, ['id']);\r\n this.replaceStyleIds(e.data, iframeEl, ['styleId']);\r\n return e;\r\n }\r\n case IncrementalSource$1.Font: {\r\n return e;\r\n }\r\n case IncrementalSource$1.Selection: {\r\n e.data.ranges.forEach((range) => {\r\n this.replaceIds(range, iframeEl, ['start', 'end']);\r\n });\r\n return e;\r\n }\r\n case IncrementalSource$1.AdoptedStyleSheet: {\r\n this.replaceIds(e.data, iframeEl, ['id']);\r\n this.replaceStyleIds(e.data, iframeEl, ['styleIds']);\r\n (_a = e.data.styles) === null || _a === void 0 ? void 0 : _a.forEach((style) => {\r\n this.replaceStyleIds(style, iframeEl, ['styleId']);\r\n });\r\n return e;\r\n }\r\n }\r\n }\r\n }\r\n return false;\r\n }\r\n replace(iframeMirror, obj, iframeEl, keys) {\r\n for (const key of keys) {\r\n if (!Array.isArray(obj[key]) && typeof obj[key] !== 'number')\r\n continue;\r\n if (Array.isArray(obj[key])) {\r\n obj[key] = iframeMirror.getIds(iframeEl, obj[key]);\r\n }\r\n else {\r\n obj[key] = iframeMirror.getId(iframeEl, obj[key]);\r\n }\r\n }\r\n return obj;\r\n }\r\n replaceIds(obj, iframeEl, keys) {\r\n return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);\r\n }\r\n replaceStyleIds(obj, iframeEl, keys) {\r\n return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);\r\n }\r\n replaceIdOnNode(node, iframeEl) {\r\n this.replaceIds(node, iframeEl, ['id', 'rootId']);\r\n if ('childNodes' in node) {\r\n node.childNodes.forEach((child) => {\r\n this.replaceIdOnNode(child, iframeEl);\r\n });\r\n }\r\n }\r\n patchRootIdOnNode(node, rootId) {\r\n if (node.type !== NodeType.Document && !node.rootId)\r\n node.rootId = rootId;\r\n if ('childNodes' in node) {\r\n node.childNodes.forEach((child) => {\r\n this.patchRootIdOnNode(child, rootId);\r\n });\r\n }\r\n }\r\n}\n\nclass ShadowDomManager {\r\n constructor(options) {\r\n this.shadowDoms = new WeakSet();\r\n this.restoreHandlers = [];\r\n this.mutationCb = options.mutationCb;\r\n this.scrollCb = options.scrollCb;\r\n this.bypassOptions = options.bypassOptions;\r\n this.mirror = options.mirror;\r\n this.init();\r\n }\r\n init() {\r\n this.reset();\r\n this.patchAttachShadow(Element, document);\r\n }\r\n addShadowRoot(shadowRoot, doc) {\r\n if (!isNativeShadowDom(shadowRoot))\r\n return;\r\n if (this.shadowDoms.has(shadowRoot))\r\n return;\r\n this.shadowDoms.add(shadowRoot);\r\n const observer = initMutationObserver(Object.assign(Object.assign({}, this.bypassOptions), { doc, mutationCb: this.mutationCb, mirror: this.mirror, shadowDomManager: this }), shadowRoot);\r\n this.restoreHandlers.push(() => observer.disconnect());\r\n this.restoreHandlers.push(initScrollObserver(Object.assign(Object.assign({}, this.bypassOptions), { scrollCb: this.scrollCb, doc: shadowRoot, mirror: this.mirror })));\r\n setTimeout(() => {\r\n if (shadowRoot.adoptedStyleSheets &&\r\n shadowRoot.adoptedStyleSheets.length > 0)\r\n this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot.adoptedStyleSheets, this.mirror.getId(shadowRoot.host));\r\n this.restoreHandlers.push(initAdoptedStyleSheetObserver({\r\n mirror: this.mirror,\r\n stylesheetManager: this.bypassOptions.stylesheetManager,\r\n }, shadowRoot));\r\n }, 0);\r\n }\r\n observeAttachShadow(iframeElement) {\r\n if (!iframeElement.contentWindow || !iframeElement.contentDocument)\r\n return;\r\n this.patchAttachShadow(iframeElement.contentWindow.Element, iframeElement.contentDocument);\r\n }\r\n patchAttachShadow(element, doc) {\r\n const manager = this;\r\n this.restoreHandlers.push(patch(element.prototype, 'attachShadow', function (original) {\r\n return function (option) {\r\n const shadowRoot = original.call(this, option);\r\n if (this.shadowRoot && inDom(this))\r\n manager.addShadowRoot(this.shadowRoot, doc);\r\n return shadowRoot;\r\n };\r\n }));\r\n }\r\n reset() {\r\n this.restoreHandlers.forEach((handler) => {\r\n try {\r\n handler();\r\n }\r\n catch (e) {\r\n }\r\n });\r\n this.restoreHandlers = [];\r\n this.shadowDoms = new WeakSet();\r\n }\r\n}\n\n/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nfunction __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nfunction __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\n\n/*\n * base64-arraybuffer 1.0.1 \n * Copyright (c) 2021 Niklas von Hertzen \n * Released under MIT License\n */\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\nvar lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nvar encode = function (arraybuffer) {\n var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n }\n else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n return base64;\n};\n\nconst canvasVarMap = new Map();\r\nfunction variableListFor(ctx, ctor) {\r\n let contextMap = canvasVarMap.get(ctx);\r\n if (!contextMap) {\r\n contextMap = new Map();\r\n canvasVarMap.set(ctx, contextMap);\r\n }\r\n if (!contextMap.has(ctor)) {\r\n contextMap.set(ctor, []);\r\n }\r\n return contextMap.get(ctor);\r\n}\r\nconst saveWebGLVar = (value, win, ctx) => {\r\n if (!value ||\r\n !(isInstanceOfWebGLObject(value, win) || typeof value === 'object'))\r\n return;\r\n const name = value.constructor.name;\r\n const list = variableListFor(ctx, name);\r\n let index = list.indexOf(value);\r\n if (index === -1) {\r\n index = list.length;\r\n list.push(value);\r\n }\r\n return index;\r\n};\r\nfunction serializeArg(value, win, ctx) {\r\n if (value instanceof Array) {\r\n return value.map((arg) => serializeArg(arg, win, ctx));\r\n }\r\n else if (value === null) {\r\n return value;\r\n }\r\n else if (value instanceof Float32Array ||\r\n value instanceof Float64Array ||\r\n value instanceof Int32Array ||\r\n value instanceof Uint32Array ||\r\n value instanceof Uint8Array ||\r\n value instanceof Uint16Array ||\r\n value instanceof Int16Array ||\r\n value instanceof Int8Array ||\r\n value instanceof Uint8ClampedArray) {\r\n const name = value.constructor.name;\r\n return {\r\n rr_type: name,\r\n args: [Object.values(value)],\r\n };\r\n }\r\n else if (value instanceof ArrayBuffer) {\r\n const name = value.constructor.name;\r\n const base64 = encode(value);\r\n return {\r\n rr_type: name,\r\n base64,\r\n };\r\n }\r\n else if (value instanceof DataView) {\r\n const name = value.constructor.name;\r\n return {\r\n rr_type: name,\r\n args: [\r\n serializeArg(value.buffer, win, ctx),\r\n value.byteOffset,\r\n value.byteLength,\r\n ],\r\n };\r\n }\r\n else if (value instanceof HTMLImageElement) {\r\n const name = value.constructor.name;\r\n const { src } = value;\r\n return {\r\n rr_type: name,\r\n src,\r\n };\r\n }\r\n else if (value instanceof HTMLCanvasElement) {\r\n const name = 'HTMLImageElement';\r\n const src = value.toDataURL();\r\n return {\r\n rr_type: name,\r\n src,\r\n };\r\n }\r\n else if (value instanceof ImageData) {\r\n const name = value.constructor.name;\r\n return {\r\n rr_type: name,\r\n args: [serializeArg(value.data, win, ctx), value.width, value.height],\r\n };\r\n }\r\n else if (isInstanceOfWebGLObject(value, win) || typeof value === 'object') {\r\n const name = value.constructor.name;\r\n const index = saveWebGLVar(value, win, ctx);\r\n return {\r\n rr_type: name,\r\n index: index,\r\n };\r\n }\r\n return value;\r\n}\r\nconst serializeArgs = (args, win, ctx) => {\r\n return args.map((arg) => serializeArg(arg, win, ctx));\r\n};\r\nconst isInstanceOfWebGLObject = (value, win) => {\r\n const webGLConstructorNames = [\r\n 'WebGLActiveInfo',\r\n 'WebGLBuffer',\r\n 'WebGLFramebuffer',\r\n 'WebGLProgram',\r\n 'WebGLRenderbuffer',\r\n 'WebGLShader',\r\n 'WebGLShaderPrecisionFormat',\r\n 'WebGLTexture',\r\n 'WebGLUniformLocation',\r\n 'WebGLVertexArrayObject',\r\n 'WebGLVertexArrayObjectOES',\r\n ];\r\n const supportedWebGLConstructorNames = webGLConstructorNames.filter((name) => typeof win[name] === 'function');\r\n return Boolean(supportedWebGLConstructorNames.find((name) => value instanceof win[name]));\r\n};\n\nfunction initCanvas2DMutationObserver(cb, win, blockClass, blockSelector) {\r\n const handlers = [];\r\n const props2D = Object.getOwnPropertyNames(win.CanvasRenderingContext2D.prototype);\r\n for (const prop of props2D) {\r\n try {\r\n if (typeof win.CanvasRenderingContext2D.prototype[prop] !== 'function') {\r\n continue;\r\n }\r\n const restoreHandler = patch(win.CanvasRenderingContext2D.prototype, prop, function (original) {\r\n return function (...args) {\r\n if (!isBlocked(this.canvas, blockClass, blockSelector, true)) {\r\n setTimeout(() => {\r\n const recordArgs = serializeArgs(args, win, this);\r\n cb(this.canvas, {\r\n type: CanvasContext['2D'],\r\n property: prop,\r\n args: recordArgs,\r\n });\r\n }, 0);\r\n }\r\n return original.apply(this, args);\r\n };\r\n });\r\n handlers.push(restoreHandler);\r\n }\r\n catch (_a) {\r\n const hookHandler = hookSetter(win.CanvasRenderingContext2D.prototype, prop, {\r\n set(v) {\r\n cb(this.canvas, {\r\n type: CanvasContext['2D'],\r\n property: prop,\r\n args: [v],\r\n setter: true,\r\n });\r\n },\r\n });\r\n handlers.push(hookHandler);\r\n }\r\n }\r\n return () => {\r\n handlers.forEach((h) => h());\r\n };\r\n}\n\nfunction getNormalizedContextName(contextType) {\r\n return contextType === 'experimental-webgl' ? 'webgl' : contextType;\r\n}\r\nfunction initCanvasContextObserver(win, blockClass, blockSelector, setPreserveDrawingBufferToTrue) {\r\n const handlers = [];\r\n try {\r\n const restoreHandler = patch(win.HTMLCanvasElement.prototype, 'getContext', function (original) {\r\n return function (contextType, ...args) {\r\n if (!isBlocked(this, blockClass, blockSelector, true)) {\r\n const ctxName = getNormalizedContextName(contextType);\r\n if (!('__context' in this))\r\n this.__context = ctxName;\r\n if (setPreserveDrawingBufferToTrue &&\r\n ['webgl', 'webgl2'].includes(ctxName)) {\r\n if (args[0] && typeof args[0] === 'object') {\r\n const contextAttributes = args[0];\r\n if (!contextAttributes.preserveDrawingBuffer) {\r\n contextAttributes.preserveDrawingBuffer = true;\r\n }\r\n }\r\n else {\r\n args.splice(0, 1, {\r\n preserveDrawingBuffer: true,\r\n });\r\n }\r\n }\r\n }\r\n return original.apply(this, [contextType, ...args]);\r\n };\r\n });\r\n handlers.push(restoreHandler);\r\n }\r\n catch (_a) {\r\n console.error('failed to patch HTMLCanvasElement.prototype.getContext');\r\n }\r\n return () => {\r\n handlers.forEach((h) => h());\r\n };\r\n}\n\nfunction patchGLPrototype(prototype, type, cb, blockClass, blockSelector, mirror, win) {\r\n const handlers = [];\r\n const props = Object.getOwnPropertyNames(prototype);\r\n for (const prop of props) {\r\n if ([\r\n 'isContextLost',\r\n 'canvas',\r\n 'drawingBufferWidth',\r\n 'drawingBufferHeight',\r\n ].includes(prop)) {\r\n continue;\r\n }\r\n try {\r\n if (typeof prototype[prop] !== 'function') {\r\n continue;\r\n }\r\n const restoreHandler = patch(prototype, prop, function (original) {\r\n return function (...args) {\r\n const result = original.apply(this, args);\r\n saveWebGLVar(result, win, this);\r\n if ('tagName' in this.canvas &&\r\n !isBlocked(this.canvas, blockClass, blockSelector, true)) {\r\n const recordArgs = serializeArgs(args, win, this);\r\n const mutation = {\r\n type,\r\n property: prop,\r\n args: recordArgs,\r\n };\r\n cb(this.canvas, mutation);\r\n }\r\n return result;\r\n };\r\n });\r\n handlers.push(restoreHandler);\r\n }\r\n catch (_a) {\r\n const hookHandler = hookSetter(prototype, prop, {\r\n set(v) {\r\n cb(this.canvas, {\r\n type,\r\n property: prop,\r\n args: [v],\r\n setter: true,\r\n });\r\n },\r\n });\r\n handlers.push(hookHandler);\r\n }\r\n }\r\n return handlers;\r\n}\r\nfunction initCanvasWebGLMutationObserver(cb, win, blockClass, blockSelector, mirror) {\r\n const handlers = [];\r\n handlers.push(...patchGLPrototype(win.WebGLRenderingContext.prototype, CanvasContext.WebGL, cb, blockClass, blockSelector, mirror, win));\r\n if (typeof win.WebGL2RenderingContext !== 'undefined') {\r\n handlers.push(...patchGLPrototype(win.WebGL2RenderingContext.prototype, CanvasContext.WebGL2, cb, blockClass, blockSelector, mirror, win));\r\n }\r\n return () => {\r\n handlers.forEach((h) => h());\r\n };\r\n}\n\nfunction funcToSource(fn, sourcemapArg) {\n var sourcemap = sourcemapArg === undefined ? null : sourcemapArg;\n var source = fn.toString();\n var lines = source.split('\\n');\n lines.pop();\n lines.shift();\n var blankPrefixLength = lines[0].search(/\\S/);\n var regex = /(['\"])__worker_loader_strict__(['\"])/g;\n for (var i = 0, n = lines.length; i < n; ++i) {\n lines[i] = lines[i].substring(blankPrefixLength).replace(regex, '$1use strict$2') + '\\n';\n }\n if (sourcemap) {\n lines.push('\\/\\/# sourceMappingURL=' + sourcemap + '\\n');\n }\n return lines;\n}\n\nfunction createURL(fn, sourcemapArg) {\n var lines = funcToSource(fn, sourcemapArg);\n var blob = new Blob(lines, { type: 'application/javascript' });\n return URL.createObjectURL(blob);\n}\n\nfunction createInlineWorkerFactory(fn, sourcemapArg) {\n var url;\n return function WorkerFactory(options) {\n url = url || createURL(fn, sourcemapArg);\n return new Worker(url, options);\n };\n}\n\nvar WorkerFactory = createInlineWorkerFactory(/* rollup-plugin-web-worker-loader */function () {\n(function () {\n '__worker_loader_strict__';\n\n /*! *****************************************************************************\r\n Copyright (c) Microsoft Corporation.\r\n\r\n Permission to use, copy, modify, and/or distribute this software for any\r\n purpose with or without fee is hereby granted.\r\n\r\n THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\n REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\n AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\n INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\n LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\n OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\n PERFORMANCE OF THIS SOFTWARE.\r\n ***************************************************************************** */\r\n\r\n function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n }\n\n /*\n * base64-arraybuffer 1.0.1 \n * Copyright (c) 2021 Niklas von Hertzen \n * Released under MIT License\n */\n var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n // Use a lookup table to find the index.\n var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\n for (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n }\n var encode = function (arraybuffer) {\n var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n }\n else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n return base64;\n };\n\n const lastBlobMap = new Map();\r\n const transparentBlobMap = new Map();\r\n function getTransparentBlobFor(width, height, dataURLOptions) {\r\n return __awaiter(this, void 0, void 0, function* () {\r\n const id = `${width}-${height}`;\r\n if ('OffscreenCanvas' in globalThis) {\r\n if (transparentBlobMap.has(id))\r\n return transparentBlobMap.get(id);\r\n const offscreen = new OffscreenCanvas(width, height);\r\n offscreen.getContext('2d');\r\n const blob = yield offscreen.convertToBlob(dataURLOptions);\r\n const arrayBuffer = yield blob.arrayBuffer();\r\n const base64 = encode(arrayBuffer);\r\n transparentBlobMap.set(id, base64);\r\n return base64;\r\n }\r\n else {\r\n return '';\r\n }\r\n });\r\n }\r\n const worker = self;\r\n worker.onmessage = function (e) {\r\n return __awaiter(this, void 0, void 0, function* () {\r\n if ('OffscreenCanvas' in globalThis) {\r\n const { id, bitmap, width, height, dataURLOptions } = e.data;\r\n const transparentBase64 = getTransparentBlobFor(width, height, dataURLOptions);\r\n const offscreen = new OffscreenCanvas(width, height);\r\n const ctx = offscreen.getContext('2d');\r\n ctx.drawImage(bitmap, 0, 0);\r\n bitmap.close();\r\n const blob = yield offscreen.convertToBlob(dataURLOptions);\r\n const type = blob.type;\r\n const arrayBuffer = yield blob.arrayBuffer();\r\n const base64 = encode(arrayBuffer);\r\n if (!lastBlobMap.has(id) && (yield transparentBase64) === base64) {\r\n lastBlobMap.set(id, base64);\r\n return worker.postMessage({ id });\r\n }\r\n if (lastBlobMap.get(id) === base64)\r\n return worker.postMessage({ id });\r\n worker.postMessage({\r\n id,\r\n type,\r\n base64,\r\n width,\r\n height,\r\n });\r\n lastBlobMap.set(id, base64);\r\n }\r\n else {\r\n return worker.postMessage({ id: e.data.id });\r\n }\r\n });\r\n };\n\n})();\n}, null);\n\nclass CanvasManager {\r\n reset() {\r\n this.pendingCanvasMutations.clear();\r\n this.resetObservers && this.resetObservers();\r\n }\r\n freeze() {\r\n this.frozen = true;\r\n }\r\n unfreeze() {\r\n this.frozen = false;\r\n }\r\n lock() {\r\n this.locked = true;\r\n }\r\n unlock() {\r\n this.locked = false;\r\n }\r\n constructor(options) {\r\n this.pendingCanvasMutations = new Map();\r\n this.rafStamps = { latestId: 0, invokeId: null };\r\n this.frozen = false;\r\n this.locked = false;\r\n this.processMutation = (target, mutation) => {\r\n const newFrame = this.rafStamps.invokeId &&\r\n this.rafStamps.latestId !== this.rafStamps.invokeId;\r\n if (newFrame || !this.rafStamps.invokeId)\r\n this.rafStamps.invokeId = this.rafStamps.latestId;\r\n if (!this.pendingCanvasMutations.has(target)) {\r\n this.pendingCanvasMutations.set(target, []);\r\n }\r\n this.pendingCanvasMutations.get(target).push(mutation);\r\n };\r\n const { sampling = 'all', win, blockClass, blockSelector, recordCanvas, dataURLOptions, } = options;\r\n this.mutationCb = options.mutationCb;\r\n this.mirror = options.mirror;\r\n if (recordCanvas && sampling === 'all')\r\n this.initCanvasMutationObserver(win, blockClass, blockSelector);\r\n if (recordCanvas && typeof sampling === 'number')\r\n this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, {\r\n dataURLOptions,\r\n });\r\n }\r\n initCanvasFPSObserver(fps, win, blockClass, blockSelector, options) {\r\n const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, true);\r\n const snapshotInProgressMap = new Map();\r\n const worker = new WorkerFactory();\r\n worker.onmessage = (e) => {\r\n const { id } = e.data;\r\n snapshotInProgressMap.set(id, false);\r\n if (!('base64' in e.data))\r\n return;\r\n const { base64, type, width, height } = e.data;\r\n this.mutationCb({\r\n id,\r\n type: CanvasContext['2D'],\r\n commands: [\r\n {\r\n property: 'clearRect',\r\n args: [0, 0, width, height],\r\n },\r\n {\r\n property: 'drawImage',\r\n args: [\r\n {\r\n rr_type: 'ImageBitmap',\r\n args: [\r\n {\r\n rr_type: 'Blob',\r\n data: [{ rr_type: 'ArrayBuffer', base64 }],\r\n type,\r\n },\r\n ],\r\n },\r\n 0,\r\n 0,\r\n ],\r\n },\r\n ],\r\n });\r\n };\r\n const timeBetweenSnapshots = 1000 / fps;\r\n let lastSnapshotTime = 0;\r\n let rafId;\r\n const getCanvas = () => {\r\n const matchedCanvas = [];\r\n win.document.querySelectorAll('canvas').forEach((canvas) => {\r\n if (!isBlocked(canvas, blockClass, blockSelector, true)) {\r\n matchedCanvas.push(canvas);\r\n }\r\n });\r\n return matchedCanvas;\r\n };\r\n const takeCanvasSnapshots = (timestamp) => {\r\n if (lastSnapshotTime &&\r\n timestamp - lastSnapshotTime < timeBetweenSnapshots) {\r\n rafId = requestAnimationFrame(takeCanvasSnapshots);\r\n return;\r\n }\r\n lastSnapshotTime = timestamp;\r\n getCanvas()\r\n .forEach((canvas) => __awaiter(this, void 0, void 0, function* () {\r\n var _a;\r\n const id = this.mirror.getId(canvas);\r\n if (snapshotInProgressMap.get(id))\r\n return;\r\n if (canvas.width === 0 || canvas.height === 0)\r\n return;\r\n snapshotInProgressMap.set(id, true);\r\n if (['webgl', 'webgl2'].includes(canvas.__context)) {\r\n const context = canvas.getContext(canvas.__context);\r\n if (((_a = context === null || context === void 0 ? void 0 : context.getContextAttributes()) === null || _a === void 0 ? void 0 : _a.preserveDrawingBuffer) === false) {\r\n context.clear(context.COLOR_BUFFER_BIT);\r\n }\r\n }\r\n const bitmap = yield createImageBitmap(canvas);\r\n worker.postMessage({\r\n id,\r\n bitmap,\r\n width: canvas.width,\r\n height: canvas.height,\r\n dataURLOptions: options.dataURLOptions,\r\n }, [bitmap]);\r\n }));\r\n rafId = requestAnimationFrame(takeCanvasSnapshots);\r\n };\r\n rafId = requestAnimationFrame(takeCanvasSnapshots);\r\n this.resetObservers = () => {\r\n canvasContextReset();\r\n cancelAnimationFrame(rafId);\r\n };\r\n }\r\n initCanvasMutationObserver(win, blockClass, blockSelector) {\r\n this.startRAFTimestamping();\r\n this.startPendingCanvasMutationFlusher();\r\n const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, false);\r\n const canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector);\r\n const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, this.mirror);\r\n this.resetObservers = () => {\r\n canvasContextReset();\r\n canvas2DReset();\r\n canvasWebGL1and2Reset();\r\n };\r\n }\r\n startPendingCanvasMutationFlusher() {\r\n requestAnimationFrame(() => this.flushPendingCanvasMutations());\r\n }\r\n startRAFTimestamping() {\r\n const setLatestRAFTimestamp = (timestamp) => {\r\n this.rafStamps.latestId = timestamp;\r\n requestAnimationFrame(setLatestRAFTimestamp);\r\n };\r\n requestAnimationFrame(setLatestRAFTimestamp);\r\n }\r\n flushPendingCanvasMutations() {\r\n this.pendingCanvasMutations.forEach((values, canvas) => {\r\n const id = this.mirror.getId(canvas);\r\n this.flushPendingCanvasMutationFor(canvas, id);\r\n });\r\n requestAnimationFrame(() => this.flushPendingCanvasMutations());\r\n }\r\n flushPendingCanvasMutationFor(canvas, id) {\r\n if (this.frozen || this.locked) {\r\n return;\r\n }\r\n const valuesWithType = this.pendingCanvasMutations.get(canvas);\r\n if (!valuesWithType || id === -1)\r\n return;\r\n const values = valuesWithType.map((value) => {\r\n const rest = __rest(value, [\"type\"]);\r\n return rest;\r\n });\r\n const { type } = valuesWithType[0];\r\n this.mutationCb({ id, type, commands: values });\r\n this.pendingCanvasMutations.delete(canvas);\r\n }\r\n}\n\nclass StylesheetManager {\r\n constructor(options) {\r\n this.trackedLinkElements = new WeakSet();\r\n this.styleMirror = new StyleSheetMirror();\r\n this.mutationCb = options.mutationCb;\r\n this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;\r\n }\r\n attachLinkElement(linkEl, childSn) {\r\n if ('_cssText' in childSn.attributes)\r\n this.mutationCb({\r\n adds: [],\r\n removes: [],\r\n texts: [],\r\n attributes: [\r\n {\r\n id: childSn.id,\r\n attributes: childSn\r\n .attributes,\r\n },\r\n ],\r\n });\r\n this.trackLinkElement(linkEl);\r\n }\r\n trackLinkElement(linkEl) {\r\n if (this.trackedLinkElements.has(linkEl))\r\n return;\r\n this.trackedLinkElements.add(linkEl);\r\n this.trackStylesheetInLinkElement(linkEl);\r\n }\r\n adoptStyleSheets(sheets, hostId) {\r\n if (sheets.length === 0)\r\n return;\r\n const adoptedStyleSheetData = {\r\n id: hostId,\r\n styleIds: [],\r\n };\r\n const styles = [];\r\n for (const sheet of sheets) {\r\n let styleId;\r\n if (!this.styleMirror.has(sheet)) {\r\n styleId = this.styleMirror.add(sheet);\r\n styles.push({\r\n styleId,\r\n rules: Array.from(sheet.rules || CSSRule, (r, index) => ({\r\n rule: stringifyRule(r),\r\n index,\r\n })),\r\n });\r\n }\r\n else\r\n styleId = this.styleMirror.getId(sheet);\r\n adoptedStyleSheetData.styleIds.push(styleId);\r\n }\r\n if (styles.length > 0)\r\n adoptedStyleSheetData.styles = styles;\r\n this.adoptedStyleSheetCb(adoptedStyleSheetData);\r\n }\r\n reset() {\r\n this.styleMirror.reset();\r\n this.trackedLinkElements = new WeakSet();\r\n }\r\n trackStylesheetInLinkElement(linkEl) {\r\n }\r\n}\n\nclass ProcessedNodeManager {\r\n constructor() {\r\n this.nodeMap = new WeakMap();\r\n this.loop = true;\r\n this.periodicallyClear();\r\n }\r\n periodicallyClear() {\r\n requestAnimationFrame(() => {\r\n this.clear();\r\n if (this.loop)\r\n this.periodicallyClear();\r\n });\r\n }\r\n inOtherBuffer(node, thisBuffer) {\r\n const buffers = this.nodeMap.get(node);\r\n return (buffers && Array.from(buffers).some((buffer) => buffer !== thisBuffer));\r\n }\r\n add(node, buffer) {\r\n this.nodeMap.set(node, (this.nodeMap.get(node) || new Set()).add(buffer));\r\n }\r\n clear() {\r\n this.nodeMap = new WeakMap();\r\n }\r\n destroy() {\r\n this.loop = false;\r\n }\r\n}\n\nfunction wrapEvent(e) {\r\n return Object.assign(Object.assign({}, e), { timestamp: nowTimestamp() });\r\n}\r\nlet wrappedEmit;\r\nlet takeFullSnapshot;\r\nlet canvasManager;\r\nlet recording = false;\r\nconst mirror = createMirror();\r\nfunction record(options = {}) {\r\n const { emit, checkoutEveryNms, checkoutEveryNth, blockClass = 'rr-block', blockSelector = null, ignoreClass = 'rr-ignore', ignoreSelector = null, maskTextClass = 'rr-mask', maskTextSelector = null, inlineStylesheet = true, maskAllInputs, maskInputOptions: _maskInputOptions, slimDOMOptions: _slimDOMOptions, maskInputFn, maskTextFn, hooks, packFn, sampling = {}, dataURLOptions = {}, mousemoveWait, recordDOM = true, recordCanvas = false, recordCrossOriginIframes = false, recordAfter = options.recordAfter === 'DOMContentLoaded'\r\n ? options.recordAfter\r\n : 'load', userTriggeredOnInput = false, collectFonts = false, inlineImages = false, plugins, keepIframeSrcFn = () => false, ignoreCSSAttributes = new Set([]), errorHandler, } = options;\r\n registerErrorHandler(errorHandler);\r\n const inEmittingFrame = recordCrossOriginIframes\r\n ? window.parent === window\r\n : true;\r\n let passEmitsToParent = false;\r\n if (!inEmittingFrame) {\r\n try {\r\n if (window.parent.document) {\r\n passEmitsToParent = false;\r\n }\r\n }\r\n catch (e) {\r\n passEmitsToParent = true;\r\n }\r\n }\r\n if (inEmittingFrame && !emit) {\r\n throw new Error('emit function is required');\r\n }\r\n if (mousemoveWait !== undefined && sampling.mousemove === undefined) {\r\n sampling.mousemove = mousemoveWait;\r\n }\r\n mirror.reset();\r\n const maskInputOptions = maskAllInputs === true\r\n ? {\r\n color: true,\r\n date: true,\r\n 'datetime-local': true,\r\n email: true,\r\n month: true,\r\n number: true,\r\n range: true,\r\n search: true,\r\n tel: true,\r\n text: true,\r\n time: true,\r\n url: true,\r\n week: true,\r\n textarea: true,\r\n select: true,\r\n password: true,\r\n }\r\n : _maskInputOptions !== undefined\r\n ? _maskInputOptions\r\n : { password: true };\r\n const slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === 'all'\r\n ? {\r\n script: true,\r\n comment: true,\r\n headFavicon: true,\r\n headWhitespace: true,\r\n headMetaSocial: true,\r\n headMetaRobots: true,\r\n headMetaHttpEquiv: true,\r\n headMetaVerification: true,\r\n headMetaAuthorship: _slimDOMOptions === 'all',\r\n headMetaDescKeywords: _slimDOMOptions === 'all',\r\n }\r\n : _slimDOMOptions\r\n ? _slimDOMOptions\r\n : {};\r\n polyfill();\r\n let lastFullSnapshotEvent;\r\n let incrementalSnapshotCount = 0;\r\n const eventProcessor = (e) => {\r\n for (const plugin of plugins || []) {\r\n if (plugin.eventProcessor) {\r\n e = plugin.eventProcessor(e);\r\n }\r\n }\r\n if (packFn &&\r\n !passEmitsToParent) {\r\n e = packFn(e);\r\n }\r\n return e;\r\n };\r\n wrappedEmit = (e, isCheckout) => {\r\n var _a;\r\n if (((_a = mutationBuffers[0]) === null || _a === void 0 ? void 0 : _a.isFrozen()) &&\r\n e.type !== EventType$1.FullSnapshot &&\r\n !(e.type === EventType$1.IncrementalSnapshot &&\r\n e.data.source === IncrementalSource$1.Mutation)) {\r\n mutationBuffers.forEach((buf) => buf.unfreeze());\r\n }\r\n if (inEmittingFrame) {\r\n emit === null || emit === void 0 ? void 0 : emit(eventProcessor(e), isCheckout);\r\n }\r\n else if (passEmitsToParent) {\r\n const message = {\r\n type: 'rrweb',\r\n event: eventProcessor(e),\r\n origin: window.location.origin,\r\n isCheckout,\r\n };\r\n window.parent.postMessage(message, '*');\r\n }\r\n if (e.type === EventType$1.FullSnapshot) {\r\n lastFullSnapshotEvent = e;\r\n incrementalSnapshotCount = 0;\r\n }\r\n else if (e.type === EventType$1.IncrementalSnapshot) {\r\n if (e.data.source === IncrementalSource$1.Mutation &&\r\n e.data.isAttachIframe) {\r\n return;\r\n }\r\n incrementalSnapshotCount++;\r\n const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;\r\n const exceedTime = checkoutEveryNms &&\r\n e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;\r\n if (exceedCount || exceedTime) {\r\n takeFullSnapshot(true);\r\n }\r\n }\r\n };\r\n const wrappedMutationEmit = (m) => {\r\n wrappedEmit(wrapEvent({\r\n type: EventType$1.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource$1.Mutation }, m),\r\n }));\r\n };\r\n const wrappedScrollEmit = (p) => wrappedEmit(wrapEvent({\r\n type: EventType$1.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource$1.Scroll }, p),\r\n }));\r\n const wrappedCanvasMutationEmit = (p) => wrappedEmit(wrapEvent({\r\n type: EventType$1.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource$1.CanvasMutation }, p),\r\n }));\r\n const wrappedAdoptedStyleSheetEmit = (a) => wrappedEmit(wrapEvent({\r\n type: EventType$1.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource$1.AdoptedStyleSheet }, a),\r\n }));\r\n const stylesheetManager = new StylesheetManager({\r\n mutationCb: wrappedMutationEmit,\r\n adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit,\r\n });\r\n const iframeManager = new IframeManager({\r\n mirror,\r\n mutationCb: wrappedMutationEmit,\r\n stylesheetManager: stylesheetManager,\r\n recordCrossOriginIframes,\r\n wrappedEmit,\r\n });\r\n for (const plugin of plugins || []) {\r\n if (plugin.getMirror)\r\n plugin.getMirror({\r\n nodeMirror: mirror,\r\n crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,\r\n crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror,\r\n });\r\n }\r\n const processedNodeManager = new ProcessedNodeManager();\r\n canvasManager = new CanvasManager({\r\n recordCanvas,\r\n mutationCb: wrappedCanvasMutationEmit,\r\n win: window,\r\n blockClass,\r\n blockSelector,\r\n mirror,\r\n sampling: sampling.canvas,\r\n dataURLOptions,\r\n });\r\n const shadowDomManager = new ShadowDomManager({\r\n mutationCb: wrappedMutationEmit,\r\n scrollCb: wrappedScrollEmit,\r\n bypassOptions: {\r\n blockClass,\r\n blockSelector,\r\n maskTextClass,\r\n maskTextSelector,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n dataURLOptions,\r\n maskTextFn,\r\n maskInputFn,\r\n recordCanvas,\r\n inlineImages,\r\n sampling,\r\n slimDOMOptions,\r\n iframeManager,\r\n stylesheetManager,\r\n canvasManager,\r\n keepIframeSrcFn,\r\n processedNodeManager,\r\n },\r\n mirror,\r\n });\r\n takeFullSnapshot = (isCheckout = false) => {\r\n if (!recordDOM) {\r\n return;\r\n }\r\n wrappedEmit(wrapEvent({\r\n type: EventType$1.Meta,\r\n data: {\r\n href: window.location.href,\r\n width: getWindowWidth(),\r\n height: getWindowHeight(),\r\n },\r\n }), isCheckout);\r\n stylesheetManager.reset();\r\n shadowDomManager.init();\r\n mutationBuffers.forEach((buf) => buf.lock());\r\n const node = snapshot(document, {\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n maskTextClass,\r\n maskTextSelector,\r\n inlineStylesheet,\r\n maskAllInputs: maskInputOptions,\r\n maskTextFn,\r\n slimDOM: slimDOMOptions,\r\n dataURLOptions,\r\n recordCanvas,\r\n inlineImages,\r\n onSerialize: (n) => {\r\n if (isSerializedIframe(n, mirror)) {\r\n iframeManager.addIframe(n);\r\n }\r\n if (isSerializedStylesheet(n, mirror)) {\r\n stylesheetManager.trackLinkElement(n);\r\n }\r\n if (hasShadowRoot(n)) {\r\n shadowDomManager.addShadowRoot(n.shadowRoot, document);\r\n }\r\n },\r\n onIframeLoad: (iframe, childSn) => {\r\n iframeManager.attachIframe(iframe, childSn);\r\n shadowDomManager.observeAttachShadow(iframe);\r\n },\r\n onStylesheetLoad: (linkEl, childSn) => {\r\n stylesheetManager.attachLinkElement(linkEl, childSn);\r\n },\r\n keepIframeSrcFn,\r\n });\r\n if (!node) {\r\n return console.warn('Failed to snapshot the document');\r\n }\r\n wrappedEmit(wrapEvent({\r\n type: EventType$1.FullSnapshot,\r\n data: {\r\n node,\r\n initialOffset: getWindowScroll(window),\r\n },\r\n }), isCheckout);\r\n mutationBuffers.forEach((buf) => buf.unlock());\r\n if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0)\r\n stylesheetManager.adoptStyleSheets(document.adoptedStyleSheets, mirror.getId(document));\r\n };\r\n try {\r\n const handlers = [];\r\n const observe = (doc) => {\r\n var _a;\r\n return callbackWrapper(initObservers)({\r\n mutationCb: wrappedMutationEmit,\r\n mousemoveCb: (positions, source) => wrappedEmit(wrapEvent({\r\n type: EventType$1.IncrementalSnapshot,\r\n data: {\r\n source,\r\n positions,\r\n },\r\n })),\r\n mouseInteractionCb: (d) => wrappedEmit(wrapEvent({\r\n type: EventType$1.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource$1.MouseInteraction }, d),\r\n })),\r\n scrollCb: wrappedScrollEmit,\r\n viewportResizeCb: (d) => wrappedEmit(wrapEvent({\r\n type: EventType$1.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource$1.ViewportResize }, d),\r\n })),\r\n inputCb: (v) => wrappedEmit(wrapEvent({\r\n type: EventType$1.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource$1.Input }, v),\r\n })),\r\n mediaInteractionCb: (p) => wrappedEmit(wrapEvent({\r\n type: EventType$1.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource$1.MediaInteraction }, p),\r\n })),\r\n styleSheetRuleCb: (r) => wrappedEmit(wrapEvent({\r\n type: EventType$1.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource$1.StyleSheetRule }, r),\r\n })),\r\n styleDeclarationCb: (r) => wrappedEmit(wrapEvent({\r\n type: EventType$1.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource$1.StyleDeclaration }, r),\r\n })),\r\n canvasMutationCb: wrappedCanvasMutationEmit,\r\n fontCb: (p) => wrappedEmit(wrapEvent({\r\n type: EventType$1.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource$1.Font }, p),\r\n })),\r\n selectionCb: (p) => {\r\n wrappedEmit(wrapEvent({\r\n type: EventType$1.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource$1.Selection }, p),\r\n }));\r\n },\r\n customElementCb: (c) => {\r\n wrappedEmit(wrapEvent({\r\n type: EventType$1.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource$1.CustomElement }, c),\r\n }));\r\n },\r\n blockClass,\r\n ignoreClass,\r\n ignoreSelector,\r\n maskTextClass,\r\n maskTextSelector,\r\n maskInputOptions,\r\n inlineStylesheet,\r\n sampling,\r\n recordDOM,\r\n recordCanvas,\r\n inlineImages,\r\n userTriggeredOnInput,\r\n collectFonts,\r\n doc,\r\n maskInputFn,\r\n maskTextFn,\r\n keepIframeSrcFn,\r\n blockSelector,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n mirror,\r\n iframeManager,\r\n stylesheetManager,\r\n shadowDomManager,\r\n processedNodeManager,\r\n canvasManager,\r\n ignoreCSSAttributes,\r\n plugins: ((_a = plugins === null || plugins === void 0 ? void 0 : plugins.filter((p) => p.observer)) === null || _a === void 0 ? void 0 : _a.map((p) => ({\r\n observer: p.observer,\r\n options: p.options,\r\n callback: (payload) => wrappedEmit(wrapEvent({\r\n type: EventType$1.Plugin,\r\n data: {\r\n plugin: p.name,\r\n payload,\r\n },\r\n })),\r\n }))) || [],\r\n }, hooks);\r\n };\r\n iframeManager.addLoadListener((iframeEl) => {\r\n try {\r\n handlers.push(observe(iframeEl.contentDocument));\r\n }\r\n catch (error) {\r\n console.warn(error);\r\n }\r\n });\r\n const init = () => {\r\n takeFullSnapshot();\r\n handlers.push(observe(document));\r\n recording = true;\r\n };\r\n if (document.readyState === 'interactive' ||\r\n document.readyState === 'complete') {\r\n init();\r\n }\r\n else {\r\n handlers.push(on('DOMContentLoaded', () => {\r\n wrappedEmit(wrapEvent({\r\n type: EventType$1.DomContentLoaded,\r\n data: {},\r\n }));\r\n if (recordAfter === 'DOMContentLoaded')\r\n init();\r\n }));\r\n handlers.push(on('load', () => {\r\n wrappedEmit(wrapEvent({\r\n type: EventType$1.Load,\r\n data: {},\r\n }));\r\n if (recordAfter === 'load')\r\n init();\r\n }, window));\r\n }\r\n return () => {\r\n handlers.forEach((h) => h());\r\n processedNodeManager.destroy();\r\n recording = false;\r\n unregisterErrorHandler();\r\n };\r\n }\r\n catch (error) {\r\n console.warn(error);\r\n }\r\n}\r\nrecord.addCustomEvent = (tag, payload) => {\r\n if (!recording) {\r\n throw new Error('please add custom event after start recording');\r\n }\r\n wrappedEmit(wrapEvent({\r\n type: EventType$1.Custom,\r\n data: {\r\n tag,\r\n payload,\r\n },\r\n }));\r\n};\r\nrecord.freezePage = () => {\r\n mutationBuffers.forEach((buf) => buf.freeze());\r\n};\r\nrecord.takeFullSnapshot = (isCheckout) => {\r\n if (!recording) {\r\n throw new Error('please take full snapshot after start recording');\r\n }\r\n takeFullSnapshot(isCheckout);\r\n};\r\nrecord.mirror = mirror;\n\nvar EventType = /* @__PURE__ */ ((EventType2) => {\n EventType2[EventType2[\"DomContentLoaded\"] = 0] = \"DomContentLoaded\";\n EventType2[EventType2[\"Load\"] = 1] = \"Load\";\n EventType2[EventType2[\"FullSnapshot\"] = 2] = \"FullSnapshot\";\n EventType2[EventType2[\"IncrementalSnapshot\"] = 3] = \"IncrementalSnapshot\";\n EventType2[EventType2[\"Meta\"] = 4] = \"Meta\";\n EventType2[EventType2[\"Custom\"] = 5] = \"Custom\";\n EventType2[EventType2[\"Plugin\"] = 6] = \"Plugin\";\n return EventType2;\n})(EventType || {});\nvar IncrementalSource = /* @__PURE__ */ ((IncrementalSource2) => {\n IncrementalSource2[IncrementalSource2[\"Mutation\"] = 0] = \"Mutation\";\n IncrementalSource2[IncrementalSource2[\"MouseMove\"] = 1] = \"MouseMove\";\n IncrementalSource2[IncrementalSource2[\"MouseInteraction\"] = 2] = \"MouseInteraction\";\n IncrementalSource2[IncrementalSource2[\"Scroll\"] = 3] = \"Scroll\";\n IncrementalSource2[IncrementalSource2[\"ViewportResize\"] = 4] = \"ViewportResize\";\n IncrementalSource2[IncrementalSource2[\"Input\"] = 5] = \"Input\";\n IncrementalSource2[IncrementalSource2[\"TouchMove\"] = 6] = \"TouchMove\";\n IncrementalSource2[IncrementalSource2[\"MediaInteraction\"] = 7] = \"MediaInteraction\";\n IncrementalSource2[IncrementalSource2[\"StyleSheetRule\"] = 8] = \"StyleSheetRule\";\n IncrementalSource2[IncrementalSource2[\"CanvasMutation\"] = 9] = \"CanvasMutation\";\n IncrementalSource2[IncrementalSource2[\"Font\"] = 10] = \"Font\";\n IncrementalSource2[IncrementalSource2[\"Log\"] = 11] = \"Log\";\n IncrementalSource2[IncrementalSource2[\"Drag\"] = 12] = \"Drag\";\n IncrementalSource2[IncrementalSource2[\"StyleDeclaration\"] = 13] = \"StyleDeclaration\";\n IncrementalSource2[IncrementalSource2[\"Selection\"] = 14] = \"Selection\";\n IncrementalSource2[IncrementalSource2[\"AdoptedStyleSheet\"] = 15] = \"AdoptedStyleSheet\";\n IncrementalSource2[IncrementalSource2[\"CustomElement\"] = 16] = \"CustomElement\";\n return IncrementalSource2;\n})(IncrementalSource || {});\n\nvar Config = {\n DEBUG: false,\n LIB_VERSION: '2.56.0'\n};\n\n/* eslint camelcase: \"off\", eqeqeq: \"off\" */\n\n// since es6 imports are static and we run unit tests from the console, window won't be defined when importing this file\nvar win;\nif (typeof(window) === 'undefined') {\n var loc = {\n hostname: ''\n };\n win = {\n navigator: { userAgent: '', onLine: true },\n document: {\n location: loc,\n referrer: ''\n },\n screen: { width: 0, height: 0 },\n location: loc\n };\n} else {\n win = window;\n}\n\n// Maximum allowed session recording length\nvar MAX_RECORDING_MS = 24 * 60 * 60 * 1000; // 24 hours\n// Maximum allowed value for minimum session recording length\nvar MAX_VALUE_FOR_MIN_RECORDING_MS = 8 * 1000; // 8 seconds\n\n/*\n * Saved references to long variable names, so that closure compiler can\n * minimize file size.\n */\n\nvar ArrayProto = Array.prototype,\n FuncProto = Function.prototype,\n ObjProto = Object.prototype,\n slice = ArrayProto.slice,\n toString = ObjProto.toString,\n hasOwnProperty = ObjProto.hasOwnProperty,\n windowConsole = win.console,\n navigator = win.navigator,\n document$1 = win.document,\n windowOpera = win.opera,\n screen = win.screen,\n userAgent = navigator.userAgent;\n\nvar nativeBind = FuncProto.bind,\n nativeForEach = ArrayProto.forEach,\n nativeIndexOf = ArrayProto.indexOf,\n nativeMap = ArrayProto.map,\n nativeIsArray = Array.isArray,\n breaker = {};\n\nvar _ = {\n trim: function(str) {\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Polyfill\n return str.replace(/^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g, '');\n }\n};\n\n// Console override\nvar console$1 = {\n /** @type {function(...*)} */\n log: function() {\n if (Config.DEBUG && !_.isUndefined(windowConsole) && windowConsole) {\n try {\n windowConsole.log.apply(windowConsole, arguments);\n } catch (err) {\n _.each(arguments, function(arg) {\n windowConsole.log(arg);\n });\n }\n }\n },\n /** @type {function(...*)} */\n warn: function() {\n if (Config.DEBUG && !_.isUndefined(windowConsole) && windowConsole) {\n var args = ['Mixpanel warning:'].concat(_.toArray(arguments));\n try {\n windowConsole.warn.apply(windowConsole, args);\n } catch (err) {\n _.each(args, function(arg) {\n windowConsole.warn(arg);\n });\n }\n }\n },\n /** @type {function(...*)} */\n error: function() {\n if (Config.DEBUG && !_.isUndefined(windowConsole) && windowConsole) {\n var args = ['Mixpanel error:'].concat(_.toArray(arguments));\n try {\n windowConsole.error.apply(windowConsole, args);\n } catch (err) {\n _.each(args, function(arg) {\n windowConsole.error(arg);\n });\n }\n }\n },\n /** @type {function(...*)} */\n critical: function() {\n if (!_.isUndefined(windowConsole) && windowConsole) {\n var args = ['Mixpanel error:'].concat(_.toArray(arguments));\n try {\n windowConsole.error.apply(windowConsole, args);\n } catch (err) {\n _.each(args, function(arg) {\n windowConsole.error(arg);\n });\n }\n }\n }\n};\n\nvar log_func_with_prefix = function(func, prefix) {\n return function() {\n arguments[0] = '[' + prefix + '] ' + arguments[0];\n return func.apply(console$1, arguments);\n };\n};\nvar console_with_prefix = function(prefix) {\n return {\n log: log_func_with_prefix(console$1.log, prefix),\n error: log_func_with_prefix(console$1.error, prefix),\n critical: log_func_with_prefix(console$1.critical, prefix)\n };\n};\n\n\n// UNDERSCORE\n// Embed part of the Underscore Library\n_.bind = function(func, context) {\n var args, bound;\n if (nativeBind && func.bind === nativeBind) {\n return nativeBind.apply(func, slice.call(arguments, 1));\n }\n if (!_.isFunction(func)) {\n throw new TypeError();\n }\n args = slice.call(arguments, 2);\n bound = function() {\n if (!(this instanceof bound)) {\n return func.apply(context, args.concat(slice.call(arguments)));\n }\n var ctor = {};\n ctor.prototype = func.prototype;\n var self = new ctor();\n ctor.prototype = null;\n var result = func.apply(self, args.concat(slice.call(arguments)));\n if (Object(result) === result) {\n return result;\n }\n return self;\n };\n return bound;\n};\n\n/**\n * @param {*=} obj\n * @param {function(...*)=} iterator\n * @param {Object=} context\n */\n_.each = function(obj, iterator, context) {\n if (obj === null || obj === undefined) {\n return;\n }\n if (nativeForEach && obj.forEach === nativeForEach) {\n obj.forEach(iterator, context);\n } else if (obj.length === +obj.length) {\n for (var i = 0, l = obj.length; i < l; i++) {\n if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) {\n return;\n }\n }\n } else {\n for (var key in obj) {\n if (hasOwnProperty.call(obj, key)) {\n if (iterator.call(context, obj[key], key, obj) === breaker) {\n return;\n }\n }\n }\n }\n};\n\n_.extend = function(obj) {\n _.each(slice.call(arguments, 1), function(source) {\n for (var prop in source) {\n if (source[prop] !== void 0) {\n obj[prop] = source[prop];\n }\n }\n });\n return obj;\n};\n\n_.isArray = nativeIsArray || function(obj) {\n return toString.call(obj) === '[object Array]';\n};\n\n// from a comment on http://dbj.org/dbj/?p=286\n// fails on only one very rare and deliberate custom object:\n// var bomb = { toString : undefined, valueOf: function(o) { return \"function BOMBA!\"; }};\n_.isFunction = function(f) {\n try {\n return /^\\s*\\bfunction\\b/.test(f);\n } catch (x) {\n return false;\n }\n};\n\n_.isArguments = function(obj) {\n return !!(obj && hasOwnProperty.call(obj, 'callee'));\n};\n\n_.toArray = function(iterable) {\n if (!iterable) {\n return [];\n }\n if (iterable.toArray) {\n return iterable.toArray();\n }\n if (_.isArray(iterable)) {\n return slice.call(iterable);\n }\n if (_.isArguments(iterable)) {\n return slice.call(iterable);\n }\n return _.values(iterable);\n};\n\n_.map = function(arr, callback, context) {\n if (nativeMap && arr.map === nativeMap) {\n return arr.map(callback, context);\n } else {\n var results = [];\n _.each(arr, function(item) {\n results.push(callback.call(context, item));\n });\n return results;\n }\n};\n\n_.keys = function(obj) {\n var results = [];\n if (obj === null) {\n return results;\n }\n _.each(obj, function(value, key) {\n results[results.length] = key;\n });\n return results;\n};\n\n_.values = function(obj) {\n var results = [];\n if (obj === null) {\n return results;\n }\n _.each(obj, function(value) {\n results[results.length] = value;\n });\n return results;\n};\n\n_.include = function(obj, target) {\n var found = false;\n if (obj === null) {\n return found;\n }\n if (nativeIndexOf && obj.indexOf === nativeIndexOf) {\n return obj.indexOf(target) != -1;\n }\n _.each(obj, function(value) {\n if (found || (found = (value === target))) {\n return breaker;\n }\n });\n return found;\n};\n\n_.includes = function(str, needle) {\n return str.indexOf(needle) !== -1;\n};\n\n// Underscore Addons\n_.inherit = function(subclass, superclass) {\n subclass.prototype = new superclass();\n subclass.prototype.constructor = subclass;\n subclass.superclass = superclass.prototype;\n return subclass;\n};\n\n_.isObject = function(obj) {\n return (obj === Object(obj) && !_.isArray(obj));\n};\n\n_.isEmptyObject = function(obj) {\n if (_.isObject(obj)) {\n for (var key in obj) {\n if (hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n }\n return false;\n};\n\n_.isUndefined = function(obj) {\n return obj === void 0;\n};\n\n_.isString = function(obj) {\n return toString.call(obj) == '[object String]';\n};\n\n_.isDate = function(obj) {\n return toString.call(obj) == '[object Date]';\n};\n\n_.isNumber = function(obj) {\n return toString.call(obj) == '[object Number]';\n};\n\n_.isElement = function(obj) {\n return !!(obj && obj.nodeType === 1);\n};\n\n_.encodeDates = function(obj) {\n _.each(obj, function(v, k) {\n if (_.isDate(v)) {\n obj[k] = _.formatDate(v);\n } else if (_.isObject(v)) {\n obj[k] = _.encodeDates(v); // recurse\n }\n });\n return obj;\n};\n\n_.timestamp = function() {\n Date.now = Date.now || function() {\n return +new Date;\n };\n return Date.now();\n};\n\n_.formatDate = function(d) {\n // YYYY-MM-DDTHH:MM:SS in UTC\n function pad(n) {\n return n < 10 ? '0' + n : n;\n }\n return d.getUTCFullYear() + '-' +\n pad(d.getUTCMonth() + 1) + '-' +\n pad(d.getUTCDate()) + 'T' +\n pad(d.getUTCHours()) + ':' +\n pad(d.getUTCMinutes()) + ':' +\n pad(d.getUTCSeconds());\n};\n\n_.strip_empty_properties = function(p) {\n var ret = {};\n _.each(p, function(v, k) {\n if (_.isString(v) && v.length > 0) {\n ret[k] = v;\n }\n });\n return ret;\n};\n\n/*\n * this function returns a copy of object after truncating it. If\n * passed an Array or Object it will iterate through obj and\n * truncate all the values recursively.\n */\n_.truncate = function(obj, length) {\n var ret;\n\n if (typeof(obj) === 'string') {\n ret = obj.slice(0, length);\n } else if (_.isArray(obj)) {\n ret = [];\n _.each(obj, function(val) {\n ret.push(_.truncate(val, length));\n });\n } else if (_.isObject(obj)) {\n ret = {};\n _.each(obj, function(val, key) {\n ret[key] = _.truncate(val, length);\n });\n } else {\n ret = obj;\n }\n\n return ret;\n};\n\n_.JSONEncode = (function() {\n return function(mixed_val) {\n var value = mixed_val;\n var quote = function(string) {\n var escapable = /[\\\\\"\\x00-\\x1f\\x7f-\\x9f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]/g; // eslint-disable-line no-control-regex\n var meta = { // table of character substitutions\n '\\b': '\\\\b',\n '\\t': '\\\\t',\n '\\n': '\\\\n',\n '\\f': '\\\\f',\n '\\r': '\\\\r',\n '\"': '\\\\\"',\n '\\\\': '\\\\\\\\'\n };\n\n escapable.lastIndex = 0;\n return escapable.test(string) ?\n '\"' + string.replace(escapable, function(a) {\n var c = meta[a];\n return typeof c === 'string' ? c :\n '\\\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);\n }) + '\"' :\n '\"' + string + '\"';\n };\n\n var str = function(key, holder) {\n var gap = '';\n var indent = ' ';\n var i = 0; // The loop counter.\n var k = ''; // The member key.\n var v = ''; // The member value.\n var length = 0;\n var mind = gap;\n var partial = [];\n var value = holder[key];\n\n // If the value has a toJSON method, call it to obtain a replacement value.\n if (value && typeof value === 'object' &&\n typeof value.toJSON === 'function') {\n value = value.toJSON(key);\n }\n\n // What happens next depends on the value's type.\n switch (typeof value) {\n case 'string':\n return quote(value);\n\n case 'number':\n // JSON numbers must be finite. Encode non-finite numbers as null.\n return isFinite(value) ? String(value) : 'null';\n\n case 'boolean':\n case 'null':\n // If the value is a boolean or null, convert it to a string. Note:\n // typeof null does not produce 'null'. The case is included here in\n // the remote chance that this gets fixed someday.\n\n return String(value);\n\n case 'object':\n // If the type is 'object', we might be dealing with an object or an array or\n // null.\n // Due to a specification blunder in ECMAScript, typeof null is 'object',\n // so watch out for that case.\n if (!value) {\n return 'null';\n }\n\n // Make an array to hold the partial results of stringifying this object value.\n gap += indent;\n partial = [];\n\n // Is the value an array?\n if (toString.apply(value) === '[object Array]') {\n // The value is an array. Stringify every element. Use null as a placeholder\n // for non-JSON values.\n\n length = value.length;\n for (i = 0; i < length; i += 1) {\n partial[i] = str(i, value) || 'null';\n }\n\n // Join all of the elements together, separated with commas, and wrap them in\n // brackets.\n v = partial.length === 0 ? '[]' :\n gap ? '[\\n' + gap +\n partial.join(',\\n' + gap) + '\\n' +\n mind + ']' :\n '[' + partial.join(',') + ']';\n gap = mind;\n return v;\n }\n\n // Iterate through all of the keys in the object.\n for (k in value) {\n if (hasOwnProperty.call(value, k)) {\n v = str(k, value);\n if (v) {\n partial.push(quote(k) + (gap ? ': ' : ':') + v);\n }\n }\n }\n\n // Join all of the member texts together, separated with commas,\n // and wrap them in braces.\n v = partial.length === 0 ? '{}' :\n gap ? '{' + partial.join(',') + '' +\n mind + '}' : '{' + partial.join(',') + '}';\n gap = mind;\n return v;\n }\n };\n\n // Make a fake root object containing our value under the key of ''.\n // Return the result of stringifying the value.\n return str('', {\n '': value\n });\n };\n})();\n\n/**\n * From https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js\n * Slightly modified to throw a real Error rather than a POJO\n */\n_.JSONDecode = (function() {\n var at, // The index of the current character\n ch, // The current character\n escapee = {\n '\"': '\"',\n '\\\\': '\\\\',\n '/': '/',\n 'b': '\\b',\n 'f': '\\f',\n 'n': '\\n',\n 'r': '\\r',\n 't': '\\t'\n },\n text,\n error = function(m) {\n var e = new SyntaxError(m);\n e.at = at;\n e.text = text;\n throw e;\n },\n next = function(c) {\n // If a c parameter is provided, verify that it matches the current character.\n if (c && c !== ch) {\n error('Expected \\'' + c + '\\' instead of \\'' + ch + '\\'');\n }\n // Get the next character. When there are no more characters,\n // return the empty string.\n ch = text.charAt(at);\n at += 1;\n return ch;\n },\n number = function() {\n // Parse a number value.\n var number,\n string = '';\n\n if (ch === '-') {\n string = '-';\n next('-');\n }\n while (ch >= '0' && ch <= '9') {\n string += ch;\n next();\n }\n if (ch === '.') {\n string += '.';\n while (next() && ch >= '0' && ch <= '9') {\n string += ch;\n }\n }\n if (ch === 'e' || ch === 'E') {\n string += ch;\n next();\n if (ch === '-' || ch === '+') {\n string += ch;\n next();\n }\n while (ch >= '0' && ch <= '9') {\n string += ch;\n next();\n }\n }\n number = +string;\n if (!isFinite(number)) {\n error('Bad number');\n } else {\n return number;\n }\n },\n\n string = function() {\n // Parse a string value.\n var hex,\n i,\n string = '',\n uffff;\n // When parsing for string values, we must look for \" and \\ characters.\n if (ch === '\"') {\n while (next()) {\n if (ch === '\"') {\n next();\n return string;\n }\n if (ch === '\\\\') {\n next();\n if (ch === 'u') {\n uffff = 0;\n for (i = 0; i < 4; i += 1) {\n hex = parseInt(next(), 16);\n if (!isFinite(hex)) {\n break;\n }\n uffff = uffff * 16 + hex;\n }\n string += String.fromCharCode(uffff);\n } else if (typeof escapee[ch] === 'string') {\n string += escapee[ch];\n } else {\n break;\n }\n } else {\n string += ch;\n }\n }\n }\n error('Bad string');\n },\n white = function() {\n // Skip whitespace.\n while (ch && ch <= ' ') {\n next();\n }\n },\n word = function() {\n // true, false, or null.\n switch (ch) {\n case 't':\n next('t');\n next('r');\n next('u');\n next('e');\n return true;\n case 'f':\n next('f');\n next('a');\n next('l');\n next('s');\n next('e');\n return false;\n case 'n':\n next('n');\n next('u');\n next('l');\n next('l');\n return null;\n }\n error('Unexpected \"' + ch + '\"');\n },\n value, // Placeholder for the value function.\n array = function() {\n // Parse an array value.\n var array = [];\n\n if (ch === '[') {\n next('[');\n white();\n if (ch === ']') {\n next(']');\n return array; // empty array\n }\n while (ch) {\n array.push(value());\n white();\n if (ch === ']') {\n next(']');\n return array;\n }\n next(',');\n white();\n }\n }\n error('Bad array');\n },\n object = function() {\n // Parse an object value.\n var key,\n object = {};\n\n if (ch === '{') {\n next('{');\n white();\n if (ch === '}') {\n next('}');\n return object; // empty object\n }\n while (ch) {\n key = string();\n white();\n next(':');\n if (Object.hasOwnProperty.call(object, key)) {\n error('Duplicate key \"' + key + '\"');\n }\n object[key] = value();\n white();\n if (ch === '}') {\n next('}');\n return object;\n }\n next(',');\n white();\n }\n }\n error('Bad object');\n };\n\n value = function() {\n // Parse a JSON value. It could be an object, an array, a string,\n // a number, or a word.\n white();\n switch (ch) {\n case '{':\n return object();\n case '[':\n return array();\n case '\"':\n return string();\n case '-':\n return number();\n default:\n return ch >= '0' && ch <= '9' ? number() : word();\n }\n };\n\n // Return the json_parse function. It will have access to all of the\n // above functions and variables.\n return function(source) {\n var result;\n\n text = source;\n at = 0;\n ch = ' ';\n result = value();\n white();\n if (ch) {\n error('Syntax error');\n }\n\n return result;\n };\n})();\n\n_.base64Encode = function(data) {\n var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,\n ac = 0,\n enc = '',\n tmp_arr = [];\n\n if (!data) {\n return data;\n }\n\n data = _.utf8Encode(data);\n\n do { // pack three octets into four hexets\n o1 = data.charCodeAt(i++);\n o2 = data.charCodeAt(i++);\n o3 = data.charCodeAt(i++);\n\n bits = o1 << 16 | o2 << 8 | o3;\n\n h1 = bits >> 18 & 0x3f;\n h2 = bits >> 12 & 0x3f;\n h3 = bits >> 6 & 0x3f;\n h4 = bits & 0x3f;\n\n // use hexets to index into b64, and append result to encoded string\n tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);\n } while (i < data.length);\n\n enc = tmp_arr.join('');\n\n switch (data.length % 3) {\n case 1:\n enc = enc.slice(0, -2) + '==';\n break;\n case 2:\n enc = enc.slice(0, -1) + '=';\n break;\n }\n\n return enc;\n};\n\n_.utf8Encode = function(string) {\n string = (string + '').replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n\n var utftext = '',\n start,\n end;\n var stringl = 0,\n n;\n\n start = end = 0;\n stringl = string.length;\n\n for (n = 0; n < stringl; n++) {\n var c1 = string.charCodeAt(n);\n var enc = null;\n\n if (c1 < 128) {\n end++;\n } else if ((c1 > 127) && (c1 < 2048)) {\n enc = String.fromCharCode((c1 >> 6) | 192, (c1 & 63) | 128);\n } else {\n enc = String.fromCharCode((c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128);\n }\n if (enc !== null) {\n if (end > start) {\n utftext += string.substring(start, end);\n }\n utftext += enc;\n start = end = n + 1;\n }\n }\n\n if (end > start) {\n utftext += string.substring(start, string.length);\n }\n\n return utftext;\n};\n\n_.UUID = (function() {\n\n // Time-based entropy\n var T = function() {\n var time = 1 * new Date(); // cross-browser version of Date.now()\n var ticks;\n if (win.performance && win.performance.now) {\n ticks = win.performance.now();\n } else {\n // fall back to busy loop\n ticks = 0;\n\n // this while loop figures how many browser ticks go by\n // before 1*new Date() returns a new number, ie the amount\n // of ticks that go by per millisecond\n while (time == 1 * new Date()) {\n ticks++;\n }\n }\n return time.toString(16) + Math.floor(ticks).toString(16);\n };\n\n // Math.Random entropy\n var R = function() {\n return Math.random().toString(16).replace('.', '');\n };\n\n // User agent entropy\n // This function takes the user agent string, and then xors\n // together each sequence of 8 bytes. This produces a final\n // sequence of 8 bytes which it returns as hex.\n var UA = function() {\n var ua = userAgent,\n i, ch, buffer = [],\n ret = 0;\n\n function xor(result, byte_array) {\n var j, tmp = 0;\n for (j = 0; j < byte_array.length; j++) {\n tmp |= (buffer[j] << j * 8);\n }\n return result ^ tmp;\n }\n\n for (i = 0; i < ua.length; i++) {\n ch = ua.charCodeAt(i);\n buffer.unshift(ch & 0xFF);\n if (buffer.length >= 4) {\n ret = xor(ret, buffer);\n buffer = [];\n }\n }\n\n if (buffer.length > 0) {\n ret = xor(ret, buffer);\n }\n\n return ret.toString(16);\n };\n\n return function() {\n var se = (screen.height * screen.width).toString(16);\n return (T() + '-' + R() + '-' + UA() + '-' + se + '-' + T());\n };\n})();\n\n// _.isBlockedUA()\n// This is to block various web spiders from executing our JS and\n// sending false tracking data\nvar BLOCKED_UA_STRS = [\n 'ahrefsbot',\n 'ahrefssiteaudit',\n 'baiduspider',\n 'bingbot',\n 'bingpreview',\n 'chrome-lighthouse',\n 'facebookexternal',\n 'petalbot',\n 'pinterest',\n 'screaming frog',\n 'yahoo! slurp',\n 'yandexbot',\n\n // a whole bunch of goog-specific crawlers\n // https://developers.google.com/search/docs/advanced/crawling/overview-google-crawlers\n 'adsbot-google',\n 'apis-google',\n 'duplexweb-google',\n 'feedfetcher-google',\n 'google favicon',\n 'google web preview',\n 'google-read-aloud',\n 'googlebot',\n 'googleweblight',\n 'mediapartners-google',\n 'storebot-google'\n];\n_.isBlockedUA = function(ua) {\n var i;\n ua = ua.toLowerCase();\n for (i = 0; i < BLOCKED_UA_STRS.length; i++) {\n if (ua.indexOf(BLOCKED_UA_STRS[i]) !== -1) {\n return true;\n }\n }\n return false;\n};\n\n/**\n * @param {Object=} formdata\n * @param {string=} arg_separator\n */\n_.HTTPBuildQuery = function(formdata, arg_separator) {\n var use_val, use_key, tmp_arr = [];\n\n if (_.isUndefined(arg_separator)) {\n arg_separator = '&';\n }\n\n _.each(formdata, function(val, key) {\n use_val = encodeURIComponent(val.toString());\n use_key = encodeURIComponent(key);\n tmp_arr[tmp_arr.length] = use_key + '=' + use_val;\n });\n\n return tmp_arr.join(arg_separator);\n};\n\n_.getQueryParam = function(url, param) {\n // Expects a raw URL\n\n param = param.replace(/[[]/g, '\\\\[').replace(/[\\]]/g, '\\\\]');\n var regexS = '[\\\\?&]' + param + '=([^]*)',\n regex = new RegExp(regexS),\n results = regex.exec(url);\n if (results === null || (results && typeof(results[1]) !== 'string' && results[1].length)) {\n return '';\n } else {\n var result = results[1];\n try {\n result = decodeURIComponent(result);\n } catch(err) {\n console$1.error('Skipping decoding for malformed query param: ' + result);\n }\n return result.replace(/\\+/g, ' ');\n }\n};\n\n\n// _.cookie\n// Methods partially borrowed from quirksmode.org/js/cookies.html\n_.cookie = {\n get: function(name) {\n var nameEQ = name + '=';\n var ca = document$1.cookie.split(';');\n for (var i = 0; i < ca.length; i++) {\n var c = ca[i];\n while (c.charAt(0) == ' ') {\n c = c.substring(1, c.length);\n }\n if (c.indexOf(nameEQ) === 0) {\n return decodeURIComponent(c.substring(nameEQ.length, c.length));\n }\n }\n return null;\n },\n\n parse: function(name) {\n var cookie;\n try {\n cookie = _.JSONDecode(_.cookie.get(name)) || {};\n } catch (err) {\n // noop\n }\n return cookie;\n },\n\n set_seconds: function(name, value, seconds, is_cross_subdomain, is_secure, is_cross_site, domain_override) {\n var cdomain = '',\n expires = '',\n secure = '';\n\n if (domain_override) {\n cdomain = '; domain=' + domain_override;\n } else if (is_cross_subdomain) {\n var domain = extract_domain(document$1.location.hostname);\n cdomain = domain ? '; domain=.' + domain : '';\n }\n\n if (seconds) {\n var date = new Date();\n date.setTime(date.getTime() + (seconds * 1000));\n expires = '; expires=' + date.toGMTString();\n }\n\n if (is_cross_site) {\n is_secure = true;\n secure = '; SameSite=None';\n }\n if (is_secure) {\n secure += '; secure';\n }\n\n document$1.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/' + cdomain + secure;\n },\n\n set: function(name, value, days, is_cross_subdomain, is_secure, is_cross_site, domain_override) {\n var cdomain = '', expires = '', secure = '';\n\n if (domain_override) {\n cdomain = '; domain=' + domain_override;\n } else if (is_cross_subdomain) {\n var domain = extract_domain(document$1.location.hostname);\n cdomain = domain ? '; domain=.' + domain : '';\n }\n\n if (days) {\n var date = new Date();\n date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));\n expires = '; expires=' + date.toGMTString();\n }\n\n if (is_cross_site) {\n is_secure = true;\n secure = '; SameSite=None';\n }\n if (is_secure) {\n secure += '; secure';\n }\n\n var new_cookie_val = name + '=' + encodeURIComponent(value) + expires + '; path=/' + cdomain + secure;\n document$1.cookie = new_cookie_val;\n return new_cookie_val;\n },\n\n remove: function(name, is_cross_subdomain, domain_override) {\n _.cookie.set(name, '', -1, is_cross_subdomain, false, false, domain_override);\n }\n};\n\nvar _localStorageSupported = null;\nvar localStorageSupported = function(storage, forceCheck) {\n if (_localStorageSupported !== null && !forceCheck) {\n return _localStorageSupported;\n }\n\n var supported = true;\n try {\n storage = storage || window.localStorage;\n var key = '__mplss_' + cheap_guid(8),\n val = 'xyz';\n storage.setItem(key, val);\n if (storage.getItem(key) !== val) {\n supported = false;\n }\n storage.removeItem(key);\n } catch (err) {\n supported = false;\n }\n\n _localStorageSupported = supported;\n return supported;\n};\n\n// _.localStorage\n_.localStorage = {\n is_supported: function(force_check) {\n var supported = localStorageSupported(null, force_check);\n if (!supported) {\n console$1.error('localStorage unsupported; falling back to cookie store');\n }\n return supported;\n },\n\n error: function(msg) {\n console$1.error('localStorage error: ' + msg);\n },\n\n get: function(name) {\n try {\n return window.localStorage.getItem(name);\n } catch (err) {\n _.localStorage.error(err);\n }\n return null;\n },\n\n parse: function(name) {\n try {\n return _.JSONDecode(_.localStorage.get(name)) || {};\n } catch (err) {\n // noop\n }\n return null;\n },\n\n set: function(name, value) {\n try {\n window.localStorage.setItem(name, value);\n } catch (err) {\n _.localStorage.error(err);\n }\n },\n\n remove: function(name) {\n try {\n window.localStorage.removeItem(name);\n } catch (err) {\n _.localStorage.error(err);\n }\n }\n};\n\n_.register_event = (function() {\n // written by Dean Edwards, 2005\n // with input from Tino Zijdel - crisp@xs4all.nl\n // with input from Carl Sverre - mail@carlsverre.com\n // with input from Mixpanel\n // http://dean.edwards.name/weblog/2005/10/add-event/\n // https://gist.github.com/1930440\n\n /**\n * @param {Object} element\n * @param {string} type\n * @param {function(...*)} handler\n * @param {boolean=} oldSchool\n * @param {boolean=} useCapture\n */\n var register_event = function(element, type, handler, oldSchool, useCapture) {\n if (!element) {\n console$1.error('No valid element provided to register_event');\n return;\n }\n\n if (element.addEventListener && !oldSchool) {\n element.addEventListener(type, handler, !!useCapture);\n } else {\n var ontype = 'on' + type;\n var old_handler = element[ontype]; // can be undefined\n element[ontype] = makeHandler(element, handler, old_handler);\n }\n };\n\n function makeHandler(element, new_handler, old_handlers) {\n var handler = function(event) {\n event = event || fixEvent(window.event);\n\n // this basically happens in firefox whenever another script\n // overwrites the onload callback and doesn't pass the event\n // object to previously defined callbacks. All the browsers\n // that don't define window.event implement addEventListener\n // so the dom_loaded handler will still be fired as usual.\n if (!event) {\n return undefined;\n }\n\n var ret = true;\n var old_result, new_result;\n\n if (_.isFunction(old_handlers)) {\n old_result = old_handlers(event);\n }\n new_result = new_handler.call(element, event);\n\n if ((false === old_result) || (false === new_result)) {\n ret = false;\n }\n\n return ret;\n };\n\n return handler;\n }\n\n function fixEvent(event) {\n if (event) {\n event.preventDefault = fixEvent.preventDefault;\n event.stopPropagation = fixEvent.stopPropagation;\n }\n return event;\n }\n fixEvent.preventDefault = function() {\n this.returnValue = false;\n };\n fixEvent.stopPropagation = function() {\n this.cancelBubble = true;\n };\n\n return register_event;\n})();\n\n\nvar TOKEN_MATCH_REGEX = new RegExp('^(\\\\w*)\\\\[(\\\\w+)([=~\\\\|\\\\^\\\\$\\\\*]?)=?\"?([^\\\\]\"]*)\"?\\\\]$');\n\n_.dom_query = (function() {\n /* document.getElementsBySelector(selector)\n - returns an array of element objects from the current document\n matching the CSS selector. Selectors can contain element names,\n class names and ids and can be nested. For example:\n\n elements = document.getElementsBySelector('div#main p a.external')\n\n Will return an array of all 'a' elements with 'external' in their\n class attribute that are contained inside 'p' elements that are\n contained inside the 'div' element which has id=\"main\"\n\n New in version 0.4: Support for CSS2 and CSS3 attribute selectors:\n See http://www.w3.org/TR/css3-selectors/#attribute-selectors\n\n Version 0.4 - Simon Willison, March 25th 2003\n -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows\n -- Opera 7 fails\n\n Version 0.5 - Carl Sverre, Jan 7th 2013\n -- Now uses jQuery-esque `hasClass` for testing class name\n equality. This fixes a bug related to '-' characters being\n considered not part of a 'word' in regex.\n */\n\n function getAllChildren(e) {\n // Returns all children of element. Workaround required for IE5/Windows. Ugh.\n return e.all ? e.all : e.getElementsByTagName('*');\n }\n\n var bad_whitespace = /[\\t\\r\\n]/g;\n\n function hasClass(elem, selector) {\n var className = ' ' + selector + ' ';\n return ((' ' + elem.className + ' ').replace(bad_whitespace, ' ').indexOf(className) >= 0);\n }\n\n function getElementsBySelector(selector) {\n // Attempt to fail gracefully in lesser browsers\n if (!document$1.getElementsByTagName) {\n return [];\n }\n // Split selector in to tokens\n var tokens = selector.split(' ');\n var token, bits, tagName, found, foundCount, i, j, k, elements, currentContextIndex;\n var currentContext = [document$1];\n for (i = 0; i < tokens.length; i++) {\n token = tokens[i].replace(/^\\s+/, '').replace(/\\s+$/, '');\n if (token.indexOf('#') > -1) {\n // Token is an ID selector\n bits = token.split('#');\n tagName = bits[0];\n var id = bits[1];\n var element = document$1.getElementById(id);\n if (!element || (tagName && element.nodeName.toLowerCase() != tagName)) {\n // element not found or tag with that ID not found, return false\n return [];\n }\n // Set currentContext to contain just this element\n currentContext = [element];\n continue; // Skip to next token\n }\n if (token.indexOf('.') > -1) {\n // Token contains a class selector\n bits = token.split('.');\n tagName = bits[0];\n var className = bits[1];\n if (!tagName) {\n tagName = '*';\n }\n // Get elements matching tag, filter them for class selector\n found = [];\n foundCount = 0;\n for (j = 0; j < currentContext.length; j++) {\n if (tagName == '*') {\n elements = getAllChildren(currentContext[j]);\n } else {\n elements = currentContext[j].getElementsByTagName(tagName);\n }\n for (k = 0; k < elements.length; k++) {\n found[foundCount++] = elements[k];\n }\n }\n currentContext = [];\n currentContextIndex = 0;\n for (j = 0; j < found.length; j++) {\n if (found[j].className &&\n _.isString(found[j].className) && // some SVG elements have classNames which are not strings\n hasClass(found[j], className)\n ) {\n currentContext[currentContextIndex++] = found[j];\n }\n }\n continue; // Skip to next token\n }\n // Code to deal with attribute selectors\n var token_match = token.match(TOKEN_MATCH_REGEX);\n if (token_match) {\n tagName = token_match[1];\n var attrName = token_match[2];\n var attrOperator = token_match[3];\n var attrValue = token_match[4];\n if (!tagName) {\n tagName = '*';\n }\n // Grab all of the tagName elements within current context\n found = [];\n foundCount = 0;\n for (j = 0; j < currentContext.length; j++) {\n if (tagName == '*') {\n elements = getAllChildren(currentContext[j]);\n } else {\n elements = currentContext[j].getElementsByTagName(tagName);\n }\n for (k = 0; k < elements.length; k++) {\n found[foundCount++] = elements[k];\n }\n }\n currentContext = [];\n currentContextIndex = 0;\n var checkFunction; // This function will be used to filter the elements\n switch (attrOperator) {\n case '=': // Equality\n checkFunction = function(e) {\n return (e.getAttribute(attrName) == attrValue);\n };\n break;\n case '~': // Match one of space seperated words\n checkFunction = function(e) {\n return (e.getAttribute(attrName).match(new RegExp('\\\\b' + attrValue + '\\\\b')));\n };\n break;\n case '|': // Match start with value followed by optional hyphen\n checkFunction = function(e) {\n return (e.getAttribute(attrName).match(new RegExp('^' + attrValue + '-?')));\n };\n break;\n case '^': // Match starts with value\n checkFunction = function(e) {\n return (e.getAttribute(attrName).indexOf(attrValue) === 0);\n };\n break;\n case '$': // Match ends with value - fails with \"Warning\" in Opera 7\n checkFunction = function(e) {\n return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length);\n };\n break;\n case '*': // Match ends with value\n checkFunction = function(e) {\n return (e.getAttribute(attrName).indexOf(attrValue) > -1);\n };\n break;\n default:\n // Just test for existence of attribute\n checkFunction = function(e) {\n return e.getAttribute(attrName);\n };\n }\n currentContext = [];\n currentContextIndex = 0;\n for (j = 0; j < found.length; j++) {\n if (checkFunction(found[j])) {\n currentContext[currentContextIndex++] = found[j];\n }\n }\n // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);\n continue; // Skip to next token\n }\n // If we get here, token is JUST an element (not a class or ID selector)\n tagName = token;\n found = [];\n foundCount = 0;\n for (j = 0; j < currentContext.length; j++) {\n elements = currentContext[j].getElementsByTagName(tagName);\n for (k = 0; k < elements.length; k++) {\n found[foundCount++] = elements[k];\n }\n }\n currentContext = found;\n }\n return currentContext;\n }\n\n return function(query) {\n if (_.isElement(query)) {\n return [query];\n } else if (_.isObject(query) && !_.isUndefined(query.length)) {\n return query;\n } else {\n return getElementsBySelector.call(this, query);\n }\n };\n})();\n\nvar CAMPAIGN_KEYWORDS = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term', 'utm_id', 'utm_source_platform','utm_campaign_id', 'utm_creative_format', 'utm_marketing_tactic'];\nvar CLICK_IDS = ['dclid', 'fbclid', 'gclid', 'ko_click_id', 'li_fat_id', 'msclkid', 'sccid', 'ttclid', 'twclid', 'wbraid'];\n\n_.info = {\n campaignParams: function(default_value) {\n var kw = '',\n params = {};\n _.each(CAMPAIGN_KEYWORDS, function(kwkey) {\n kw = _.getQueryParam(document$1.URL, kwkey);\n if (kw.length) {\n params[kwkey] = kw;\n } else if (default_value !== undefined) {\n params[kwkey] = default_value;\n }\n });\n\n return params;\n },\n\n clickParams: function() {\n var id = '',\n params = {};\n _.each(CLICK_IDS, function(idkey) {\n id = _.getQueryParam(document$1.URL, idkey);\n if (id.length) {\n params[idkey] = id;\n }\n });\n\n return params;\n },\n\n marketingParams: function() {\n return _.extend(_.info.campaignParams(), _.info.clickParams());\n },\n\n searchEngine: function(referrer) {\n if (referrer.search('https?://(.*)google.([^/?]*)') === 0) {\n return 'google';\n } else if (referrer.search('https?://(.*)bing.com') === 0) {\n return 'bing';\n } else if (referrer.search('https?://(.*)yahoo.com') === 0) {\n return 'yahoo';\n } else if (referrer.search('https?://(.*)duckduckgo.com') === 0) {\n return 'duckduckgo';\n } else {\n return null;\n }\n },\n\n searchInfo: function(referrer) {\n var search = _.info.searchEngine(referrer),\n param = (search != 'yahoo') ? 'q' : 'p',\n ret = {};\n\n if (search !== null) {\n ret['$search_engine'] = search;\n\n var keyword = _.getQueryParam(referrer, param);\n if (keyword.length) {\n ret['mp_keyword'] = keyword;\n }\n }\n\n return ret;\n },\n\n /**\n * This function detects which browser is running this script.\n * The order of the checks are important since many user agents\n * include key words used in later checks.\n */\n browser: function(user_agent, vendor, opera) {\n vendor = vendor || ''; // vendor is undefined for at least IE9\n if (opera || _.includes(user_agent, ' OPR/')) {\n if (_.includes(user_agent, 'Mini')) {\n return 'Opera Mini';\n }\n return 'Opera';\n } else if (/(BlackBerry|PlayBook|BB10)/i.test(user_agent)) {\n return 'BlackBerry';\n } else if (_.includes(user_agent, 'IEMobile') || _.includes(user_agent, 'WPDesktop')) {\n return 'Internet Explorer Mobile';\n } else if (_.includes(user_agent, 'SamsungBrowser/')) {\n // https://developer.samsung.com/internet/user-agent-string-format\n return 'Samsung Internet';\n } else if (_.includes(user_agent, 'Edge') || _.includes(user_agent, 'Edg/')) {\n return 'Microsoft Edge';\n } else if (_.includes(user_agent, 'FBIOS')) {\n return 'Facebook Mobile';\n } else if (_.includes(user_agent, 'Chrome')) {\n return 'Chrome';\n } else if (_.includes(user_agent, 'CriOS')) {\n return 'Chrome iOS';\n } else if (_.includes(user_agent, 'UCWEB') || _.includes(user_agent, 'UCBrowser')) {\n return 'UC Browser';\n } else if (_.includes(user_agent, 'FxiOS')) {\n return 'Firefox iOS';\n } else if (_.includes(vendor, 'Apple')) {\n if (_.includes(user_agent, 'Mobile')) {\n return 'Mobile Safari';\n }\n return 'Safari';\n } else if (_.includes(user_agent, 'Android')) {\n return 'Android Mobile';\n } else if (_.includes(user_agent, 'Konqueror')) {\n return 'Konqueror';\n } else if (_.includes(user_agent, 'Firefox')) {\n return 'Firefox';\n } else if (_.includes(user_agent, 'MSIE') || _.includes(user_agent, 'Trident/')) {\n return 'Internet Explorer';\n } else if (_.includes(user_agent, 'Gecko')) {\n return 'Mozilla';\n } else {\n return '';\n }\n },\n\n /**\n * This function detects which browser version is running this script,\n * parsing major and minor version (e.g., 42.1). User agent strings from:\n * http://www.useragentstring.com/pages/useragentstring.php\n */\n browserVersion: function(userAgent, vendor, opera) {\n var browser = _.info.browser(userAgent, vendor, opera);\n var versionRegexs = {\n 'Internet Explorer Mobile': /rv:(\\d+(\\.\\d+)?)/,\n 'Microsoft Edge': /Edge?\\/(\\d+(\\.\\d+)?)/,\n 'Chrome': /Chrome\\/(\\d+(\\.\\d+)?)/,\n 'Chrome iOS': /CriOS\\/(\\d+(\\.\\d+)?)/,\n 'UC Browser' : /(UCBrowser|UCWEB)\\/(\\d+(\\.\\d+)?)/,\n 'Safari': /Version\\/(\\d+(\\.\\d+)?)/,\n 'Mobile Safari': /Version\\/(\\d+(\\.\\d+)?)/,\n 'Opera': /(Opera|OPR)\\/(\\d+(\\.\\d+)?)/,\n 'Firefox': /Firefox\\/(\\d+(\\.\\d+)?)/,\n 'Firefox iOS': /FxiOS\\/(\\d+(\\.\\d+)?)/,\n 'Konqueror': /Konqueror:(\\d+(\\.\\d+)?)/,\n 'BlackBerry': /BlackBerry (\\d+(\\.\\d+)?)/,\n 'Android Mobile': /android\\s(\\d+(\\.\\d+)?)/,\n 'Samsung Internet': /SamsungBrowser\\/(\\d+(\\.\\d+)?)/,\n 'Internet Explorer': /(rv:|MSIE )(\\d+(\\.\\d+)?)/,\n 'Mozilla': /rv:(\\d+(\\.\\d+)?)/\n };\n var regex = versionRegexs[browser];\n if (regex === undefined) {\n return null;\n }\n var matches = userAgent.match(regex);\n if (!matches) {\n return null;\n }\n return parseFloat(matches[matches.length - 2]);\n },\n\n os: function() {\n var a = userAgent;\n if (/Windows/i.test(a)) {\n if (/Phone/.test(a) || /WPDesktop/.test(a)) {\n return 'Windows Phone';\n }\n return 'Windows';\n } else if (/(iPhone|iPad|iPod)/.test(a)) {\n return 'iOS';\n } else if (/Android/.test(a)) {\n return 'Android';\n } else if (/(BlackBerry|PlayBook|BB10)/i.test(a)) {\n return 'BlackBerry';\n } else if (/Mac/i.test(a)) {\n return 'Mac OS X';\n } else if (/Linux/.test(a)) {\n return 'Linux';\n } else if (/CrOS/.test(a)) {\n return 'Chrome OS';\n } else {\n return '';\n }\n },\n\n device: function(user_agent) {\n if (/Windows Phone/i.test(user_agent) || /WPDesktop/.test(user_agent)) {\n return 'Windows Phone';\n } else if (/iPad/.test(user_agent)) {\n return 'iPad';\n } else if (/iPod/.test(user_agent)) {\n return 'iPod Touch';\n } else if (/iPhone/.test(user_agent)) {\n return 'iPhone';\n } else if (/(BlackBerry|PlayBook|BB10)/i.test(user_agent)) {\n return 'BlackBerry';\n } else if (/Android/.test(user_agent)) {\n return 'Android';\n } else {\n return '';\n }\n },\n\n referringDomain: function(referrer) {\n var split = referrer.split('/');\n if (split.length >= 3) {\n return split[2];\n }\n return '';\n },\n\n currentUrl: function() {\n return win.location.href;\n },\n\n properties: function(extra_props) {\n if (typeof extra_props !== 'object') {\n extra_props = {};\n }\n return _.extend(_.strip_empty_properties({\n '$os': _.info.os(),\n '$browser': _.info.browser(userAgent, navigator.vendor, windowOpera),\n '$referrer': document$1.referrer,\n '$referring_domain': _.info.referringDomain(document$1.referrer),\n '$device': _.info.device(userAgent)\n }), {\n '$current_url': _.info.currentUrl(),\n '$browser_version': _.info.browserVersion(userAgent, navigator.vendor, windowOpera),\n '$screen_height': screen.height,\n '$screen_width': screen.width,\n 'mp_lib': 'web',\n '$lib_version': Config.LIB_VERSION,\n '$insert_id': cheap_guid(),\n 'time': _.timestamp() / 1000 // epoch time in seconds\n }, _.strip_empty_properties(extra_props));\n },\n\n people_properties: function() {\n return _.extend(_.strip_empty_properties({\n '$os': _.info.os(),\n '$browser': _.info.browser(userAgent, navigator.vendor, windowOpera)\n }), {\n '$browser_version': _.info.browserVersion(userAgent, navigator.vendor, windowOpera)\n });\n },\n\n mpPageViewProperties: function() {\n return _.strip_empty_properties({\n 'current_page_title': document$1.title,\n 'current_domain': win.location.hostname,\n 'current_url_path': win.location.pathname,\n 'current_url_protocol': win.location.protocol,\n 'current_url_search': win.location.search\n });\n }\n};\n\nvar cheap_guid = function(maxlen) {\n var guid = Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10);\n return maxlen ? guid.substring(0, maxlen) : guid;\n};\n\n// naive way to extract domain name (example.com) from full hostname (my.sub.example.com)\nvar SIMPLE_DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]*\\.[a-z]+$/i;\n// this next one attempts to account for some ccSLDs, e.g. extracting oxford.ac.uk from www.oxford.ac.uk\nvar DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]+\\.[a-z.]{2,6}$/i;\n/**\n * Attempts to extract main domain name from full hostname, using a few blunt heuristics. For\n * common TLDs like .com/.org that always have a simple SLD.TLD structure (example.com), we\n * simply extract the last two .-separated parts of the hostname (SIMPLE_DOMAIN_MATCH_REGEX).\n * For others, we attempt to account for short ccSLD+TLD combos (.ac.uk) with the legacy\n * DOMAIN_MATCH_REGEX (kept to maintain backwards compatibility with existing Mixpanel\n * integrations). The only _reliable_ way to extract domain from hostname is with an up-to-date\n * list like at https://publicsuffix.org/ so for cases that this helper fails at, the SDK\n * offers the 'cookie_domain' config option to set it explicitly.\n * @example\n * extract_domain('my.sub.example.com')\n * // 'example.com'\n */\nvar extract_domain = function(hostname) {\n var domain_regex = DOMAIN_MATCH_REGEX;\n var parts = hostname.split('.');\n var tld = parts[parts.length - 1];\n if (tld.length > 4 || tld === 'com' || tld === 'org') {\n domain_regex = SIMPLE_DOMAIN_MATCH_REGEX;\n }\n var matches = hostname.match(domain_regex);\n return matches ? matches[0] : '';\n};\n\n/**\n * Check whether we have network connection. default to true for browsers that don't support navigator.onLine (IE)\n * @returns {boolean}\n */\nvar isOnline = function() {\n var onLine = win.navigator['onLine'];\n return _.isUndefined(onLine) || onLine;\n};\n\nvar JSONStringify = null, JSONParse = null;\nif (typeof JSON !== 'undefined') {\n JSONStringify = JSON.stringify;\n JSONParse = JSON.parse;\n}\nJSONStringify = JSONStringify || _.JSONEncode;\nJSONParse = JSONParse || _.JSONDecode;\n\n// EXPORTS (for closure compiler)\n_['toArray'] = _.toArray;\n_['isObject'] = _.isObject;\n_['JSONEncode'] = _.JSONEncode;\n_['JSONDecode'] = _.JSONDecode;\n_['isBlockedUA'] = _.isBlockedUA;\n_['isEmptyObject'] = _.isEmptyObject;\n_['info'] = _.info;\n_['info']['device'] = _.info.device;\n_['info']['browser'] = _.info.browser;\n_['info']['browserVersion'] = _.info.browserVersion;\n_['info']['properties'] = _.info.properties;\n\n/**\n * GDPR utils\n *\n * The General Data Protection Regulation (GDPR) is a regulation in EU law on data protection\n * and privacy for all individuals within the European Union. It addresses the export of personal\n * data outside the EU. The GDPR aims primarily to give control back to citizens and residents\n * over their personal data and to simplify the regulatory environment for international business\n * by unifying the regulation within the EU.\n *\n * This set of utilities is intended to enable opt in/out functionality in the Mixpanel JS SDK.\n * These functions are used internally by the SDK and are not intended to be publicly exposed.\n */\n\n/**\n * A function used to track a Mixpanel event (e.g. MixpanelLib.track)\n * @callback trackFunction\n * @param {String} event_name The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', 'Item Purchased', etc.\n * @param {Object} [properties] A set of properties to include with the event you're sending. These describe the user who did the event or details about the event itself.\n * @param {Function} [callback] If provided, the callback function will be called after tracking the event.\n */\n\n/** Public **/\n\nvar GDPR_DEFAULT_PERSISTENCE_PREFIX = '__mp_opt_in_out_';\n\n/**\n * Opt the user in to data tracking and cookies/localstorage for the given token\n * @param {string} token - Mixpanel project tracking token\n * @param {Object} [options]\n * @param {trackFunction} [options.track] - function used for tracking a Mixpanel event to record the opt-in action\n * @param {string} [options.trackEventName] - event name to be used for tracking the opt-in action\n * @param {Object} [options.trackProperties] - set of properties to be tracked along with the opt-in action\n * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage\n * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires\n * @param {string} [options.cookieDomain] - custom cookie domain\n * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled\n * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not\n * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not\n */\nfunction optIn(token, options) {\n _optInOut(true, token, options);\n}\n\n/**\n * Opt the user out of data tracking and cookies/localstorage for the given token\n * @param {string} token - Mixpanel project tracking token\n * @param {Object} [options]\n * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage\n * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @param {Number} [options.cookieExpiration] - number of days until the opt-out cookie expires\n * @param {string} [options.cookieDomain] - custom cookie domain\n * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled\n * @param {boolean} [options.crossSubdomainCookie] - whether the opt-out cookie is set as cross-subdomain or not\n * @param {boolean} [options.secureCookie] - whether the opt-out cookie is set as secure or not\n */\nfunction optOut(token, options) {\n _optInOut(false, token, options);\n}\n\n/**\n * Check whether the user has opted in to data tracking and cookies/localstorage for the given token\n * @param {string} token - Mixpanel project tracking token\n * @param {Object} [options]\n * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage\n * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @returns {boolean} whether the user has opted in to the given opt type\n */\nfunction hasOptedIn(token, options) {\n return _getStorageValue(token, options) === '1';\n}\n\n/**\n * Check whether the user has opted out of data tracking and cookies/localstorage for the given token\n * @param {string} token - Mixpanel project tracking token\n * @param {Object} [options]\n * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage\n * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @param {boolean} [options.ignoreDnt] - flag to ignore browser DNT settings and always return false\n * @returns {boolean} whether the user has opted out of the given opt type\n */\nfunction hasOptedOut(token, options) {\n if (_hasDoNotTrackFlagOn(options)) {\n console$1.warn('This browser has \"Do Not Track\" enabled. This will prevent the Mixpanel SDK from sending any data. To ignore the \"Do Not Track\" browser setting, initialize the Mixpanel instance with the config \"ignore_dnt: true\"');\n return true;\n }\n var optedOut = _getStorageValue(token, options) === '0';\n if (optedOut) {\n console$1.warn('You are opted out of Mixpanel tracking. This will prevent the Mixpanel SDK from sending any data.');\n }\n return optedOut;\n}\n\n/**\n * Wrap a MixpanelLib method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token\n * If the user has opted out, return early instead of executing the method.\n * If a callback argument was provided, execute it passing the 0 error code.\n * @param {function} method - wrapped method to be executed if the user has not opted out\n * @returns {*} the result of executing method OR undefined if the user has opted out\n */\nfunction addOptOutCheckMixpanelLib(method) {\n return _addOptOutCheck(method, function(name) {\n return this.get_config(name);\n });\n}\n\n/**\n * Wrap a MixpanelPeople method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token\n * If the user has opted out, return early instead of executing the method.\n * If a callback argument was provided, execute it passing the 0 error code.\n * @param {function} method - wrapped method to be executed if the user has not opted out\n * @returns {*} the result of executing method OR undefined if the user has opted out\n */\nfunction addOptOutCheckMixpanelPeople(method) {\n return _addOptOutCheck(method, function(name) {\n return this._get_config(name);\n });\n}\n\n/**\n * Wrap a MixpanelGroup method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token\n * If the user has opted out, return early instead of executing the method.\n * If a callback argument was provided, execute it passing the 0 error code.\n * @param {function} method - wrapped method to be executed if the user has not opted out\n * @returns {*} the result of executing method OR undefined if the user has opted out\n */\nfunction addOptOutCheckMixpanelGroup(method) {\n return _addOptOutCheck(method, function(name) {\n return this._get_config(name);\n });\n}\n\n/**\n * Clear the user's opt in/out status of data tracking and cookies/localstorage for the given token\n * @param {string} token - Mixpanel project tracking token\n * @param {Object} [options]\n * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage\n * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires\n * @param {string} [options.cookieDomain] - custom cookie domain\n * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled\n * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not\n * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not\n */\nfunction clearOptInOut(token, options) {\n options = options || {};\n _getStorage(options).remove(\n _getStorageKey(token, options), !!options.crossSubdomainCookie, options.cookieDomain\n );\n}\n\n/** Private **/\n\n/**\n * Get storage util\n * @param {Object} [options]\n * @param {string} [options.persistenceType]\n * @returns {object} either _.cookie or _.localstorage\n */\nfunction _getStorage(options) {\n options = options || {};\n return options.persistenceType === 'localStorage' ? _.localStorage : _.cookie;\n}\n\n/**\n * Get the name of the cookie that is used for the given opt type (tracking, cookie, etc.)\n * @param {string} token - Mixpanel project tracking token\n * @param {Object} [options]\n * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @returns {string} the name of the cookie for the given opt type\n */\nfunction _getStorageKey(token, options) {\n options = options || {};\n return (options.persistencePrefix || GDPR_DEFAULT_PERSISTENCE_PREFIX) + token;\n}\n\n/**\n * Get the value of the cookie that is used for the given opt type (tracking, cookie, etc.)\n * @param {string} token - Mixpanel project tracking token\n * @param {Object} [options]\n * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @returns {string} the value of the cookie for the given opt type\n */\nfunction _getStorageValue(token, options) {\n return _getStorage(options).get(_getStorageKey(token, options));\n}\n\n/**\n * Check whether the user has set the DNT/doNotTrack setting to true in their browser\n * @param {Object} [options]\n * @param {string} [options.window] - alternate window object to check; used to force various DNT settings in browser tests\n * @param {boolean} [options.ignoreDnt] - flag to ignore browser DNT settings and always return false\n * @returns {boolean} whether the DNT setting is true\n */\nfunction _hasDoNotTrackFlagOn(options) {\n if (options && options.ignoreDnt) {\n return false;\n }\n var win$1 = (options && options.window) || win;\n var nav = win$1['navigator'] || {};\n var hasDntOn = false;\n\n _.each([\n nav['doNotTrack'], // standard\n nav['msDoNotTrack'],\n win$1['doNotTrack']\n ], function(dntValue) {\n if (_.includes([true, 1, '1', 'yes'], dntValue)) {\n hasDntOn = true;\n }\n });\n\n return hasDntOn;\n}\n\n/**\n * Set cookie/localstorage for the user indicating that they are opted in or out for the given opt type\n * @param {boolean} optValue - whether to opt the user in or out for the given opt type\n * @param {string} token - Mixpanel project tracking token\n * @param {Object} [options]\n * @param {trackFunction} [options.track] - function used for tracking a Mixpanel event to record the opt-in action\n * @param {string} [options.trackEventName] - event name to be used for tracking the opt-in action\n * @param {Object} [options.trackProperties] - set of properties to be tracked along with the opt-in action\n * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires\n * @param {string} [options.cookieDomain] - custom cookie domain\n * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled\n * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not\n * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not\n */\nfunction _optInOut(optValue, token, options) {\n if (!_.isString(token) || !token.length) {\n console$1.error('gdpr.' + (optValue ? 'optIn' : 'optOut') + ' called with an invalid token');\n return;\n }\n\n options = options || {};\n\n _getStorage(options).set(\n _getStorageKey(token, options),\n optValue ? 1 : 0,\n _.isNumber(options.cookieExpiration) ? options.cookieExpiration : null,\n !!options.crossSubdomainCookie,\n !!options.secureCookie,\n !!options.crossSiteCookie,\n options.cookieDomain\n );\n\n if (options.track && optValue) { // only track event if opting in (optValue=true)\n options.track(options.trackEventName || '$opt_in', options.trackProperties, {\n 'send_immediately': true\n });\n }\n}\n\n/**\n * Wrap a method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token\n * If the user has opted out, return early instead of executing the method.\n * If a callback argument was provided, execute it passing the 0 error code.\n * @param {function} method - wrapped method to be executed if the user has not opted out\n * @param {function} getConfigValue - getter function for the Mixpanel API token and other options to be used with opt-out check\n * @returns {*} the result of executing method OR undefined if the user has opted out\n */\nfunction _addOptOutCheck(method, getConfigValue) {\n return function() {\n var optedOut = false;\n\n try {\n var token = getConfigValue.call(this, 'token');\n var ignoreDnt = getConfigValue.call(this, 'ignore_dnt');\n var persistenceType = getConfigValue.call(this, 'opt_out_tracking_persistence_type');\n var persistencePrefix = getConfigValue.call(this, 'opt_out_tracking_cookie_prefix');\n var win = getConfigValue.call(this, 'window'); // used to override window during browser tests\n\n if (token) { // if there was an issue getting the token, continue method execution as normal\n optedOut = hasOptedOut(token, {\n ignoreDnt: ignoreDnt,\n persistenceType: persistenceType,\n persistencePrefix: persistencePrefix,\n window: win\n });\n }\n } catch(err) {\n console$1.error('Unexpected error when checking tracking opt-out status: ' + err);\n }\n\n if (!optedOut) {\n return method.apply(this, arguments);\n }\n\n var callback = arguments[arguments.length - 1];\n if (typeof(callback) === 'function') {\n callback(0);\n }\n\n return;\n };\n}\n\nvar logger$4 = console_with_prefix('lock');\n\n/**\n * SharedLock: a mutex built on HTML5 localStorage, to ensure that only one browser\n * window/tab at a time will be able to access shared resources.\n *\n * Based on the Alur and Taubenfeld fast lock\n * (http://www.cs.rochester.edu/research/synchronization/pseudocode/fastlock.html)\n * with an added timeout to ensure there will be eventual progress in the event\n * that a window is closed in the middle of the callback.\n *\n * Implementation based on the original version by David Wolever (https://github.com/wolever)\n * at https://gist.github.com/wolever/5fd7573d1ef6166e8f8c4af286a69432.\n *\n * @example\n * const myLock = new SharedLock('some-key');\n * myLock.withLock(function() {\n * console.log('I hold the mutex!');\n * });\n *\n * @constructor\n */\nvar SharedLock = function(key, options) {\n options = options || {};\n\n this.storageKey = key;\n this.storage = options.storage || window.localStorage;\n this.pollIntervalMS = options.pollIntervalMS || 100;\n this.timeoutMS = options.timeoutMS || 2000;\n};\n\n// pass in a specific pid to test contention scenarios; otherwise\n// it is chosen randomly for each acquisition attempt\nSharedLock.prototype.withLock = function(lockedCB, errorCB, pid) {\n if (!pid && typeof errorCB !== 'function') {\n pid = errorCB;\n errorCB = null;\n }\n\n var i = pid || (new Date().getTime() + '|' + Math.random());\n var startTime = new Date().getTime();\n\n var key = this.storageKey;\n var pollIntervalMS = this.pollIntervalMS;\n var timeoutMS = this.timeoutMS;\n var storage = this.storage;\n\n var keyX = key + ':X';\n var keyY = key + ':Y';\n var keyZ = key + ':Z';\n\n var reportError = function(err) {\n errorCB && errorCB(err);\n };\n\n var delay = function(cb) {\n if (new Date().getTime() - startTime > timeoutMS) {\n logger$4.error('Timeout waiting for mutex on ' + key + '; clearing lock. [' + i + ']');\n storage.removeItem(keyZ);\n storage.removeItem(keyY);\n loop();\n return;\n }\n setTimeout(function() {\n try {\n cb();\n } catch(err) {\n reportError(err);\n }\n }, pollIntervalMS * (Math.random() + 0.1));\n };\n\n var waitFor = function(predicate, cb) {\n if (predicate()) {\n cb();\n } else {\n delay(function() {\n waitFor(predicate, cb);\n });\n }\n };\n\n var getSetY = function() {\n var valY = storage.getItem(keyY);\n if (valY && valY !== i) { // if Y == i then this process already has the lock (useful for test cases)\n return false;\n } else {\n storage.setItem(keyY, i);\n if (storage.getItem(keyY) === i) {\n return true;\n } else {\n if (!localStorageSupported(storage, true)) {\n throw new Error('localStorage support dropped while acquiring lock');\n }\n return false;\n }\n }\n };\n\n var loop = function() {\n storage.setItem(keyX, i);\n\n waitFor(getSetY, function() {\n if (storage.getItem(keyX) === i) {\n criticalSection();\n return;\n }\n\n delay(function() {\n if (storage.getItem(keyY) !== i) {\n loop();\n return;\n }\n waitFor(function() {\n return !storage.getItem(keyZ);\n }, criticalSection);\n });\n });\n };\n\n var criticalSection = function() {\n storage.setItem(keyZ, '1');\n try {\n lockedCB();\n } finally {\n storage.removeItem(keyZ);\n if (storage.getItem(keyY) === i) {\n storage.removeItem(keyY);\n }\n if (storage.getItem(keyX) === i) {\n storage.removeItem(keyX);\n }\n }\n };\n\n try {\n if (localStorageSupported(storage, true)) {\n loop();\n } else {\n throw new Error('localStorage support check failed');\n }\n } catch(err) {\n reportError(err);\n }\n};\n\nvar logger$3 = console_with_prefix('batch');\n\n/**\n * RequestQueue: queue for batching API requests with localStorage backup for retries.\n * Maintains an in-memory queue which represents the source of truth for the current\n * page, but also writes all items out to a copy in the browser's localStorage, which\n * can be read on subsequent pageloads and retried. For batchability, all the request\n * items in the queue should be of the same type (events, people updates, group updates)\n * so they can be sent in a single request to the same API endpoint.\n *\n * LocalStorage keying and locking: In order for reloads and subsequent pageloads of\n * the same site to access the same persisted data, they must share the same localStorage\n * key (for instance based on project token and queue type). Therefore access to the\n * localStorage entry is guarded by an asynchronous mutex (SharedLock) to prevent\n * simultaneously open windows/tabs from overwriting each other's data (which would lead\n * to data loss in some situations).\n * @constructor\n */\nvar RequestQueue = function(storageKey, options) {\n options = options || {};\n this.storageKey = storageKey;\n this.usePersistence = options.usePersistence;\n if (this.usePersistence) {\n this.storage = options.storage || window.localStorage;\n this.lock = new SharedLock(storageKey, {storage: this.storage});\n }\n this.reportError = options.errorReporter || _.bind(logger$3.error, logger$3);\n\n this.pid = options.pid || null; // pass pid to test out storage lock contention scenarios\n\n this.memQueue = [];\n};\n\n/**\n * Add one item to queues (memory and localStorage). The queued entry includes\n * the given item along with an auto-generated ID and a \"flush-after\" timestamp.\n * It is expected that the item will be sent over the network and dequeued\n * before the flush-after time; if this doesn't happen it is considered orphaned\n * (e.g., the original tab where it was enqueued got closed before it could be\n * sent) and the item can be sent by any tab that finds it in localStorage.\n *\n * The final callback param is called with a param indicating success or\n * failure of the enqueue operation; it is asynchronous because the localStorage\n * lock is asynchronous.\n */\nRequestQueue.prototype.enqueue = function(item, flushInterval, cb) {\n var queueEntry = {\n 'id': cheap_guid(),\n 'flushAfter': new Date().getTime() + flushInterval * 2,\n 'payload': item\n };\n\n if (!this.usePersistence) {\n this.memQueue.push(queueEntry);\n if (cb) {\n cb(true);\n }\n } else {\n this.lock.withLock(_.bind(function lockAcquired() {\n var succeeded;\n try {\n var storedQueue = this.readFromStorage();\n storedQueue.push(queueEntry);\n succeeded = this.saveToStorage(storedQueue);\n if (succeeded) {\n // only add to in-memory queue when storage succeeds\n this.memQueue.push(queueEntry);\n }\n } catch(err) {\n this.reportError('Error enqueueing item', item);\n succeeded = false;\n }\n if (cb) {\n cb(succeeded);\n }\n }, this), _.bind(function lockFailure(err) {\n this.reportError('Error acquiring storage lock', err);\n if (cb) {\n cb(false);\n }\n }, this), this.pid);\n }\n};\n\n/**\n * Read out the given number of queue entries. If this.memQueue\n * has fewer than batchSize items, then look for \"orphaned\" items\n * in the persisted queue (items where the 'flushAfter' time has\n * already passed).\n */\nRequestQueue.prototype.fillBatch = function(batchSize) {\n var batch = this.memQueue.slice(0, batchSize);\n if (this.usePersistence && batch.length < batchSize) {\n // don't need lock just to read events; localStorage is thread-safe\n // and the worst that could happen is a duplicate send of some\n // orphaned events, which will be deduplicated on the server side\n var storedQueue = this.readFromStorage();\n if (storedQueue.length) {\n // item IDs already in batch; don't duplicate out of storage\n var idsInBatch = {}; // poor man's Set\n _.each(batch, function(item) { idsInBatch[item['id']] = true; });\n\n for (var i = 0; i < storedQueue.length; i++) {\n var item = storedQueue[i];\n if (new Date().getTime() > item['flushAfter'] && !idsInBatch[item['id']]) {\n item.orphaned = true;\n batch.push(item);\n if (batch.length >= batchSize) {\n break;\n }\n }\n }\n }\n }\n return batch;\n};\n\n/**\n * Remove items with matching 'id' from array (immutably)\n * also remove any item without a valid id (e.g., malformed\n * storage entries).\n */\nvar filterOutIDsAndInvalid = function(items, idSet) {\n var filteredItems = [];\n _.each(items, function(item) {\n if (item['id'] && !idSet[item['id']]) {\n filteredItems.push(item);\n }\n });\n return filteredItems;\n};\n\n/**\n * Remove items with matching IDs from both in-memory queue\n * and persisted queue\n */\nRequestQueue.prototype.removeItemsByID = function(ids, cb) {\n var idSet = {}; // poor man's Set\n _.each(ids, function(id) { idSet[id] = true; });\n\n this.memQueue = filterOutIDsAndInvalid(this.memQueue, idSet);\n if (!this.usePersistence) {\n if (cb) {\n cb(true);\n }\n } else {\n var removeFromStorage = _.bind(function() {\n var succeeded;\n try {\n var storedQueue = this.readFromStorage();\n storedQueue = filterOutIDsAndInvalid(storedQueue, idSet);\n succeeded = this.saveToStorage(storedQueue);\n\n // an extra check: did storage report success but somehow\n // the items are still there?\n if (succeeded) {\n storedQueue = this.readFromStorage();\n for (var i = 0; i < storedQueue.length; i++) {\n var item = storedQueue[i];\n if (item['id'] && !!idSet[item['id']]) {\n this.reportError('Item not removed from storage');\n return false;\n }\n }\n }\n } catch(err) {\n this.reportError('Error removing items', ids);\n succeeded = false;\n }\n return succeeded;\n }, this);\n\n this.lock.withLock(function lockAcquired() {\n var succeeded = removeFromStorage();\n if (cb) {\n cb(succeeded);\n }\n }, _.bind(function lockFailure(err) {\n var succeeded = false;\n this.reportError('Error acquiring storage lock', err);\n if (!localStorageSupported(this.storage, true)) {\n // Looks like localStorage writes have stopped working sometime after\n // initialization (probably full), and so nobody can acquire locks\n // anymore. Consider it temporarily safe to remove items without the\n // lock, since nobody's writing successfully anyway.\n succeeded = removeFromStorage();\n if (!succeeded) {\n // OK, we couldn't even write out the smaller queue. Try clearing it\n // entirely.\n try {\n this.storage.removeItem(this.storageKey);\n } catch(err) {\n this.reportError('Error clearing queue', err);\n }\n }\n }\n if (cb) {\n cb(succeeded);\n }\n }, this), this.pid);\n }\n\n};\n\n// internal helper for RequestQueue.updatePayloads\nvar updatePayloads = function(existingItems, itemsToUpdate) {\n var newItems = [];\n _.each(existingItems, function(item) {\n var id = item['id'];\n if (id in itemsToUpdate) {\n var newPayload = itemsToUpdate[id];\n if (newPayload !== null) {\n item['payload'] = newPayload;\n newItems.push(item);\n }\n } else {\n // no update\n newItems.push(item);\n }\n });\n return newItems;\n};\n\n/**\n * Update payloads of given items in both in-memory queue and\n * persisted queue. Items set to null are removed from queues.\n */\nRequestQueue.prototype.updatePayloads = function(itemsToUpdate, cb) {\n this.memQueue = updatePayloads(this.memQueue, itemsToUpdate);\n if (!this.usePersistence) {\n if (cb) {\n cb(true);\n }\n } else {\n this.lock.withLock(_.bind(function lockAcquired() {\n var succeeded;\n try {\n var storedQueue = this.readFromStorage();\n storedQueue = updatePayloads(storedQueue, itemsToUpdate);\n succeeded = this.saveToStorage(storedQueue);\n } catch(err) {\n this.reportError('Error updating items', itemsToUpdate);\n succeeded = false;\n }\n if (cb) {\n cb(succeeded);\n }\n }, this), _.bind(function lockFailure(err) {\n this.reportError('Error acquiring storage lock', err);\n if (cb) {\n cb(false);\n }\n }, this), this.pid);\n }\n\n};\n\n/**\n * Read and parse items array from localStorage entry, handling\n * malformed/missing data if necessary.\n */\nRequestQueue.prototype.readFromStorage = function() {\n var storageEntry;\n try {\n storageEntry = this.storage.getItem(this.storageKey);\n if (storageEntry) {\n storageEntry = JSONParse(storageEntry);\n if (!_.isArray(storageEntry)) {\n this.reportError('Invalid storage entry:', storageEntry);\n storageEntry = null;\n }\n }\n } catch (err) {\n this.reportError('Error retrieving queue', err);\n storageEntry = null;\n }\n return storageEntry || [];\n};\n\n/**\n * Serialize the given items array to localStorage.\n */\nRequestQueue.prototype.saveToStorage = function(queue) {\n try {\n this.storage.setItem(this.storageKey, JSONStringify(queue));\n return true;\n } catch (err) {\n this.reportError('Error saving queue', err);\n return false;\n }\n};\n\n/**\n * Clear out queues (memory and localStorage).\n */\nRequestQueue.prototype.clear = function() {\n this.memQueue = [];\n\n if (this.usePersistence) {\n this.storage.removeItem(this.storageKey);\n }\n};\n\n// maximum interval between request retries after exponential backoff\nvar MAX_RETRY_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes\n\nvar logger$2 = console_with_prefix('batch');\n\n/**\n * RequestBatcher: manages the queueing, flushing, retry etc of requests of one\n * type (events, people, groups).\n * Uses RequestQueue to manage the backing store.\n * @constructor\n */\nvar RequestBatcher = function(storageKey, options) {\n this.errorReporter = options.errorReporter;\n this.queue = new RequestQueue(storageKey, {\n errorReporter: _.bind(this.reportError, this),\n storage: options.storage,\n usePersistence: options.usePersistence\n });\n\n this.libConfig = options.libConfig;\n this.sendRequest = options.sendRequestFunc;\n this.beforeSendHook = options.beforeSendHook;\n this.stopAllBatching = options.stopAllBatchingFunc;\n\n // seed variable batch size + flush interval with configured values\n this.batchSize = this.libConfig['batch_size'];\n this.flushInterval = this.libConfig['batch_flush_interval_ms'];\n\n this.stopped = !this.libConfig['batch_autostart'];\n this.consecutiveRemovalFailures = 0;\n\n // extra client-side dedupe\n this.itemIdsSentSuccessfully = {};\n\n // Make the flush occur at the interval specified by flushIntervalMs, default behavior will attempt consecutive flushes\n // as long as the queue is not empty. This is useful for high-frequency events like Session Replay where we might end up\n // in a request loop and get ratelimited by the server.\n this.flushOnlyOnInterval = options.flushOnlyOnInterval || false;\n};\n\n/**\n * Add one item to queue.\n */\nRequestBatcher.prototype.enqueue = function(item, cb) {\n this.queue.enqueue(item, this.flushInterval, cb);\n};\n\n/**\n * Start flushing batches at the configured time interval. Must call\n * this method upon SDK init in order to send anything over the network.\n */\nRequestBatcher.prototype.start = function() {\n this.stopped = false;\n this.consecutiveRemovalFailures = 0;\n this.flush();\n};\n\n/**\n * Stop flushing batches. Can be restarted by calling start().\n */\nRequestBatcher.prototype.stop = function() {\n this.stopped = true;\n if (this.timeoutID) {\n clearTimeout(this.timeoutID);\n this.timeoutID = null;\n }\n};\n\n/**\n * Clear out queue.\n */\nRequestBatcher.prototype.clear = function() {\n this.queue.clear();\n};\n\n/**\n * Restore batch size configuration to whatever is set in the main SDK.\n */\nRequestBatcher.prototype.resetBatchSize = function() {\n this.batchSize = this.libConfig['batch_size'];\n};\n\n/**\n * Restore flush interval time configuration to whatever is set in the main SDK.\n */\nRequestBatcher.prototype.resetFlush = function() {\n this.scheduleFlush(this.libConfig['batch_flush_interval_ms']);\n};\n\n/**\n * Schedule the next flush in the given number of milliseconds.\n */\nRequestBatcher.prototype.scheduleFlush = function(flushMS) {\n this.flushInterval = flushMS;\n if (!this.stopped) { // don't schedule anymore if batching has been stopped\n this.timeoutID = setTimeout(_.bind(function() {\n if (!this.stopped) {\n this.flush();\n }\n }, this), this.flushInterval);\n }\n};\n\n/**\n * Flush one batch to network. Depending on success/failure modes, it will either\n * remove the batch from the queue or leave it in for retry, and schedule the next\n * flush. In cases of most network or API failures, it will back off exponentially\n * when retrying.\n * @param {Object} [options]\n * @param {boolean} [options.sendBeacon] - whether to send batch with\n * navigator.sendBeacon (only useful for sending batches before page unloads, as\n * sendBeacon offers no callbacks or status indications)\n */\nRequestBatcher.prototype.flush = function(options) {\n try {\n\n if (this.requestInProgress) {\n logger$2.log('Flush: Request already in progress');\n return;\n }\n\n options = options || {};\n var timeoutMS = this.libConfig['batch_request_timeout_ms'];\n var startTime = new Date().getTime();\n var currentBatchSize = this.batchSize;\n var batch = this.queue.fillBatch(currentBatchSize);\n // if there's more items in the queue than the batch size, attempt\n // to flush again after the current batch is done.\n var attemptSecondaryFlush = batch.length === currentBatchSize;\n var dataForRequest = [];\n var transformedItems = {};\n _.each(batch, function(item) {\n var payload = item['payload'];\n if (this.beforeSendHook && !item.orphaned) {\n payload = this.beforeSendHook(payload);\n }\n if (payload) {\n // mp_sent_by_lib_version prop captures which lib version actually\n // sends each event (regardless of which version originally queued\n // it for sending)\n if (payload['event'] && payload['properties']) {\n payload['properties'] = _.extend(\n {},\n payload['properties'],\n {'mp_sent_by_lib_version': Config.LIB_VERSION}\n );\n }\n var addPayload = true;\n var itemId = item['id'];\n if (itemId) {\n if ((this.itemIdsSentSuccessfully[itemId] || 0) > 5) {\n this.reportError('[dupe] item ID sent too many times, not sending', {\n item: item,\n batchSize: batch.length,\n timesSent: this.itemIdsSentSuccessfully[itemId]\n });\n addPayload = false;\n }\n } else {\n this.reportError('[dupe] found item with no ID', {item: item});\n }\n\n if (addPayload) {\n dataForRequest.push(payload);\n }\n }\n transformedItems[item['id']] = payload;\n }, this);\n if (dataForRequest.length < 1) {\n this.resetFlush();\n return; // nothing to do\n }\n\n this.requestInProgress = true;\n\n var batchSendCallback = _.bind(function(res) {\n this.requestInProgress = false;\n\n try {\n\n // handle API response in a try-catch to make sure we can reset the\n // flush operation if something goes wrong\n\n var removeItemsFromQueue = false;\n if (options.unloading) {\n // update persisted data to include hook transformations\n this.queue.updatePayloads(transformedItems);\n } else if (\n _.isObject(res) &&\n res.error === 'timeout' &&\n new Date().getTime() - startTime >= timeoutMS\n ) {\n this.reportError('Network timeout; retrying');\n this.flush();\n } else if (\n _.isObject(res) &&\n (\n res.httpStatusCode >= 500\n || res.httpStatusCode === 429\n || (res.httpStatusCode <= 0 && !isOnline())\n || res.error === 'timeout'\n )\n ) {\n // network or API error, or 429 Too Many Requests, retry\n var retryMS = this.flushInterval * 2;\n if (res.retryAfter) {\n retryMS = (parseInt(res.retryAfter, 10) * 1000) || retryMS;\n }\n retryMS = Math.min(MAX_RETRY_INTERVAL_MS, retryMS);\n this.reportError('Error; retry in ' + retryMS + ' ms');\n this.scheduleFlush(retryMS);\n } else if (_.isObject(res) && res.httpStatusCode === 413) {\n // 413 Payload Too Large\n if (batch.length > 1) {\n var halvedBatchSize = Math.max(1, Math.floor(currentBatchSize / 2));\n this.batchSize = Math.min(this.batchSize, halvedBatchSize, batch.length - 1);\n this.reportError('413 response; reducing batch size to ' + this.batchSize);\n this.resetFlush();\n } else {\n this.reportError('Single-event request too large; dropping', batch);\n this.resetBatchSize();\n removeItemsFromQueue = true;\n }\n } else {\n // successful network request+response; remove each item in batch from queue\n // (even if it was e.g. a 400, in which case retrying won't help)\n removeItemsFromQueue = true;\n }\n\n if (removeItemsFromQueue) {\n this.queue.removeItemsByID(\n _.map(batch, function(item) { return item['id']; }),\n _.bind(function(succeeded) {\n if (succeeded) {\n this.consecutiveRemovalFailures = 0;\n if (this.flushOnlyOnInterval && !attemptSecondaryFlush) {\n this.resetFlush(); // schedule next batch with a delay\n } else {\n this.flush(); // handle next batch if the queue isn't empty\n }\n } else {\n this.reportError('Failed to remove items from queue');\n if (++this.consecutiveRemovalFailures > 5) {\n this.reportError('Too many queue failures; disabling batching system.');\n this.stopAllBatching();\n } else {\n this.resetFlush();\n }\n }\n }, this)\n );\n\n // client-side dedupe\n _.each(batch, _.bind(function(item) {\n var itemId = item['id'];\n if (itemId) {\n this.itemIdsSentSuccessfully[itemId] = this.itemIdsSentSuccessfully[itemId] || 0;\n this.itemIdsSentSuccessfully[itemId]++;\n if (this.itemIdsSentSuccessfully[itemId] > 5) {\n this.reportError('[dupe] item ID sent too many times', {\n item: item,\n batchSize: batch.length,\n timesSent: this.itemIdsSentSuccessfully[itemId]\n });\n }\n } else {\n this.reportError('[dupe] found item with no ID while removing', {item: item});\n }\n }, this));\n }\n\n } catch(err) {\n this.reportError('Error handling API response', err);\n this.resetFlush();\n }\n }, this);\n var requestOptions = {\n method: 'POST',\n verbose: true,\n ignore_json_errors: true, // eslint-disable-line camelcase\n timeout_ms: timeoutMS // eslint-disable-line camelcase\n };\n if (options.unloading) {\n requestOptions.transport = 'sendBeacon';\n }\n logger$2.log('MIXPANEL REQUEST:', dataForRequest);\n this.sendRequest(dataForRequest, requestOptions, batchSendCallback);\n } catch(err) {\n this.reportError('Error flushing request queue', err);\n this.resetFlush();\n }\n};\n\n/**\n * Log error to global logger and optional user-defined logger.\n */\nRequestBatcher.prototype.reportError = function(msg, err) {\n logger$2.error.apply(logger$2.error, arguments);\n if (this.errorReporter) {\n try {\n if (!(err instanceof Error)) {\n err = new Error(msg);\n }\n this.errorReporter(msg, err);\n } catch(err) {\n logger$2.error(err);\n }\n }\n};\n\nvar logger$1 = console_with_prefix('recorder');\nvar CompressionStream = win['CompressionStream'];\n\nvar RECORDER_BATCHER_LIB_CONFIG = {\n 'batch_size': 1000,\n 'batch_flush_interval_ms': 10 * 1000,\n 'batch_request_timeout_ms': 90 * 1000,\n 'batch_autostart': true\n};\n\nvar ACTIVE_SOURCES = new Set([\n IncrementalSource.MouseMove,\n IncrementalSource.MouseInteraction,\n IncrementalSource.Scroll,\n IncrementalSource.ViewportResize,\n IncrementalSource.Input,\n IncrementalSource.TouchMove,\n IncrementalSource.MediaInteraction,\n IncrementalSource.Drag,\n IncrementalSource.Selection,\n]);\n\nfunction isUserEvent(ev) {\n return ev.type === EventType.IncrementalSnapshot && ACTIVE_SOURCES.has(ev.data.source);\n}\n\n/**\n * This class encapsulates a single session recording and its lifecycle.\n * @param {Object} [options.mixpanelInstance] - reference to the core MixpanelLib\n * @param {String} [options.replayId] - unique uuid for a single replay\n * @param {Function} [options.onIdleTimeout] - callback when a recording reaches idle timeout\n * @param {Function} [options.onMaxLengthReached] - callback when a recording reaches its maximum length\n * @param {Function} [options.rrwebRecord] - rrweb's `record` function\n */\nvar SessionRecording = function(options) {\n this._mixpanel = options.mixpanelInstance;\n this._onIdleTimeout = options.onIdleTimeout;\n this._onMaxLengthReached = options.onMaxLengthReached;\n this._rrwebRecord = options.rrwebRecord;\n\n this.replayId = options.replayId;\n\n // internal rrweb stopRecording function\n this._stopRecording = null;\n\n this.seqNo = 0;\n this.replayStartTime = null;\n this.batchStartUrl = null;\n\n this.idleTimeoutId = null;\n this.maxTimeoutId = null;\n\n this.recordMaxMs = MAX_RECORDING_MS;\n this.recordMinMs = 0;\n\n // each replay has its own batcher key to avoid conflicts between rrweb events of different recordings\n // this will be important when persistence is introduced\n var batcherKey = '__mprec_' + this.getConfig('token') + '_' + this.replayId;\n this.batcher = new RequestBatcher(batcherKey, {\n errorReporter: _.bind(this.reportError, this),\n flushOnlyOnInterval: true,\n libConfig: RECORDER_BATCHER_LIB_CONFIG,\n sendRequestFunc: _.bind(this.flushEventsWithOptOut, this),\n usePersistence: false\n });\n};\n\nSessionRecording.prototype.getConfig = function(configVar) {\n return this._mixpanel.get_config(configVar);\n};\n\n// Alias for getConfig, used by the common addOptOutCheckMixpanelLib function which\n// reaches into this class instance and expects the snake case version of the function.\n// eslint-disable-next-line camelcase\nSessionRecording.prototype.get_config = function(configVar) {\n return this.getConfig(configVar);\n};\n\nSessionRecording.prototype.startRecording = function (shouldStopBatcher) {\n if (this._stopRecording !== null) {\n logger$1.log('Recording already in progress, skipping startRecording.');\n return;\n }\n\n this.recordMaxMs = this.getConfig('record_max_ms');\n if (this.recordMaxMs > MAX_RECORDING_MS) {\n this.recordMaxMs = MAX_RECORDING_MS;\n logger$1.critical('record_max_ms cannot be greater than ' + MAX_RECORDING_MS + 'ms. Capping value.');\n }\n\n this.recordMinMs = this.getConfig('record_min_ms');\n if (this.recordMinMs > MAX_VALUE_FOR_MIN_RECORDING_MS) {\n this.recordMinMs = MAX_VALUE_FOR_MIN_RECORDING_MS;\n logger$1.critical('record_min_ms cannot be greater than ' + MAX_VALUE_FOR_MIN_RECORDING_MS + 'ms. Capping value.');\n }\n\n this.replayStartTime = new Date().getTime();\n this.batchStartUrl = _.info.currentUrl();\n\n if (shouldStopBatcher || this.recordMinMs > 0) {\n // the primary case for shouldStopBatcher is when we're starting recording after a reset\n // and don't want to send anything over the network until there's\n // actual user activity\n // this also applies if the minimum recording length has not been hit yet\n // so that we don't send data until we know the recording will be long enough\n this.batcher.stop();\n } else {\n this.batcher.start();\n }\n\n var resetIdleTimeout = _.bind(function () {\n clearTimeout(this.idleTimeoutId);\n this.idleTimeoutId = setTimeout(this._onIdleTimeout, this.getConfig('record_idle_timeout_ms'));\n }, this);\n\n var blockSelector = this.getConfig('record_block_selector');\n if (blockSelector === '' || blockSelector === null) {\n blockSelector = undefined;\n }\n\n this._stopRecording = this._rrwebRecord({\n 'emit': _.bind(function (ev) {\n this.batcher.enqueue(ev);\n if (isUserEvent(ev)) {\n if (this.batcher.stopped && new Date().getTime() - this.replayStartTime >= this.recordMinMs) {\n // start flushing again after user activity\n this.batcher.start();\n }\n resetIdleTimeout();\n }\n }, this),\n 'blockClass': this.getConfig('record_block_class'),\n 'blockSelector': blockSelector,\n 'collectFonts': this.getConfig('record_collect_fonts'),\n 'maskAllInputs': true,\n 'maskTextClass': this.getConfig('record_mask_text_class'),\n 'maskTextSelector': this.getConfig('record_mask_text_selector')\n });\n\n if (typeof this._stopRecording !== 'function') {\n this.reportError('rrweb failed to start, skipping this recording.');\n this._stopRecording = null;\n this.stopRecording(); // stop batcher looping and any timeouts\n return;\n }\n\n resetIdleTimeout();\n\n this.maxTimeoutId = setTimeout(_.bind(this._onMaxLengthReached, this), this.recordMaxMs);\n};\n\nSessionRecording.prototype.stopRecording = function () {\n if (!this.isRrwebStopped()) {\n try {\n this._stopRecording();\n } catch (err) {\n this.reportError('Error with rrweb stopRecording', err);\n }\n this._stopRecording = null;\n }\n\n if (this.batcher.stopped) {\n // never got user activity to flush after reset, so just clear the batcher\n this.batcher.clear();\n } else {\n // flush any remaining events from running batcher\n this.batcher.flush();\n this.batcher.stop();\n }\n\n clearTimeout(this.idleTimeoutId);\n clearTimeout(this.maxTimeoutId);\n};\n\nSessionRecording.prototype.isRrwebStopped = function () {\n return this._stopRecording === null;\n};\n\n/**\n * Flushes the current batch of events to the server, but passes an opt-out callback to make sure\n * we stop recording and dump any queued events if the user has opted out.\n */\nSessionRecording.prototype.flushEventsWithOptOut = function (data, options, cb) {\n this._flushEvents(data, options, cb, _.bind(this._onOptOut, this));\n};\n\nSessionRecording.prototype._onOptOut = function (code) {\n // addOptOutCheckMixpanelLib invokes this function with code=0 when the user has opted out\n if (code === 0) {\n this.stopRecording();\n }\n};\n\nSessionRecording.prototype._sendRequest = function(currentReplayId, reqParams, reqBody, callback) {\n var onSuccess = _.bind(function (response, responseBody) {\n // Update batch specific props only if the request was successful to guarantee ordering.\n // RequestBatcher will always flush the next batch after the previous one succeeds.\n // extra check to see if the replay ID has changed so that we don't increment the seqNo on the wrong replay\n if (response.status === 200 && this.replayId === currentReplayId) {\n this.seqNo++;\n this.batchStartUrl = _.info.currentUrl();\n }\n callback({\n status: 0,\n httpStatusCode: response.status,\n responseBody: responseBody,\n retryAfter: response.headers.get('Retry-After')\n });\n }, this);\n\n win['fetch'](this.getConfig('api_host') + '/' + this.getConfig('api_routes')['record'] + '?' + new URLSearchParams(reqParams), {\n 'method': 'POST',\n 'headers': {\n 'Authorization': 'Basic ' + btoa(this.getConfig('token') + ':'),\n 'Content-Type': 'application/octet-stream'\n },\n 'body': reqBody,\n }).then(function (response) {\n response.json().then(function (responseBody) {\n onSuccess(response, responseBody);\n }).catch(function (error) {\n callback({error: error});\n });\n }).catch(function (error) {\n callback({error: error, httpStatusCode: 0});\n });\n};\n\nSessionRecording.prototype._flushEvents = addOptOutCheckMixpanelLib(function (data, options, callback) {\n const numEvents = data.length;\n\n if (numEvents > 0) {\n var replayId = this.replayId;\n // each rrweb event has a timestamp - leverage those to get time properties\n var batchStartTime = data[0].timestamp;\n if (this.seqNo === 0 || !this.replayStartTime) {\n // extra safety net so that we don't send a null replay start time\n if (this.seqNo !== 0) {\n this.reportError('Replay start time not set but seqNo is not 0. Using current batch start time as a fallback.');\n }\n\n this.replayStartTime = batchStartTime;\n }\n var replayLengthMs = data[numEvents - 1].timestamp - this.replayStartTime;\n\n var reqParams = {\n '$current_url': this.batchStartUrl,\n '$lib_version': Config.LIB_VERSION,\n 'batch_start_time': batchStartTime / 1000,\n 'distinct_id': String(this._mixpanel.get_distinct_id()),\n 'mp_lib': 'web',\n 'replay_id': replayId,\n 'replay_length_ms': replayLengthMs,\n 'replay_start_time': this.replayStartTime / 1000,\n 'seq': this.seqNo\n };\n var eventsJson = _.JSONEncode(data);\n\n // send ID management props if they exist\n var deviceId = this._mixpanel.get_property('$device_id');\n if (deviceId) {\n reqParams['$device_id'] = deviceId;\n }\n var userId = this._mixpanel.get_property('$user_id');\n if (userId) {\n reqParams['$user_id'] = userId;\n }\n\n if (CompressionStream) {\n var jsonStream = new Blob([eventsJson], {type: 'application/json'}).stream();\n var gzipStream = jsonStream.pipeThrough(new CompressionStream('gzip'));\n new Response(gzipStream)\n .blob()\n .then(_.bind(function(compressedBlob) {\n reqParams['format'] = 'gzip';\n this._sendRequest(replayId, reqParams, compressedBlob, callback);\n }, this));\n } else {\n reqParams['format'] = 'body';\n this._sendRequest(replayId, reqParams, eventsJson, callback);\n }\n }\n});\n\n\nSessionRecording.prototype.reportError = function(msg, err) {\n logger$1.error.apply(logger$1.error, arguments);\n try {\n if (!err && !(msg instanceof Error)) {\n msg = new Error(msg);\n }\n this.getConfig('error_reporter')(msg, err);\n } catch(err) {\n logger$1.error(err);\n }\n};\n\nvar logger = console_with_prefix('recorder');\n\n/**\n * Recorder API: manages recordings and exposes methods public to the core Mixpanel library.\n * @param {Object} [options.mixpanelInstance] - reference to the core MixpanelLib\n */\nvar MixpanelRecorder = function(mixpanelInstance) {\n this._mixpanel = mixpanelInstance;\n this.activeRecording = null;\n};\n\nMixpanelRecorder.prototype.startRecording = function(shouldStopBatcher) {\n if (this.activeRecording && !this.activeRecording.isRrwebStopped()) {\n logger.log('Recording already in progress, skipping startRecording.');\n return;\n }\n\n var onIdleTimeout = _.bind(function () {\n logger.log('Idle timeout reached, restarting recording.');\n this.resetRecording();\n }, this);\n\n var onMaxLengthReached = _.bind(function () {\n logger.log('Max recording length reached, stopping recording.');\n this.resetRecording();\n }, this);\n\n this.activeRecording = new SessionRecording({\n mixpanelInstance: this._mixpanel,\n onIdleTimeout: onIdleTimeout,\n onMaxLengthReached: onMaxLengthReached,\n replayId: _.UUID(),\n rrwebRecord: record\n });\n\n this.activeRecording.startRecording(shouldStopBatcher);\n};\n\nMixpanelRecorder.prototype.stopRecording = function() {\n if (this.activeRecording) {\n this.activeRecording.stopRecording();\n this.activeRecording = null;\n }\n};\n\nMixpanelRecorder.prototype.resetRecording = function () {\n this.stopRecording();\n this.startRecording(true);\n};\n\nMixpanelRecorder.prototype.getActiveReplayId = function () {\n if (this.activeRecording && !this.activeRecording.isRrwebStopped()) {\n return this.activeRecording.replayId;\n } else {\n return null;\n }\n};\n\n// getter so that older mixpanel-core versions can still retrieve the replay ID\n// when pulling the latest recorder bundle from the CDN\nObject.defineProperty(MixpanelRecorder.prototype, 'replayId', {\n get: function () {\n return this.getActiveReplayId();\n }\n});\n\nwin['__mp_recorder'] = MixpanelRecorder;\n\n/* eslint camelcase: \"off\" */\n\n/**\n * DomTracker Object\n * @constructor\n */\nvar DomTracker = function() {};\n\n\n// interface\nDomTracker.prototype.create_properties = function() {};\nDomTracker.prototype.event_handler = function() {};\nDomTracker.prototype.after_track_handler = function() {};\n\nDomTracker.prototype.init = function(mixpanel_instance) {\n this.mp = mixpanel_instance;\n return this;\n};\n\n/**\n * @param {Object|string} query\n * @param {string} event_name\n * @param {Object=} properties\n * @param {function=} user_callback\n */\nDomTracker.prototype.track = function(query, event_name, properties, user_callback) {\n var that = this;\n var elements = _.dom_query(query);\n\n if (elements.length === 0) {\n console$1.error('The DOM query (' + query + ') returned 0 elements');\n return;\n }\n\n _.each(elements, function(element) {\n _.register_event(element, this.override_event, function(e) {\n var options = {};\n var props = that.create_properties(properties, this);\n var timeout = that.mp.get_config('track_links_timeout');\n\n that.event_handler(e, this, options);\n\n // in case the mixpanel servers don't get back to us in time\n window.setTimeout(that.track_callback(user_callback, props, options, true), timeout);\n\n // fire the tracking event\n that.mp.track(event_name, props, that.track_callback(user_callback, props, options));\n });\n }, this);\n\n return true;\n};\n\n/**\n * @param {function} user_callback\n * @param {Object} props\n * @param {boolean=} timeout_occured\n */\nDomTracker.prototype.track_callback = function(user_callback, props, options, timeout_occured) {\n timeout_occured = timeout_occured || false;\n var that = this;\n\n return function() {\n // options is referenced from both callbacks, so we can have\n // a 'lock' of sorts to ensure only one fires\n if (options.callback_fired) { return; }\n options.callback_fired = true;\n\n if (user_callback && user_callback(timeout_occured, props) === false) {\n // user can prevent the default functionality by\n // returning false from their callback\n return;\n }\n\n that.after_track_handler(props, options, timeout_occured);\n };\n};\n\nDomTracker.prototype.create_properties = function(properties, element) {\n var props;\n\n if (typeof(properties) === 'function') {\n props = properties(element);\n } else {\n props = _.extend({}, properties);\n }\n\n return props;\n};\n\n/**\n * LinkTracker Object\n * @constructor\n * @extends DomTracker\n */\nvar LinkTracker = function() {\n this.override_event = 'click';\n};\n_.inherit(LinkTracker, DomTracker);\n\nLinkTracker.prototype.create_properties = function(properties, element) {\n var props = LinkTracker.superclass.create_properties.apply(this, arguments);\n\n if (element.href) { props['url'] = element.href; }\n\n return props;\n};\n\nLinkTracker.prototype.event_handler = function(evt, element, options) {\n options.new_tab = (\n evt.which === 2 ||\n evt.metaKey ||\n evt.ctrlKey ||\n element.target === '_blank'\n );\n options.href = element.href;\n\n if (!options.new_tab) {\n evt.preventDefault();\n }\n};\n\nLinkTracker.prototype.after_track_handler = function(props, options) {\n if (options.new_tab) { return; }\n\n setTimeout(function() {\n window.location = options.href;\n }, 0);\n};\n\n/**\n * FormTracker Object\n * @constructor\n * @extends DomTracker\n */\nvar FormTracker = function() {\n this.override_event = 'submit';\n};\n_.inherit(FormTracker, DomTracker);\n\nFormTracker.prototype.event_handler = function(evt, element, options) {\n options.element = element;\n evt.preventDefault();\n};\n\nFormTracker.prototype.after_track_handler = function(props, options) {\n setTimeout(function() {\n options.element.submit();\n }, 0);\n};\n\n/* eslint camelcase: \"off\" */\n\n/** @const */ var SET_ACTION = '$set';\n/** @const */ var SET_ONCE_ACTION = '$set_once';\n/** @const */ var UNSET_ACTION = '$unset';\n/** @const */ var ADD_ACTION = '$add';\n/** @const */ var APPEND_ACTION = '$append';\n/** @const */ var UNION_ACTION = '$union';\n/** @const */ var REMOVE_ACTION = '$remove';\n/** @const */ var DELETE_ACTION = '$delete';\n\n// Common internal methods for mixpanel.people and mixpanel.group APIs.\n// These methods shouldn't involve network I/O.\nvar apiActions = {\n set_action: function(prop, to) {\n var data = {};\n var $set = {};\n if (_.isObject(prop)) {\n _.each(prop, function(v, k) {\n if (!this._is_reserved_property(k)) {\n $set[k] = v;\n }\n }, this);\n } else {\n $set[prop] = to;\n }\n\n data[SET_ACTION] = $set;\n return data;\n },\n\n unset_action: function(prop) {\n var data = {};\n var $unset = [];\n if (!_.isArray(prop)) {\n prop = [prop];\n }\n\n _.each(prop, function(k) {\n if (!this._is_reserved_property(k)) {\n $unset.push(k);\n }\n }, this);\n\n data[UNSET_ACTION] = $unset;\n return data;\n },\n\n set_once_action: function(prop, to) {\n var data = {};\n var $set_once = {};\n if (_.isObject(prop)) {\n _.each(prop, function(v, k) {\n if (!this._is_reserved_property(k)) {\n $set_once[k] = v;\n }\n }, this);\n } else {\n $set_once[prop] = to;\n }\n data[SET_ONCE_ACTION] = $set_once;\n return data;\n },\n\n union_action: function(list_name, values) {\n var data = {};\n var $union = {};\n if (_.isObject(list_name)) {\n _.each(list_name, function(v, k) {\n if (!this._is_reserved_property(k)) {\n $union[k] = _.isArray(v) ? v : [v];\n }\n }, this);\n } else {\n $union[list_name] = _.isArray(values) ? values : [values];\n }\n data[UNION_ACTION] = $union;\n return data;\n },\n\n append_action: function(list_name, value) {\n var data = {};\n var $append = {};\n if (_.isObject(list_name)) {\n _.each(list_name, function(v, k) {\n if (!this._is_reserved_property(k)) {\n $append[k] = v;\n }\n }, this);\n } else {\n $append[list_name] = value;\n }\n data[APPEND_ACTION] = $append;\n return data;\n },\n\n remove_action: function(list_name, value) {\n var data = {};\n var $remove = {};\n if (_.isObject(list_name)) {\n _.each(list_name, function(v, k) {\n if (!this._is_reserved_property(k)) {\n $remove[k] = v;\n }\n }, this);\n } else {\n $remove[list_name] = value;\n }\n data[REMOVE_ACTION] = $remove;\n return data;\n },\n\n delete_action: function() {\n var data = {};\n data[DELETE_ACTION] = '';\n return data;\n }\n};\n\n/* eslint camelcase: \"off\" */\n\n/**\n * Mixpanel Group Object\n * @constructor\n */\nvar MixpanelGroup = function() {};\n\n_.extend(MixpanelGroup.prototype, apiActions);\n\nMixpanelGroup.prototype._init = function(mixpanel_instance, group_key, group_id) {\n this._mixpanel = mixpanel_instance;\n this._group_key = group_key;\n this._group_id = group_id;\n};\n\n/**\n * Set properties on a group.\n *\n * ### Usage:\n *\n * mixpanel.get_group('company', 'mixpanel').set('Location', '405 Howard');\n *\n * // or set multiple properties at once\n * mixpanel.get_group('company', 'mixpanel').set({\n * 'Location': '405 Howard',\n * 'Founded' : 2009,\n * });\n * // properties can be strings, integers, dates, or lists\n *\n * @param {Object|String} prop If a string, this is the name of the property. If an object, this is an associative array of names and values.\n * @param {*} [to] A value to set on the given property name\n * @param {Function} [callback] If provided, the callback will be called after the tracking event\n */\nMixpanelGroup.prototype.set = addOptOutCheckMixpanelGroup(function(prop, to, callback) {\n var data = this.set_action(prop, to);\n if (_.isObject(prop)) {\n callback = to;\n }\n return this._send_request(data, callback);\n});\n\n/**\n * Set properties on a group, only if they do not yet exist.\n * This will not overwrite previous group property values, unlike\n * group.set().\n *\n * ### Usage:\n *\n * mixpanel.get_group('company', 'mixpanel').set_once('Location', '405 Howard');\n *\n * // or set multiple properties at once\n * mixpanel.get_group('company', 'mixpanel').set_once({\n * 'Location': '405 Howard',\n * 'Founded' : 2009,\n * });\n * // properties can be strings, integers, lists or dates\n *\n * @param {Object|String} prop If a string, this is the name of the property. If an object, this is an associative array of names and values.\n * @param {*} [to] A value to set on the given property name\n * @param {Function} [callback] If provided, the callback will be called after the tracking event\n */\nMixpanelGroup.prototype.set_once = addOptOutCheckMixpanelGroup(function(prop, to, callback) {\n var data = this.set_once_action(prop, to);\n if (_.isObject(prop)) {\n callback = to;\n }\n return this._send_request(data, callback);\n});\n\n/**\n * Unset properties on a group permanently.\n *\n * ### Usage:\n *\n * mixpanel.get_group('company', 'mixpanel').unset('Founded');\n *\n * @param {String} prop The name of the property.\n * @param {Function} [callback] If provided, the callback will be called after the tracking event\n */\nMixpanelGroup.prototype.unset = addOptOutCheckMixpanelGroup(function(prop, callback) {\n var data = this.unset_action(prop);\n return this._send_request(data, callback);\n});\n\n/**\n * Merge a given list with a list-valued group property, excluding duplicate values.\n *\n * ### Usage:\n *\n * // merge a value to a list, creating it if needed\n * mixpanel.get_group('company', 'mixpanel').union('Location', ['San Francisco', 'London']);\n *\n * @param {String} list_name Name of the property.\n * @param {Array} values Values to merge with the given property\n * @param {Function} [callback] If provided, the callback will be called after the tracking event\n */\nMixpanelGroup.prototype.union = addOptOutCheckMixpanelGroup(function(list_name, values, callback) {\n if (_.isObject(list_name)) {\n callback = values;\n }\n var data = this.union_action(list_name, values);\n return this._send_request(data, callback);\n});\n\n/**\n * Permanently delete a group.\n *\n * ### Usage:\n *\n * mixpanel.get_group('company', 'mixpanel').delete();\n *\n * @param {Function} [callback] If provided, the callback will be called after the tracking event\n */\nMixpanelGroup.prototype['delete'] = addOptOutCheckMixpanelGroup(function(callback) {\n // bracket notation above prevents a minification error related to reserved words\n var data = this.delete_action();\n return this._send_request(data, callback);\n});\n\n/**\n * Remove a property from a group. The value will be ignored if doesn't exist.\n *\n * ### Usage:\n *\n * mixpanel.get_group('company', 'mixpanel').remove('Location', 'London');\n *\n * @param {String} list_name Name of the property.\n * @param {Object} value Value to remove from the given group property\n * @param {Function} [callback] If provided, the callback will be called after the tracking event\n */\nMixpanelGroup.prototype.remove = addOptOutCheckMixpanelGroup(function(list_name, value, callback) {\n var data = this.remove_action(list_name, value);\n return this._send_request(data, callback);\n});\n\nMixpanelGroup.prototype._send_request = function(data, callback) {\n data['$group_key'] = this._group_key;\n data['$group_id'] = this._group_id;\n data['$token'] = this._get_config('token');\n\n var date_encoded_data = _.encodeDates(data);\n return this._mixpanel._track_or_batch({\n type: 'groups',\n data: date_encoded_data,\n endpoint: this._get_config('api_host') + '/' + this._get_config('api_routes')['groups'],\n batcher: this._mixpanel.request_batchers.groups\n }, callback);\n};\n\nMixpanelGroup.prototype._is_reserved_property = function(prop) {\n return prop === '$group_key' || prop === '$group_id';\n};\n\nMixpanelGroup.prototype._get_config = function(conf) {\n return this._mixpanel.get_config(conf);\n};\n\nMixpanelGroup.prototype.toString = function() {\n return this._mixpanel.toString() + '.group.' + this._group_key + '.' + this._group_id;\n};\n\n// MixpanelGroup Exports\nMixpanelGroup.prototype['remove'] = MixpanelGroup.prototype.remove;\nMixpanelGroup.prototype['set'] = MixpanelGroup.prototype.set;\nMixpanelGroup.prototype['set_once'] = MixpanelGroup.prototype.set_once;\nMixpanelGroup.prototype['union'] = MixpanelGroup.prototype.union;\nMixpanelGroup.prototype['unset'] = MixpanelGroup.prototype.unset;\nMixpanelGroup.prototype['toString'] = MixpanelGroup.prototype.toString;\n\n/* eslint camelcase: \"off\" */\n\n/**\n * Mixpanel People Object\n * @constructor\n */\nvar MixpanelPeople = function() {};\n\n_.extend(MixpanelPeople.prototype, apiActions);\n\nMixpanelPeople.prototype._init = function(mixpanel_instance) {\n this._mixpanel = mixpanel_instance;\n};\n\n/*\n* Set properties on a user record.\n*\n* ### Usage:\n*\n* mixpanel.people.set('gender', 'm');\n*\n* // or set multiple properties at once\n* mixpanel.people.set({\n* 'Company': 'Acme',\n* 'Plan': 'Premium',\n* 'Upgrade date': new Date()\n* });\n* // properties can be strings, integers, dates, or lists\n*\n* @param {Object|String} prop If a string, this is the name of the property. If an object, this is an associative array of names and values.\n* @param {*} [to] A value to set on the given property name\n* @param {Function} [callback] If provided, the callback will be called after tracking the event.\n*/\nMixpanelPeople.prototype.set = addOptOutCheckMixpanelPeople(function(prop, to, callback) {\n var data = this.set_action(prop, to);\n if (_.isObject(prop)) {\n callback = to;\n }\n // make sure that the referrer info has been updated and saved\n if (this._get_config('save_referrer')) {\n this._mixpanel['persistence'].update_referrer_info(document.referrer);\n }\n\n // update $set object with default people properties\n data[SET_ACTION] = _.extend(\n {},\n _.info.people_properties(),\n data[SET_ACTION]\n );\n return this._send_request(data, callback);\n});\n\n/*\n* Set properties on a user record, only if they do not yet exist.\n* This will not overwrite previous people property values, unlike\n* people.set().\n*\n* ### Usage:\n*\n* mixpanel.people.set_once('First Login Date', new Date());\n*\n* // or set multiple properties at once\n* mixpanel.people.set_once({\n* 'First Login Date': new Date(),\n* 'Starting Plan': 'Premium'\n* });\n*\n* // properties can be strings, integers or dates\n*\n* @param {Object|String} prop If a string, this is the name of the property. If an object, this is an associative array of names and values.\n* @param {*} [to] A value to set on the given property name\n* @param {Function} [callback] If provided, the callback will be called after tracking the event.\n*/\nMixpanelPeople.prototype.set_once = addOptOutCheckMixpanelPeople(function(prop, to, callback) {\n var data = this.set_once_action(prop, to);\n if (_.isObject(prop)) {\n callback = to;\n }\n return this._send_request(data, callback);\n});\n\n/*\n* Unset properties on a user record (permanently removes the properties and their values from a profile).\n*\n* ### Usage:\n*\n* mixpanel.people.unset('gender');\n*\n* // or unset multiple properties at once\n* mixpanel.people.unset(['gender', 'Company']);\n*\n* @param {Array|String} prop If a string, this is the name of the property. If an array, this is a list of property names.\n* @param {Function} [callback] If provided, the callback will be called after tracking the event.\n*/\nMixpanelPeople.prototype.unset = addOptOutCheckMixpanelPeople(function(prop, callback) {\n var data = this.unset_action(prop);\n return this._send_request(data, callback);\n});\n\n/*\n* Increment/decrement numeric people analytics properties.\n*\n* ### Usage:\n*\n* mixpanel.people.increment('page_views', 1);\n*\n* // or, for convenience, if you're just incrementing a counter by\n* // 1, you can simply do\n* mixpanel.people.increment('page_views');\n*\n* // to decrement a counter, pass a negative number\n* mixpanel.people.increment('credits_left', -1);\n*\n* // like mixpanel.people.set(), you can increment multiple\n* // properties at once:\n* mixpanel.people.increment({\n* counter1: 1,\n* counter2: 6\n* });\n*\n* @param {Object|String} prop If a string, this is the name of the property. If an object, this is an associative array of names and numeric values.\n* @param {Number} [by] An amount to increment the given property\n* @param {Function} [callback] If provided, the callback will be called after tracking the event.\n*/\nMixpanelPeople.prototype.increment = addOptOutCheckMixpanelPeople(function(prop, by, callback) {\n var data = {};\n var $add = {};\n if (_.isObject(prop)) {\n _.each(prop, function(v, k) {\n if (!this._is_reserved_property(k)) {\n if (isNaN(parseFloat(v))) {\n console$1.error('Invalid increment value passed to mixpanel.people.increment - must be a number');\n return;\n } else {\n $add[k] = v;\n }\n }\n }, this);\n callback = by;\n } else {\n // convenience: mixpanel.people.increment('property'); will\n // increment 'property' by 1\n if (_.isUndefined(by)) {\n by = 1;\n }\n $add[prop] = by;\n }\n data[ADD_ACTION] = $add;\n\n return this._send_request(data, callback);\n});\n\n/*\n* Append a value to a list-valued people analytics property.\n*\n* ### Usage:\n*\n* // append a value to a list, creating it if needed\n* mixpanel.people.append('pages_visited', 'homepage');\n*\n* // like mixpanel.people.set(), you can append multiple\n* // properties at once:\n* mixpanel.people.append({\n* list1: 'bob',\n* list2: 123\n* });\n*\n* @param {Object|String} list_name If a string, this is the name of the property. If an object, this is an associative array of names and values.\n* @param {*} [value] value An item to append to the list\n* @param {Function} [callback] If provided, the callback will be called after tracking the event.\n*/\nMixpanelPeople.prototype.append = addOptOutCheckMixpanelPeople(function(list_name, value, callback) {\n if (_.isObject(list_name)) {\n callback = value;\n }\n var data = this.append_action(list_name, value);\n return this._send_request(data, callback);\n});\n\n/*\n* Remove a value from a list-valued people analytics property.\n*\n* ### Usage:\n*\n* mixpanel.people.remove('School', 'UCB');\n*\n* @param {Object|String} list_name If a string, this is the name of the property. If an object, this is an associative array of names and values.\n* @param {*} [value] value Item to remove from the list\n* @param {Function} [callback] If provided, the callback will be called after tracking the event.\n*/\nMixpanelPeople.prototype.remove = addOptOutCheckMixpanelPeople(function(list_name, value, callback) {\n if (_.isObject(list_name)) {\n callback = value;\n }\n var data = this.remove_action(list_name, value);\n return this._send_request(data, callback);\n});\n\n/*\n* Merge a given list with a list-valued people analytics property,\n* excluding duplicate values.\n*\n* ### Usage:\n*\n* // merge a value to a list, creating it if needed\n* mixpanel.people.union('pages_visited', 'homepage');\n*\n* // like mixpanel.people.set(), you can append multiple\n* // properties at once:\n* mixpanel.people.union({\n* list1: 'bob',\n* list2: 123\n* });\n*\n* // like mixpanel.people.append(), you can append multiple\n* // values to the same list:\n* mixpanel.people.union({\n* list1: ['bob', 'billy']\n* });\n*\n* @param {Object|String} list_name If a string, this is the name of the property. If an object, this is an associative array of names and values.\n* @param {*} [value] Value / values to merge with the given property\n* @param {Function} [callback] If provided, the callback will be called after tracking the event.\n*/\nMixpanelPeople.prototype.union = addOptOutCheckMixpanelPeople(function(list_name, values, callback) {\n if (_.isObject(list_name)) {\n callback = values;\n }\n var data = this.union_action(list_name, values);\n return this._send_request(data, callback);\n});\n\n/*\n * Record that you have charged the current user a certain amount\n * of money. Charges recorded with track_charge() will appear in the\n * Mixpanel revenue report.\n *\n * ### Usage:\n *\n * // charge a user $50\n * mixpanel.people.track_charge(50);\n *\n * // charge a user $30.50 on the 2nd of january\n * mixpanel.people.track_charge(30.50, {\n * '$time': new Date('jan 1 2012')\n * });\n *\n * @param {Number} amount The amount of money charged to the current user\n * @param {Object} [properties] An associative array of properties associated with the charge\n * @param {Function} [callback] If provided, the callback will be called when the server responds\n * @deprecated\n */\nMixpanelPeople.prototype.track_charge = addOptOutCheckMixpanelPeople(function(amount, properties, callback) {\n if (!_.isNumber(amount)) {\n amount = parseFloat(amount);\n if (isNaN(amount)) {\n console$1.error('Invalid value passed to mixpanel.people.track_charge - must be a number');\n return;\n }\n }\n\n return this.append('$transactions', _.extend({\n '$amount': amount\n }, properties), callback);\n});\n\n/*\n * Permanently clear all revenue report transactions from the\n * current user's people analytics profile.\n *\n * ### Usage:\n *\n * mixpanel.people.clear_charges();\n *\n * @param {Function} [callback] If provided, the callback will be called after tracking the event.\n * @deprecated\n */\nMixpanelPeople.prototype.clear_charges = function(callback) {\n return this.set('$transactions', [], callback);\n};\n\n/*\n* Permanently deletes the current people analytics profile from\n* Mixpanel (using the current distinct_id).\n*\n* ### Usage:\n*\n* // remove the all data you have stored about the current user\n* mixpanel.people.delete_user();\n*\n*/\nMixpanelPeople.prototype.delete_user = function() {\n if (!this._identify_called()) {\n console$1.error('mixpanel.people.delete_user() requires you to call identify() first');\n return;\n }\n var data = {'$delete': this._mixpanel.get_distinct_id()};\n return this._send_request(data);\n};\n\nMixpanelPeople.prototype.toString = function() {\n return this._mixpanel.toString() + '.people';\n};\n\nMixpanelPeople.prototype._send_request = function(data, callback) {\n data['$token'] = this._get_config('token');\n data['$distinct_id'] = this._mixpanel.get_distinct_id();\n var device_id = this._mixpanel.get_property('$device_id');\n var user_id = this._mixpanel.get_property('$user_id');\n var had_persisted_distinct_id = this._mixpanel.get_property('$had_persisted_distinct_id');\n if (device_id) {\n data['$device_id'] = device_id;\n }\n if (user_id) {\n data['$user_id'] = user_id;\n }\n if (had_persisted_distinct_id) {\n data['$had_persisted_distinct_id'] = had_persisted_distinct_id;\n }\n\n var date_encoded_data = _.encodeDates(data);\n\n if (!this._identify_called()) {\n this._enqueue(data);\n if (!_.isUndefined(callback)) {\n if (this._get_config('verbose')) {\n callback({status: -1, error: null});\n } else {\n callback(-1);\n }\n }\n return _.truncate(date_encoded_data, 255);\n }\n\n return this._mixpanel._track_or_batch({\n type: 'people',\n data: date_encoded_data,\n endpoint: this._get_config('api_host') + '/' + this._get_config('api_routes')['engage'],\n batcher: this._mixpanel.request_batchers.people\n }, callback);\n};\n\nMixpanelPeople.prototype._get_config = function(conf_var) {\n return this._mixpanel.get_config(conf_var);\n};\n\nMixpanelPeople.prototype._identify_called = function() {\n return this._mixpanel._flags.identify_called === true;\n};\n\n// Queue up engage operations if identify hasn't been called yet.\nMixpanelPeople.prototype._enqueue = function(data) {\n if (SET_ACTION in data) {\n this._mixpanel['persistence']._add_to_people_queue(SET_ACTION, data);\n } else if (SET_ONCE_ACTION in data) {\n this._mixpanel['persistence']._add_to_people_queue(SET_ONCE_ACTION, data);\n } else if (UNSET_ACTION in data) {\n this._mixpanel['persistence']._add_to_people_queue(UNSET_ACTION, data);\n } else if (ADD_ACTION in data) {\n this._mixpanel['persistence']._add_to_people_queue(ADD_ACTION, data);\n } else if (APPEND_ACTION in data) {\n this._mixpanel['persistence']._add_to_people_queue(APPEND_ACTION, data);\n } else if (REMOVE_ACTION in data) {\n this._mixpanel['persistence']._add_to_people_queue(REMOVE_ACTION, data);\n } else if (UNION_ACTION in data) {\n this._mixpanel['persistence']._add_to_people_queue(UNION_ACTION, data);\n } else {\n console$1.error('Invalid call to _enqueue():', data);\n }\n};\n\nMixpanelPeople.prototype._flush_one_queue = function(action, action_method, callback, queue_to_params_fn) {\n var _this = this;\n var queued_data = _.extend({}, this._mixpanel['persistence'].load_queue(action));\n var action_params = queued_data;\n\n if (!_.isUndefined(queued_data) && _.isObject(queued_data) && !_.isEmptyObject(queued_data)) {\n _this._mixpanel['persistence']._pop_from_people_queue(action, queued_data);\n _this._mixpanel['persistence'].save();\n if (queue_to_params_fn) {\n action_params = queue_to_params_fn(queued_data);\n }\n action_method.call(_this, action_params, function(response, data) {\n // on bad response, we want to add it back to the queue\n if (response === 0) {\n _this._mixpanel['persistence']._add_to_people_queue(action, queued_data);\n }\n if (!_.isUndefined(callback)) {\n callback(response, data);\n }\n });\n }\n};\n\n// Flush queued engage operations - order does not matter,\n// and there are network level race conditions anyway\nMixpanelPeople.prototype._flush = function(\n _set_callback, _add_callback, _append_callback, _set_once_callback, _union_callback, _unset_callback, _remove_callback\n) {\n var _this = this;\n\n this._flush_one_queue(SET_ACTION, this.set, _set_callback);\n this._flush_one_queue(SET_ONCE_ACTION, this.set_once, _set_once_callback);\n this._flush_one_queue(UNSET_ACTION, this.unset, _unset_callback, function(queue) { return _.keys(queue); });\n this._flush_one_queue(ADD_ACTION, this.increment, _add_callback);\n this._flush_one_queue(UNION_ACTION, this.union, _union_callback);\n\n // we have to fire off each $append individually since there is\n // no concat method server side\n var $append_queue = this._mixpanel['persistence'].load_queue(APPEND_ACTION);\n if (!_.isUndefined($append_queue) && _.isArray($append_queue) && $append_queue.length) {\n var $append_item;\n var append_callback = function(response, data) {\n if (response === 0) {\n _this._mixpanel['persistence']._add_to_people_queue(APPEND_ACTION, $append_item);\n }\n if (!_.isUndefined(_append_callback)) {\n _append_callback(response, data);\n }\n };\n for (var i = $append_queue.length - 1; i >= 0; i--) {\n $append_queue = this._mixpanel['persistence'].load_queue(APPEND_ACTION);\n $append_item = $append_queue.pop();\n _this._mixpanel['persistence'].save();\n if (!_.isEmptyObject($append_item)) {\n _this.append($append_item, append_callback);\n }\n }\n }\n\n // same for $remove\n var $remove_queue = this._mixpanel['persistence'].load_queue(REMOVE_ACTION);\n if (!_.isUndefined($remove_queue) && _.isArray($remove_queue) && $remove_queue.length) {\n var $remove_item;\n var remove_callback = function(response, data) {\n if (response === 0) {\n _this._mixpanel['persistence']._add_to_people_queue(REMOVE_ACTION, $remove_item);\n }\n if (!_.isUndefined(_remove_callback)) {\n _remove_callback(response, data);\n }\n };\n for (var j = $remove_queue.length - 1; j >= 0; j--) {\n $remove_queue = this._mixpanel['persistence'].load_queue(REMOVE_ACTION);\n $remove_item = $remove_queue.pop();\n _this._mixpanel['persistence'].save();\n if (!_.isEmptyObject($remove_item)) {\n _this.remove($remove_item, remove_callback);\n }\n }\n }\n};\n\nMixpanelPeople.prototype._is_reserved_property = function(prop) {\n return prop === '$distinct_id' || prop === '$token' || prop === '$device_id' || prop === '$user_id' || prop === '$had_persisted_distinct_id';\n};\n\n// MixpanelPeople Exports\nMixpanelPeople.prototype['set'] = MixpanelPeople.prototype.set;\nMixpanelPeople.prototype['set_once'] = MixpanelPeople.prototype.set_once;\nMixpanelPeople.prototype['unset'] = MixpanelPeople.prototype.unset;\nMixpanelPeople.prototype['increment'] = MixpanelPeople.prototype.increment;\nMixpanelPeople.prototype['append'] = MixpanelPeople.prototype.append;\nMixpanelPeople.prototype['remove'] = MixpanelPeople.prototype.remove;\nMixpanelPeople.prototype['union'] = MixpanelPeople.prototype.union;\nMixpanelPeople.prototype['track_charge'] = MixpanelPeople.prototype.track_charge;\nMixpanelPeople.prototype['clear_charges'] = MixpanelPeople.prototype.clear_charges;\nMixpanelPeople.prototype['delete_user'] = MixpanelPeople.prototype.delete_user;\nMixpanelPeople.prototype['toString'] = MixpanelPeople.prototype.toString;\n\n/* eslint camelcase: \"off\" */\n\n/*\n * Constants\n */\n/** @const */ var SET_QUEUE_KEY = '__mps';\n/** @const */ var SET_ONCE_QUEUE_KEY = '__mpso';\n/** @const */ var UNSET_QUEUE_KEY = '__mpus';\n/** @const */ var ADD_QUEUE_KEY = '__mpa';\n/** @const */ var APPEND_QUEUE_KEY = '__mpap';\n/** @const */ var REMOVE_QUEUE_KEY = '__mpr';\n/** @const */ var UNION_QUEUE_KEY = '__mpu';\n// This key is deprecated, but we want to check for it to see whether aliasing is allowed.\n/** @const */ var PEOPLE_DISTINCT_ID_KEY = '$people_distinct_id';\n/** @const */ var ALIAS_ID_KEY = '__alias';\n/** @const */ var EVENT_TIMERS_KEY = '__timers';\n/** @const */ var RESERVED_PROPERTIES = [\n SET_QUEUE_KEY,\n SET_ONCE_QUEUE_KEY,\n UNSET_QUEUE_KEY,\n ADD_QUEUE_KEY,\n APPEND_QUEUE_KEY,\n REMOVE_QUEUE_KEY,\n UNION_QUEUE_KEY,\n PEOPLE_DISTINCT_ID_KEY,\n ALIAS_ID_KEY,\n EVENT_TIMERS_KEY\n];\n\n/**\n * Mixpanel Persistence Object\n * @constructor\n */\nvar MixpanelPersistence = function(config) {\n this['props'] = {};\n this.campaign_params_saved = false;\n\n if (config['persistence_name']) {\n this.name = 'mp_' + config['persistence_name'];\n } else {\n this.name = 'mp_' + config['token'] + '_mixpanel';\n }\n\n var storage_type = config['persistence'];\n if (storage_type !== 'cookie' && storage_type !== 'localStorage') {\n console$1.critical('Unknown persistence type ' + storage_type + '; falling back to cookie');\n storage_type = config['persistence'] = 'cookie';\n }\n\n if (storage_type === 'localStorage' && _.localStorage.is_supported()) {\n this.storage = _.localStorage;\n } else {\n this.storage = _.cookie;\n }\n\n this.load();\n this.update_config(config);\n this.upgrade();\n this.save();\n};\n\nMixpanelPersistence.prototype.properties = function() {\n var p = {};\n\n this.load();\n\n // Filter out reserved properties\n _.each(this['props'], function(v, k) {\n if (!_.include(RESERVED_PROPERTIES, k)) {\n p[k] = v;\n }\n });\n return p;\n};\n\nMixpanelPersistence.prototype.load = function() {\n if (this.disabled) { return; }\n\n var entry = this.storage.parse(this.name);\n\n if (entry) {\n this['props'] = _.extend({}, entry);\n }\n};\n\nMixpanelPersistence.prototype.upgrade = function() {\n var old_cookie,\n old_localstorage;\n\n // if transferring from cookie to localStorage or vice-versa, copy existing\n // super properties over to new storage mode\n if (this.storage === _.localStorage) {\n old_cookie = _.cookie.parse(this.name);\n\n _.cookie.remove(this.name);\n _.cookie.remove(this.name, true);\n\n if (old_cookie) {\n this.register_once(old_cookie);\n }\n } else if (this.storage === _.cookie) {\n old_localstorage = _.localStorage.parse(this.name);\n\n _.localStorage.remove(this.name);\n\n if (old_localstorage) {\n this.register_once(old_localstorage);\n }\n }\n};\n\nMixpanelPersistence.prototype.save = function() {\n if (this.disabled) { return; }\n\n this.storage.set(\n this.name,\n _.JSONEncode(this['props']),\n this.expire_days,\n this.cross_subdomain,\n this.secure,\n this.cross_site,\n this.cookie_domain\n );\n};\n\nMixpanelPersistence.prototype.load_prop = function(key) {\n this.load();\n return this['props'][key];\n};\n\nMixpanelPersistence.prototype.remove = function() {\n // remove both domain and subdomain cookies\n this.storage.remove(this.name, false, this.cookie_domain);\n this.storage.remove(this.name, true, this.cookie_domain);\n};\n\n// removes the storage entry and deletes all loaded data\n// forced name for tests\nMixpanelPersistence.prototype.clear = function() {\n this.remove();\n this['props'] = {};\n};\n\n/**\n* @param {Object} props\n* @param {*=} default_value\n* @param {number=} days\n*/\nMixpanelPersistence.prototype.register_once = function(props, default_value, days) {\n if (_.isObject(props)) {\n if (typeof(default_value) === 'undefined') { default_value = 'None'; }\n this.expire_days = (typeof(days) === 'undefined') ? this.default_expiry : days;\n\n this.load();\n\n _.each(props, function(val, prop) {\n if (!this['props'].hasOwnProperty(prop) || this['props'][prop] === default_value) {\n this['props'][prop] = val;\n }\n }, this);\n\n this.save();\n\n return true;\n }\n return false;\n};\n\n/**\n* @param {Object} props\n* @param {number=} days\n*/\nMixpanelPersistence.prototype.register = function(props, days) {\n if (_.isObject(props)) {\n this.expire_days = (typeof(days) === 'undefined') ? this.default_expiry : days;\n\n this.load();\n _.extend(this['props'], props);\n this.save();\n\n return true;\n }\n return false;\n};\n\nMixpanelPersistence.prototype.unregister = function(prop) {\n this.load();\n if (prop in this['props']) {\n delete this['props'][prop];\n this.save();\n }\n};\n\nMixpanelPersistence.prototype.update_search_keyword = function(referrer) {\n this.register(_.info.searchInfo(referrer));\n};\n\n// EXPORTED METHOD, we test this directly.\nMixpanelPersistence.prototype.update_referrer_info = function(referrer) {\n // If referrer doesn't exist, we want to note the fact that it was type-in traffic.\n this.register_once({\n '$initial_referrer': referrer || '$direct',\n '$initial_referring_domain': _.info.referringDomain(referrer) || '$direct'\n }, '');\n};\n\nMixpanelPersistence.prototype.get_referrer_info = function() {\n return _.strip_empty_properties({\n '$initial_referrer': this['props']['$initial_referrer'],\n '$initial_referring_domain': this['props']['$initial_referring_domain']\n });\n};\n\nMixpanelPersistence.prototype.update_config = function(config) {\n this.default_expiry = this.expire_days = config['cookie_expiration'];\n this.set_disabled(config['disable_persistence']);\n this.set_cookie_domain(config['cookie_domain']);\n this.set_cross_site(config['cross_site_cookie']);\n this.set_cross_subdomain(config['cross_subdomain_cookie']);\n this.set_secure(config['secure_cookie']);\n};\n\nMixpanelPersistence.prototype.set_disabled = function(disabled) {\n this.disabled = disabled;\n if (this.disabled) {\n this.remove();\n } else {\n this.save();\n }\n};\n\nMixpanelPersistence.prototype.set_cookie_domain = function(cookie_domain) {\n if (cookie_domain !== this.cookie_domain) {\n this.remove();\n this.cookie_domain = cookie_domain;\n this.save();\n }\n};\n\nMixpanelPersistence.prototype.set_cross_site = function(cross_site) {\n if (cross_site !== this.cross_site) {\n this.cross_site = cross_site;\n this.remove();\n this.save();\n }\n};\n\nMixpanelPersistence.prototype.set_cross_subdomain = function(cross_subdomain) {\n if (cross_subdomain !== this.cross_subdomain) {\n this.cross_subdomain = cross_subdomain;\n this.remove();\n this.save();\n }\n};\n\nMixpanelPersistence.prototype.get_cross_subdomain = function() {\n return this.cross_subdomain;\n};\n\nMixpanelPersistence.prototype.set_secure = function(secure) {\n if (secure !== this.secure) {\n this.secure = secure ? true : false;\n this.remove();\n this.save();\n }\n};\n\nMixpanelPersistence.prototype._add_to_people_queue = function(queue, data) {\n var q_key = this._get_queue_key(queue),\n q_data = data[queue],\n set_q = this._get_or_create_queue(SET_ACTION),\n set_once_q = this._get_or_create_queue(SET_ONCE_ACTION),\n unset_q = this._get_or_create_queue(UNSET_ACTION),\n add_q = this._get_or_create_queue(ADD_ACTION),\n union_q = this._get_or_create_queue(UNION_ACTION),\n remove_q = this._get_or_create_queue(REMOVE_ACTION, []),\n append_q = this._get_or_create_queue(APPEND_ACTION, []);\n\n if (q_key === SET_QUEUE_KEY) {\n // Update the set queue - we can override any existing values\n _.extend(set_q, q_data);\n // if there was a pending increment, override it\n // with the set.\n this._pop_from_people_queue(ADD_ACTION, q_data);\n // if there was a pending union, override it\n // with the set.\n this._pop_from_people_queue(UNION_ACTION, q_data);\n this._pop_from_people_queue(UNSET_ACTION, q_data);\n } else if (q_key === SET_ONCE_QUEUE_KEY) {\n // only queue the data if there is not already a set_once call for it.\n _.each(q_data, function(v, k) {\n if (!(k in set_once_q)) {\n set_once_q[k] = v;\n }\n });\n this._pop_from_people_queue(UNSET_ACTION, q_data);\n } else if (q_key === UNSET_QUEUE_KEY) {\n _.each(q_data, function(prop) {\n\n // undo previously-queued actions on this key\n _.each([set_q, set_once_q, add_q, union_q], function(enqueued_obj) {\n if (prop in enqueued_obj) {\n delete enqueued_obj[prop];\n }\n });\n _.each(append_q, function(append_obj) {\n if (prop in append_obj) {\n delete append_obj[prop];\n }\n });\n\n unset_q[prop] = true;\n\n });\n } else if (q_key === ADD_QUEUE_KEY) {\n _.each(q_data, function(v, k) {\n // If it exists in the set queue, increment\n // the value\n if (k in set_q) {\n set_q[k] += v;\n } else {\n // If it doesn't exist, update the add\n // queue\n if (!(k in add_q)) {\n add_q[k] = 0;\n }\n add_q[k] += v;\n }\n }, this);\n this._pop_from_people_queue(UNSET_ACTION, q_data);\n } else if (q_key === UNION_QUEUE_KEY) {\n _.each(q_data, function(v, k) {\n if (_.isArray(v)) {\n if (!(k in union_q)) {\n union_q[k] = [];\n }\n // We may send duplicates, the server will dedup them.\n union_q[k] = union_q[k].concat(v);\n }\n });\n this._pop_from_people_queue(UNSET_ACTION, q_data);\n } else if (q_key === REMOVE_QUEUE_KEY) {\n remove_q.push(q_data);\n this._pop_from_people_queue(APPEND_ACTION, q_data);\n } else if (q_key === APPEND_QUEUE_KEY) {\n append_q.push(q_data);\n this._pop_from_people_queue(UNSET_ACTION, q_data);\n }\n\n console$1.log('MIXPANEL PEOPLE REQUEST (QUEUED, PENDING IDENTIFY):');\n console$1.log(data);\n\n this.save();\n};\n\nMixpanelPersistence.prototype._pop_from_people_queue = function(queue, data) {\n var q = this['props'][this._get_queue_key(queue)];\n if (!_.isUndefined(q)) {\n _.each(data, function(v, k) {\n if (queue === APPEND_ACTION || queue === REMOVE_ACTION) {\n // list actions: only remove if both k+v match\n // e.g. remove should not override append in a case like\n // append({foo: 'bar'}); remove({foo: 'qux'})\n _.each(q, function(queued_action) {\n if (queued_action[k] === v) {\n delete queued_action[k];\n }\n });\n } else {\n delete q[k];\n }\n }, this);\n }\n};\n\nMixpanelPersistence.prototype.load_queue = function(queue) {\n return this.load_prop(this._get_queue_key(queue));\n};\n\nMixpanelPersistence.prototype._get_queue_key = function(queue) {\n if (queue === SET_ACTION) {\n return SET_QUEUE_KEY;\n } else if (queue === SET_ONCE_ACTION) {\n return SET_ONCE_QUEUE_KEY;\n } else if (queue === UNSET_ACTION) {\n return UNSET_QUEUE_KEY;\n } else if (queue === ADD_ACTION) {\n return ADD_QUEUE_KEY;\n } else if (queue === APPEND_ACTION) {\n return APPEND_QUEUE_KEY;\n } else if (queue === REMOVE_ACTION) {\n return REMOVE_QUEUE_KEY;\n } else if (queue === UNION_ACTION) {\n return UNION_QUEUE_KEY;\n } else {\n console$1.error('Invalid queue:', queue);\n }\n};\n\nMixpanelPersistence.prototype._get_or_create_queue = function(queue, default_val) {\n var key = this._get_queue_key(queue);\n default_val = _.isUndefined(default_val) ? {} : default_val;\n return this['props'][key] || (this['props'][key] = default_val);\n};\n\nMixpanelPersistence.prototype.set_event_timer = function(event_name, timestamp) {\n var timers = this.load_prop(EVENT_TIMERS_KEY) || {};\n timers[event_name] = timestamp;\n this['props'][EVENT_TIMERS_KEY] = timers;\n this.save();\n};\n\nMixpanelPersistence.prototype.remove_event_timer = function(event_name) {\n var timers = this.load_prop(EVENT_TIMERS_KEY) || {};\n var timestamp = timers[event_name];\n if (!_.isUndefined(timestamp)) {\n delete this['props'][EVENT_TIMERS_KEY][event_name];\n this.save();\n }\n return timestamp;\n};\n\n/* eslint camelcase: \"off\" */\n\n/*\n * Mixpanel JS Library\n *\n * Copyright 2012, Mixpanel, Inc. All Rights Reserved\n * http://mixpanel.com/\n *\n * Includes portions of Underscore.js\n * http://documentcloud.github.com/underscore/\n * (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.\n * Released under the MIT License.\n */\n\n// ==ClosureCompiler==\n// @compilation_level ADVANCED_OPTIMIZATIONS\n// @output_file_name mixpanel-2.8.min.js\n// ==/ClosureCompiler==\n\n/*\nSIMPLE STYLE GUIDE:\n\nthis.x === public function\nthis._x === internal - only use within this file\nthis.__x === private - only use within the class\n\nGlobals should be all caps\n*/\n\nvar init_type; // MODULE or SNIPPET loader\n// allow bundlers to specify how extra code (recorder bundle) should be loaded\n// eslint-disable-next-line no-unused-vars\nvar load_extra_bundle = function(src, _onload) {\n throw new Error(src + ' not available in this build.');\n};\n\nvar mixpanel_master; // main mixpanel instance / object\nvar INIT_MODULE = 0;\nvar INIT_SNIPPET = 1;\n\nvar IDENTITY_FUNC = function(x) {return x;};\nvar NOOP_FUNC = function() {};\n\n/** @const */ var PRIMARY_INSTANCE_NAME = 'mixpanel';\n/** @const */ var PAYLOAD_TYPE_BASE64 = 'base64';\n/** @const */ var PAYLOAD_TYPE_JSON = 'json';\n/** @const */ var DEVICE_ID_PREFIX = '$device:';\n\n\n/*\n * Dynamic... constants? Is that an oxymoron?\n */\n// http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/\n// https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#withCredentials\nvar USE_XHR = (win.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest());\n\n// IE<10 does not support cross-origin XHR's but script tags\n// with defer won't block window.onload; ENQUEUE_REQUESTS\n// should only be true for Opera<12\nvar ENQUEUE_REQUESTS = !USE_XHR && (userAgent.indexOf('MSIE') === -1) && (userAgent.indexOf('Mozilla') === -1);\n\n// save reference to navigator.sendBeacon so it can be minified\nvar sendBeacon = null;\nif (navigator['sendBeacon']) {\n sendBeacon = function() {\n // late reference to navigator.sendBeacon to allow patching/spying\n return navigator['sendBeacon'].apply(navigator, arguments);\n };\n}\n\nvar DEFAULT_API_ROUTES = {\n 'track': 'track/',\n 'engage': 'engage/',\n 'groups': 'groups/',\n 'record': 'record/'\n};\n\n/*\n * Module-level globals\n */\nvar DEFAULT_CONFIG = {\n 'api_host': 'https://api-js.mixpanel.com',\n 'api_routes': DEFAULT_API_ROUTES,\n 'api_method': 'POST',\n 'api_transport': 'XHR',\n 'api_payload_format': PAYLOAD_TYPE_BASE64,\n 'app_host': 'https://mixpanel.com',\n 'cdn': 'https://cdn.mxpnl.com',\n 'cross_site_cookie': false,\n 'cross_subdomain_cookie': true,\n 'error_reporter': NOOP_FUNC,\n 'persistence': 'cookie',\n 'persistence_name': '',\n 'cookie_domain': '',\n 'cookie_name': '',\n 'loaded': NOOP_FUNC,\n 'mp_loader': null,\n 'track_marketing': true,\n 'track_pageview': false,\n 'skip_first_touch_marketing': false,\n 'store_google': true,\n 'stop_utm_persistence': false,\n 'save_referrer': true,\n 'test': false,\n 'verbose': false,\n 'img': false,\n 'debug': false,\n 'track_links_timeout': 300,\n 'cookie_expiration': 365,\n 'upgrade': false,\n 'disable_persistence': false,\n 'disable_cookie': false,\n 'secure_cookie': false,\n 'ip': true,\n 'opt_out_tracking_by_default': false,\n 'opt_out_persistence_by_default': false,\n 'opt_out_tracking_persistence_type': 'localStorage',\n 'opt_out_tracking_cookie_prefix': null,\n 'property_blacklist': [],\n 'xhr_headers': {}, // { header: value, header2: value }\n 'ignore_dnt': false,\n 'batch_requests': true,\n 'batch_size': 50,\n 'batch_flush_interval_ms': 5000,\n 'batch_request_timeout_ms': 90000,\n 'batch_autostart': true,\n 'hooks': {},\n 'record_block_class': new RegExp('^(mp-block|fs-exclude|amp-block|rr-block|ph-no-capture)$'),\n 'record_block_selector': 'img, video',\n 'record_collect_fonts': false,\n 'record_idle_timeout_ms': 30 * 60 * 1000, // 30 minutes\n 'record_mask_text_class': new RegExp('^(mp-mask|fs-mask|amp-mask|rr-mask|ph-mask)$'),\n 'record_mask_text_selector': '*',\n 'record_max_ms': MAX_RECORDING_MS,\n 'record_min_ms': 0,\n 'record_sessions_percent': 0,\n 'recorder_src': 'https://cdn.mxpnl.com/libs/mixpanel-recorder.min.js'\n};\n\nvar DOM_LOADED = false;\n\n/**\n * Mixpanel Library Object\n * @constructor\n */\nvar MixpanelLib = function() {};\n\n\n/**\n * create_mplib(token:string, config:object, name:string)\n *\n * This function is used by the init method of MixpanelLib objects\n * as well as the main initializer at the end of the JSLib (that\n * initializes document.mixpanel as well as any additional instances\n * declared before this file has loaded).\n */\nvar create_mplib = function(token, config, name) {\n var instance,\n target = (name === PRIMARY_INSTANCE_NAME) ? mixpanel_master : mixpanel_master[name];\n\n if (target && init_type === INIT_MODULE) {\n instance = target;\n } else {\n if (target && !_.isArray(target)) {\n console$1.error('You have already initialized ' + name);\n return;\n }\n instance = new MixpanelLib();\n }\n\n instance._cached_groups = {}; // cache groups in a pool\n\n instance._init(token, config, name);\n\n instance['people'] = new MixpanelPeople();\n instance['people']._init(instance);\n\n if (!instance.get_config('skip_first_touch_marketing')) {\n // We need null UTM params in the object because\n // UTM parameters act as a tuple. If any UTM param\n // is present, then we set all UTM params including\n // empty ones together\n var utm_params = _.info.campaignParams(null);\n var initial_utm_params = {};\n var has_utm = false;\n _.each(utm_params, function(utm_value, utm_key) {\n initial_utm_params['initial_' + utm_key] = utm_value;\n if (utm_value) {\n has_utm = true;\n }\n });\n if (has_utm) {\n instance['people'].set_once(initial_utm_params);\n }\n }\n\n // if any instance on the page has debug = true, we set the\n // global debug to be true\n Config.DEBUG = Config.DEBUG || instance.get_config('debug');\n\n // if target is not defined, we called init after the lib already\n // loaded, so there won't be an array of things to execute\n if (!_.isUndefined(target) && _.isArray(target)) {\n // Crunch through the people queue first - we queue this data up &\n // flush on identify, so it's better to do all these operations first\n instance._execute_array.call(instance['people'], target['people']);\n instance._execute_array(target);\n }\n\n return instance;\n};\n\n// Initialization methods\n\n/**\n * This function initializes a new instance of the Mixpanel tracking object.\n * All new instances are added to the main mixpanel object as sub properties (such as\n * mixpanel.library_name) and also returned by this function. To define a\n * second instance on the page, you would call:\n *\n * mixpanel.init('new token', { your: 'config' }, 'library_name');\n *\n * and use it like so:\n *\n * mixpanel.library_name.track(...);\n *\n * @param {String} token Your Mixpanel API token\n * @param {Object} [config] A dictionary of config options to override. See a list of default config options.\n * @param {String} [name] The name for the new mixpanel instance that you want created\n */\nMixpanelLib.prototype.init = function (token, config, name) {\n if (_.isUndefined(name)) {\n this.report_error('You must name your new library: init(token, config, name)');\n return;\n }\n if (name === PRIMARY_INSTANCE_NAME) {\n this.report_error('You must initialize the main mixpanel object right after you include the Mixpanel js snippet');\n return;\n }\n\n var instance = create_mplib(token, config, name);\n mixpanel_master[name] = instance;\n instance._loaded();\n\n return instance;\n};\n\n// mixpanel._init(token:string, config:object, name:string)\n//\n// This function sets up the current instance of the mixpanel\n// library. The difference between this method and the init(...)\n// method is this one initializes the actual instance, whereas the\n// init(...) method sets up a new library and calls _init on it.\n//\nMixpanelLib.prototype._init = function(token, config, name) {\n config = config || {};\n\n this['__loaded'] = true;\n this['config'] = {};\n\n var variable_features = {};\n\n // default to JSON payload for standard mixpanel.com API hosts\n if (!('api_payload_format' in config)) {\n var api_host = config['api_host'] || DEFAULT_CONFIG['api_host'];\n if (api_host.match(/\\.mixpanel\\.com/)) {\n variable_features['api_payload_format'] = PAYLOAD_TYPE_JSON;\n }\n }\n\n this.set_config(_.extend({}, DEFAULT_CONFIG, variable_features, config, {\n 'name': name,\n 'token': token,\n 'callback_fn': ((name === PRIMARY_INSTANCE_NAME) ? name : PRIMARY_INSTANCE_NAME + '.' + name) + '._jsc'\n }));\n\n this['_jsc'] = NOOP_FUNC;\n\n this.__dom_loaded_queue = [];\n this.__request_queue = [];\n this.__disabled_events = [];\n this._flags = {\n 'disable_all_events': false,\n 'identify_called': false\n };\n\n // set up request queueing/batching\n this.request_batchers = {};\n this._batch_requests = this.get_config('batch_requests');\n if (this._batch_requests) {\n if (!_.localStorage.is_supported(true) || !USE_XHR) {\n this._batch_requests = false;\n console$1.log('Turning off Mixpanel request-queueing; needs XHR and localStorage support');\n _.each(this.get_batcher_configs(), function(batcher_config) {\n console$1.log('Clearing batch queue ' + batcher_config.queue_key);\n _.localStorage.remove(batcher_config.queue_key);\n });\n } else {\n this.init_batchers();\n if (sendBeacon && win.addEventListener) {\n // Before page closes or hides (user tabs away etc), attempt to flush any events\n // queued up via navigator.sendBeacon. Since sendBeacon doesn't report success/failure,\n // events will not be removed from the persistent store; if the site is loaded again,\n // the events will be flushed again on startup and deduplicated on the Mixpanel server\n // side.\n // There is no reliable way to capture only page close events, so we lean on the\n // visibilitychange and pagehide events as recommended at\n // https://developer.mozilla.org/en-US/docs/Web/API/Window/unload_event#usage_notes.\n // These events fire when the user clicks away from the current page/tab, so will occur\n // more frequently than page unload, but are the only mechanism currently for capturing\n // this scenario somewhat reliably.\n var flush_on_unload = _.bind(function() {\n if (!this.request_batchers.events.stopped) {\n this.request_batchers.events.flush({unloading: true});\n }\n }, this);\n win.addEventListener('pagehide', function(ev) {\n if (ev['persisted']) {\n flush_on_unload();\n }\n });\n win.addEventListener('visibilitychange', function() {\n if (document$1['visibilityState'] === 'hidden') {\n flush_on_unload();\n }\n });\n }\n }\n }\n\n this['persistence'] = this['cookie'] = new MixpanelPersistence(this['config']);\n this.unpersisted_superprops = {};\n this._gdpr_init();\n\n var uuid = _.UUID();\n if (!this.get_distinct_id()) {\n // There is no need to set the distinct id\n // or the device id if something was already stored\n // in the persitence\n this.register_once({\n 'distinct_id': DEVICE_ID_PREFIX + uuid,\n '$device_id': uuid\n }, '');\n }\n\n var track_pageview_option = this.get_config('track_pageview');\n if (track_pageview_option) {\n this._init_url_change_tracking(track_pageview_option);\n }\n\n if (this.get_config('record_sessions_percent') > 0 && Math.random() * 100 <= this.get_config('record_sessions_percent')) {\n this.start_session_recording();\n }\n};\n\nMixpanelLib.prototype.start_session_recording = addOptOutCheckMixpanelLib(function () {\n if (!win['MutationObserver']) {\n console$1.critical('Browser does not support MutationObserver; skipping session recording');\n return;\n }\n\n var handleLoadedRecorder = _.bind(function() {\n this._recorder = this._recorder || new win['__mp_recorder'](this);\n this._recorder['startRecording']();\n }, this);\n\n if (_.isUndefined(win['__mp_recorder'])) {\n load_extra_bundle(this.get_config('recorder_src'), handleLoadedRecorder);\n } else {\n handleLoadedRecorder();\n }\n});\n\nMixpanelLib.prototype.stop_session_recording = function () {\n if (this._recorder) {\n this._recorder['stopRecording']();\n } else {\n console$1.critical('Session recorder module not loaded');\n }\n};\n\nMixpanelLib.prototype.get_session_recording_properties = function () {\n var props = {};\n var replay_id = this._get_session_replay_id();\n if (replay_id) {\n props['$mp_replay_id'] = replay_id;\n }\n return props;\n};\n\nMixpanelLib.prototype.get_session_replay_url = function () {\n var replay_url = null;\n var replay_id = this._get_session_replay_id();\n if (replay_id) {\n var query_params = _.HTTPBuildQuery({\n 'replay_id': replay_id,\n 'distinct_id': this.get_distinct_id(),\n 'token': this.get_config('token')\n });\n replay_url = 'https://mixpanel.com/projects/replay-redirect?' + query_params;\n }\n return replay_url;\n};\n\nMixpanelLib.prototype._get_session_replay_id = function () {\n var replay_id = null;\n if (this._recorder) {\n replay_id = this._recorder['replayId'];\n }\n return replay_id || null;\n};\n\n// Private methods\n\nMixpanelLib.prototype._loaded = function() {\n this.get_config('loaded')(this);\n this._set_default_superprops();\n this['people'].set_once(this['persistence'].get_referrer_info());\n\n // `store_google` is now deprecated and previously stored UTM parameters are cleared\n // from persistence by default.\n if (this.get_config('store_google') && this.get_config('stop_utm_persistence')) {\n var utm_params = _.info.campaignParams(null);\n _.each(utm_params, function(_utm_value, utm_key) {\n // We need to unregister persisted UTM parameters so old values\n // are not mixed with the new UTM parameters\n this.unregister(utm_key);\n }.bind(this));\n }\n};\n\n// update persistence with info on referrer, UTM params, etc\nMixpanelLib.prototype._set_default_superprops = function() {\n this['persistence'].update_search_keyword(document$1.referrer);\n // Registering super properties for UTM persistence by 'store_google' is deprecated.\n if (this.get_config('store_google') && !this.get_config('stop_utm_persistence')) {\n this.register(_.info.campaignParams());\n }\n if (this.get_config('save_referrer')) {\n this['persistence'].update_referrer_info(document$1.referrer);\n }\n};\n\nMixpanelLib.prototype._dom_loaded = function() {\n _.each(this.__dom_loaded_queue, function(item) {\n this._track_dom.apply(this, item);\n }, this);\n\n if (!this.has_opted_out_tracking()) {\n _.each(this.__request_queue, function(item) {\n this._send_request.apply(this, item);\n }, this);\n }\n\n delete this.__dom_loaded_queue;\n delete this.__request_queue;\n};\n\nMixpanelLib.prototype._track_dom = function(DomClass, args) {\n if (this.get_config('img')) {\n this.report_error('You can\\'t use DOM tracking functions with img = true.');\n return false;\n }\n\n if (!DOM_LOADED) {\n this.__dom_loaded_queue.push([DomClass, args]);\n return false;\n }\n\n var dt = new DomClass().init(this);\n return dt.track.apply(dt, args);\n};\n\nMixpanelLib.prototype._init_url_change_tracking = function(track_pageview_option) {\n var previous_tracked_url = '';\n var tracked = this.track_pageview();\n if (tracked) {\n previous_tracked_url = _.info.currentUrl();\n }\n\n if (_.include(['full-url', 'url-with-path-and-query-string', 'url-with-path'], track_pageview_option)) {\n win.addEventListener('popstate', function() {\n win.dispatchEvent(new Event('mp_locationchange'));\n });\n win.addEventListener('hashchange', function() {\n win.dispatchEvent(new Event('mp_locationchange'));\n });\n var nativePushState = win.history.pushState;\n if (typeof nativePushState === 'function') {\n win.history.pushState = function(state, unused, url) {\n nativePushState.call(win.history, state, unused, url);\n win.dispatchEvent(new Event('mp_locationchange'));\n };\n }\n var nativeReplaceState = win.history.replaceState;\n if (typeof nativeReplaceState === 'function') {\n win.history.replaceState = function(state, unused, url) {\n nativeReplaceState.call(win.history, state, unused, url);\n win.dispatchEvent(new Event('mp_locationchange'));\n };\n }\n win.addEventListener('mp_locationchange', function() {\n var current_url = _.info.currentUrl();\n var should_track = false;\n if (track_pageview_option === 'full-url') {\n should_track = current_url !== previous_tracked_url;\n } else if (track_pageview_option === 'url-with-path-and-query-string') {\n should_track = current_url.split('#')[0] !== previous_tracked_url.split('#')[0];\n } else if (track_pageview_option === 'url-with-path') {\n should_track = current_url.split('#')[0].split('?')[0] !== previous_tracked_url.split('#')[0].split('?')[0];\n }\n\n if (should_track) {\n var tracked = this.track_pageview();\n if (tracked) {\n previous_tracked_url = current_url;\n }\n }\n }.bind(this));\n }\n};\n\n/**\n * _prepare_callback() should be called by callers of _send_request for use\n * as the callback argument.\n *\n * If there is no callback, this returns null.\n * If we are going to make XHR/XDR requests, this returns a function.\n * If we are going to use script tags, this returns a string to use as the\n * callback GET param.\n */\nMixpanelLib.prototype._prepare_callback = function(callback, data) {\n if (_.isUndefined(callback)) {\n return null;\n }\n\n if (USE_XHR) {\n var callback_function = function(response) {\n callback(response, data);\n };\n return callback_function;\n } else {\n // if the user gives us a callback, we store as a random\n // property on this instances jsc function and update our\n // callback string to reflect that.\n var jsc = this['_jsc'];\n var randomized_cb = '' + Math.floor(Math.random() * 100000000);\n var callback_string = this.get_config('callback_fn') + '[' + randomized_cb + ']';\n jsc[randomized_cb] = function(response) {\n delete jsc[randomized_cb];\n callback(response, data);\n };\n return callback_string;\n }\n};\n\nMixpanelLib.prototype._send_request = function(url, data, options, callback) {\n var succeeded = true;\n\n if (ENQUEUE_REQUESTS) {\n this.__request_queue.push(arguments);\n return succeeded;\n }\n\n var DEFAULT_OPTIONS = {\n method: this.get_config('api_method'),\n transport: this.get_config('api_transport'),\n verbose: this.get_config('verbose')\n };\n var body_data = null;\n\n if (!callback && (_.isFunction(options) || typeof options === 'string')) {\n callback = options;\n options = null;\n }\n options = _.extend(DEFAULT_OPTIONS, options || {});\n if (!USE_XHR) {\n options.method = 'GET';\n }\n var use_post = options.method === 'POST';\n var use_sendBeacon = sendBeacon && use_post && options.transport.toLowerCase() === 'sendbeacon';\n\n // needed to correctly format responses\n var verbose_mode = options.verbose;\n if (data['verbose']) { verbose_mode = true; }\n\n if (this.get_config('test')) { data['test'] = 1; }\n if (verbose_mode) { data['verbose'] = 1; }\n if (this.get_config('img')) { data['img'] = 1; }\n if (!USE_XHR) {\n if (callback) {\n data['callback'] = callback;\n } else if (verbose_mode || this.get_config('test')) {\n // Verbose output (from verbose mode, or an error in test mode) is a json blob,\n // which by itself is not valid javascript. Without a callback, this verbose output will\n // cause an error when returned via jsonp, so we force a no-op callback param.\n // See the ECMA script spec: http://www.ecma-international.org/ecma-262/5.1/#sec-12.4\n data['callback'] = '(function(){})';\n }\n }\n\n data['ip'] = this.get_config('ip')?1:0;\n data['_'] = new Date().getTime().toString();\n\n if (use_post) {\n body_data = 'data=' + encodeURIComponent(data['data']);\n delete data['data'];\n }\n\n url += '?' + _.HTTPBuildQuery(data);\n\n var lib = this;\n if ('img' in data) {\n var img = document$1.createElement('img');\n img.src = url;\n document$1.body.appendChild(img);\n } else if (use_sendBeacon) {\n try {\n succeeded = sendBeacon(url, body_data);\n } catch (e) {\n lib.report_error(e);\n succeeded = false;\n }\n try {\n if (callback) {\n callback(succeeded ? 1 : 0);\n }\n } catch (e) {\n lib.report_error(e);\n }\n } else if (USE_XHR) {\n try {\n var req = new XMLHttpRequest();\n req.open(options.method, url, true);\n\n var headers = this.get_config('xhr_headers');\n if (use_post) {\n headers['Content-Type'] = 'application/x-www-form-urlencoded';\n }\n _.each(headers, function(headerValue, headerName) {\n req.setRequestHeader(headerName, headerValue);\n });\n\n if (options.timeout_ms && typeof req.timeout !== 'undefined') {\n req.timeout = options.timeout_ms;\n var start_time = new Date().getTime();\n }\n\n // send the mp_optout cookie\n // withCredentials cannot be modified until after calling .open on Android and Mobile Safari\n req.withCredentials = true;\n req.onreadystatechange = function () {\n if (req.readyState === 4) { // XMLHttpRequest.DONE == 4, except in safari 4\n if (req.status === 200) {\n if (callback) {\n if (verbose_mode) {\n var response;\n try {\n response = _.JSONDecode(req.responseText);\n } catch (e) {\n lib.report_error(e);\n if (options.ignore_json_errors) {\n response = req.responseText;\n } else {\n return;\n }\n }\n callback(response);\n } else {\n callback(Number(req.responseText));\n }\n }\n } else {\n var error;\n if (\n req.timeout &&\n !req.status &&\n new Date().getTime() - start_time >= req.timeout\n ) {\n error = 'timeout';\n } else {\n error = 'Bad HTTP status: ' + req.status + ' ' + req.statusText;\n }\n lib.report_error(error);\n if (callback) {\n if (verbose_mode) {\n var response_headers = req['responseHeaders'] || {};\n callback({status: 0, httpStatusCode: req['status'], error: error, retryAfter: response_headers['Retry-After']});\n } else {\n callback(0);\n }\n }\n }\n }\n };\n req.send(body_data);\n } catch (e) {\n lib.report_error(e);\n succeeded = false;\n }\n } else {\n var script = document$1.createElement('script');\n script.type = 'text/javascript';\n script.async = true;\n script.defer = true;\n script.src = url;\n var s = document$1.getElementsByTagName('script')[0];\n s.parentNode.insertBefore(script, s);\n }\n\n return succeeded;\n};\n\n/**\n * _execute_array() deals with processing any mixpanel function\n * calls that were called before the Mixpanel library were loaded\n * (and are thus stored in an array so they can be called later)\n *\n * Note: we fire off all the mixpanel function calls && user defined\n * functions BEFORE we fire off mixpanel tracking calls. This is so\n * identify/register/set_config calls can properly modify early\n * tracking calls.\n *\n * @param {Array} array\n */\nMixpanelLib.prototype._execute_array = function(array) {\n var fn_name, alias_calls = [], other_calls = [], tracking_calls = [];\n _.each(array, function(item) {\n if (item) {\n fn_name = item[0];\n if (_.isArray(fn_name)) {\n tracking_calls.push(item); // chained call e.g. mixpanel.get_group().set()\n } else if (typeof(item) === 'function') {\n item.call(this);\n } else if (_.isArray(item) && fn_name === 'alias') {\n alias_calls.push(item);\n } else if (_.isArray(item) && fn_name.indexOf('track') !== -1 && typeof(this[fn_name]) === 'function') {\n tracking_calls.push(item);\n } else {\n other_calls.push(item);\n }\n }\n }, this);\n\n var execute = function(calls, context) {\n _.each(calls, function(item) {\n if (_.isArray(item[0])) {\n // chained call\n var caller = context;\n _.each(item, function(call) {\n caller = caller[call[0]].apply(caller, call.slice(1));\n });\n } else {\n this[item[0]].apply(this, item.slice(1));\n }\n }, context);\n };\n\n execute(alias_calls, this);\n execute(other_calls, this);\n execute(tracking_calls, this);\n};\n\n// request queueing utils\n\nMixpanelLib.prototype.are_batchers_initialized = function() {\n return !!this.request_batchers.events;\n};\n\nMixpanelLib.prototype.get_batcher_configs = function() {\n var queue_prefix = '__mpq_' + this.get_config('token');\n var api_routes = this.get_config('api_routes');\n this._batcher_configs = this._batcher_configs || {\n events: {type: 'events', endpoint: '/' + api_routes['track'], queue_key: queue_prefix + '_ev'},\n people: {type: 'people', endpoint: '/' + api_routes['engage'], queue_key: queue_prefix + '_pp'},\n groups: {type: 'groups', endpoint: '/' + api_routes['groups'], queue_key: queue_prefix + '_gr'}\n };\n return this._batcher_configs;\n};\n\nMixpanelLib.prototype.init_batchers = function() {\n if (!this.are_batchers_initialized()) {\n var batcher_for = _.bind(function(attrs) {\n return new RequestBatcher(\n attrs.queue_key,\n {\n libConfig: this['config'],\n errorReporter: this.get_config('error_reporter'),\n sendRequestFunc: _.bind(function(data, options, cb) {\n this._send_request(\n this.get_config('api_host') + attrs.endpoint,\n this._encode_data_for_request(data),\n options,\n this._prepare_callback(cb, data)\n );\n }, this),\n beforeSendHook: _.bind(function(item) {\n return this._run_hook('before_send_' + attrs.type, item);\n }, this),\n stopAllBatchingFunc: _.bind(this.stop_batch_senders, this),\n usePersistence: true\n }\n );\n }, this);\n var batcher_configs = this.get_batcher_configs();\n this.request_batchers = {\n events: batcher_for(batcher_configs.events),\n people: batcher_for(batcher_configs.people),\n groups: batcher_for(batcher_configs.groups)\n };\n }\n if (this.get_config('batch_autostart')) {\n this.start_batch_senders();\n }\n};\n\nMixpanelLib.prototype.start_batch_senders = function() {\n this._batchers_were_started = true;\n if (this.are_batchers_initialized()) {\n this._batch_requests = true;\n _.each(this.request_batchers, function(batcher) {\n batcher.start();\n });\n }\n};\n\nMixpanelLib.prototype.stop_batch_senders = function() {\n this._batch_requests = false;\n _.each(this.request_batchers, function(batcher) {\n batcher.stop();\n batcher.clear();\n });\n};\n\n/**\n * push() keeps the standard async-array-push\n * behavior around after the lib is loaded.\n * This is only useful for external integrations that\n * do not wish to rely on our convenience methods\n * (created in the snippet).\n *\n * ### Usage:\n * mixpanel.push(['register', { a: 'b' }]);\n *\n * @param {Array} item A [function_name, args...] array to be executed\n */\nMixpanelLib.prototype.push = function(item) {\n this._execute_array([item]);\n};\n\n/**\n * Disable events on the Mixpanel object. If passed no arguments,\n * this function disables tracking of any event. If passed an\n * array of event names, those events will be disabled, but other\n * events will continue to be tracked.\n *\n * Note: this function does not stop other mixpanel functions from\n * firing, such as register() or people.set().\n *\n * @param {Array} [events] An array of event names to disable\n */\nMixpanelLib.prototype.disable = function(events) {\n if (typeof(events) === 'undefined') {\n this._flags.disable_all_events = true;\n } else {\n this.__disabled_events = this.__disabled_events.concat(events);\n }\n};\n\nMixpanelLib.prototype._encode_data_for_request = function(data) {\n var encoded_data = _.JSONEncode(data);\n if (this.get_config('api_payload_format') === PAYLOAD_TYPE_BASE64) {\n encoded_data = _.base64Encode(encoded_data);\n }\n return {'data': encoded_data};\n};\n\n// internal method for handling track vs batch-enqueue logic\nMixpanelLib.prototype._track_or_batch = function(options, callback) {\n var truncated_data = _.truncate(options.data, 255);\n var endpoint = options.endpoint;\n var batcher = options.batcher;\n var should_send_immediately = options.should_send_immediately;\n var send_request_options = options.send_request_options || {};\n callback = callback || NOOP_FUNC;\n\n var request_enqueued_or_initiated = true;\n var send_request_immediately = _.bind(function() {\n if (!send_request_options.skip_hooks) {\n truncated_data = this._run_hook('before_send_' + options.type, truncated_data);\n }\n if (truncated_data) {\n console$1.log('MIXPANEL REQUEST:');\n console$1.log(truncated_data);\n return this._send_request(\n endpoint,\n this._encode_data_for_request(truncated_data),\n send_request_options,\n this._prepare_callback(callback, truncated_data)\n );\n } else {\n return null;\n }\n }, this);\n\n if (this._batch_requests && !should_send_immediately) {\n batcher.enqueue(truncated_data, function(succeeded) {\n if (succeeded) {\n callback(1, truncated_data);\n } else {\n send_request_immediately();\n }\n });\n } else {\n request_enqueued_or_initiated = send_request_immediately();\n }\n\n return request_enqueued_or_initiated && truncated_data;\n};\n\n/**\n * Track an event. This is the most important and\n * frequently used Mixpanel function.\n *\n * ### Usage:\n *\n * // track an event named 'Registered'\n * mixpanel.track('Registered', {'Gender': 'Male', 'Age': 21});\n *\n * // track an event using navigator.sendBeacon\n * mixpanel.track('Left page', {'duration_seconds': 35}, {transport: 'sendBeacon'});\n *\n * To track link clicks or form submissions, see track_links() or track_forms().\n *\n * @param {String} event_name The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', 'Item Purchased', etc.\n * @param {Object} [properties] A set of properties to include with the event you're sending. These describe the user who did the event or details about the event itself.\n * @param {Object} [options] Optional configuration for this track request.\n * @param {String} [options.transport] Transport method for network request ('xhr' or 'sendBeacon').\n * @param {Boolean} [options.send_immediately] Whether to bypass batching/queueing and send track request immediately.\n * @param {Function} [callback] If provided, the callback function will be called after tracking the event.\n * @returns {Boolean|Object} If the tracking request was successfully initiated/queued, an object\n * with the tracking payload sent to the API server is returned; otherwise false.\n */\nMixpanelLib.prototype.track = addOptOutCheckMixpanelLib(function(event_name, properties, options, callback) {\n if (!callback && typeof options === 'function') {\n callback = options;\n options = null;\n }\n options = options || {};\n var transport = options['transport']; // external API, don't minify 'transport' prop\n if (transport) {\n options.transport = transport; // 'transport' prop name can be minified internally\n }\n var should_send_immediately = options['send_immediately'];\n if (typeof callback !== 'function') {\n callback = NOOP_FUNC;\n }\n\n if (_.isUndefined(event_name)) {\n this.report_error('No event name provided to mixpanel.track');\n return;\n }\n\n if (this._event_is_disabled(event_name)) {\n callback(0);\n return;\n }\n\n // set defaults\n properties = _.extend({}, properties);\n properties['token'] = this.get_config('token');\n\n // set $duration if time_event was previously called for this event\n var start_timestamp = this['persistence'].remove_event_timer(event_name);\n if (!_.isUndefined(start_timestamp)) {\n var duration_in_ms = new Date().getTime() - start_timestamp;\n properties['$duration'] = parseFloat((duration_in_ms / 1000).toFixed(3));\n }\n\n this._set_default_superprops();\n\n var marketing_properties = this.get_config('track_marketing')\n ? _.info.marketingParams()\n : {};\n\n // note: extend writes to the first object, so lets make sure we\n // don't write to the persistence properties object and info\n // properties object by passing in a new object\n\n // update properties with pageview info and super-properties\n properties = _.extend(\n {},\n _.info.properties({'mp_loader': this.get_config('mp_loader')}),\n marketing_properties,\n this['persistence'].properties(),\n this.unpersisted_superprops,\n this.get_session_recording_properties(),\n properties\n );\n\n var property_blacklist = this.get_config('property_blacklist');\n if (_.isArray(property_blacklist)) {\n _.each(property_blacklist, function(blacklisted_prop) {\n delete properties[blacklisted_prop];\n });\n } else {\n this.report_error('Invalid value for property_blacklist config: ' + property_blacklist);\n }\n\n var data = {\n 'event': event_name,\n 'properties': properties\n };\n var ret = this._track_or_batch({\n type: 'events',\n data: data,\n endpoint: this.get_config('api_host') + '/' + this.get_config('api_routes')['track'],\n batcher: this.request_batchers.events,\n should_send_immediately: should_send_immediately,\n send_request_options: options\n }, callback);\n\n return ret;\n});\n\n/**\n * Register the current user into one/many groups.\n *\n * ### Usage:\n *\n * mixpanel.set_group('company', ['mixpanel', 'google']) // an array of IDs\n * mixpanel.set_group('company', 'mixpanel')\n * mixpanel.set_group('company', 128746312)\n *\n * @param {String} group_key Group key\n * @param {Array|String|Number} group_ids An array of group IDs, or a singular group ID\n * @param {Function} [callback] If provided, the callback will be called after tracking the event.\n *\n */\nMixpanelLib.prototype.set_group = addOptOutCheckMixpanelLib(function(group_key, group_ids, callback) {\n if (!_.isArray(group_ids)) {\n group_ids = [group_ids];\n }\n var prop = {};\n prop[group_key] = group_ids;\n this.register(prop);\n return this['people'].set(group_key, group_ids, callback);\n});\n\n/**\n * Add a new group for this user.\n *\n * ### Usage:\n *\n * mixpanel.add_group('company', 'mixpanel')\n *\n * @param {String} group_key Group key\n * @param {*} group_id A valid Mixpanel property type\n * @param {Function} [callback] If provided, the callback will be called after tracking the event.\n */\nMixpanelLib.prototype.add_group = addOptOutCheckMixpanelLib(function(group_key, group_id, callback) {\n var old_values = this.get_property(group_key);\n var prop = {};\n if (old_values === undefined) {\n prop[group_key] = [group_id];\n this.register(prop);\n } else {\n if (old_values.indexOf(group_id) === -1) {\n old_values.push(group_id);\n prop[group_key] = old_values;\n this.register(prop);\n }\n }\n return this['people'].union(group_key, group_id, callback);\n});\n\n/**\n * Remove a group from this user.\n *\n * ### Usage:\n *\n * mixpanel.remove_group('company', 'mixpanel')\n *\n * @param {String} group_key Group key\n * @param {*} group_id A valid Mixpanel property type\n * @param {Function} [callback] If provided, the callback will be called after tracking the event.\n */\nMixpanelLib.prototype.remove_group = addOptOutCheckMixpanelLib(function(group_key, group_id, callback) {\n var old_value = this.get_property(group_key);\n // if the value doesn't exist, the persistent store is unchanged\n if (old_value !== undefined) {\n var idx = old_value.indexOf(group_id);\n if (idx > -1) {\n old_value.splice(idx, 1);\n this.register({group_key: old_value});\n }\n if (old_value.length === 0) {\n this.unregister(group_key);\n }\n }\n return this['people'].remove(group_key, group_id, callback);\n});\n\n/**\n * Track an event with specific groups.\n *\n * ### Usage:\n *\n * mixpanel.track_with_groups('purchase', {'product': 'iphone'}, {'University': ['UCB', 'UCLA']})\n *\n * @param {String} event_name The name of the event (see `mixpanel.track()`)\n * @param {Object=} properties A set of properties to include with the event you're sending (see `mixpanel.track()`)\n * @param {Object=} groups An object mapping group name keys to one or more values\n * @param {Function} [callback] If provided, the callback will be called after tracking the event.\n */\nMixpanelLib.prototype.track_with_groups = addOptOutCheckMixpanelLib(function(event_name, properties, groups, callback) {\n var tracking_props = _.extend({}, properties || {});\n _.each(groups, function(v, k) {\n if (v !== null && v !== undefined) {\n tracking_props[k] = v;\n }\n });\n return this.track(event_name, tracking_props, callback);\n});\n\nMixpanelLib.prototype._create_map_key = function (group_key, group_id) {\n return group_key + '_' + JSON.stringify(group_id);\n};\n\nMixpanelLib.prototype._remove_group_from_cache = function (group_key, group_id) {\n delete this._cached_groups[this._create_map_key(group_key, group_id)];\n};\n\n/**\n * Look up reference to a Mixpanel group\n *\n * ### Usage:\n *\n * mixpanel.get_group(group_key, group_id)\n *\n * @param {String} group_key Group key\n * @param {Object} group_id A valid Mixpanel property type\n * @returns {Object} A MixpanelGroup identifier\n */\nMixpanelLib.prototype.get_group = function (group_key, group_id) {\n var map_key = this._create_map_key(group_key, group_id);\n var group = this._cached_groups[map_key];\n if (group === undefined || group._group_key !== group_key || group._group_id !== group_id) {\n group = new MixpanelGroup();\n group._init(this, group_key, group_id);\n this._cached_groups[map_key] = group;\n }\n return group;\n};\n\n/**\n * Track a default Mixpanel page view event, which includes extra default event properties to\n * improve page view data.\n *\n * ### Usage:\n *\n * // track a default $mp_web_page_view event\n * mixpanel.track_pageview();\n *\n * // track a page view event with additional event properties\n * mixpanel.track_pageview({'ab_test_variant': 'card-layout-b'});\n *\n * // example approach to track page views on different page types as event properties\n * mixpanel.track_pageview({'page': 'pricing'});\n * mixpanel.track_pageview({'page': 'homepage'});\n *\n * // UNCOMMON: Tracking a page view event with a custom event_name option. NOT expected to be used for\n * // individual pages on the same site or product. Use cases for custom event_name may be page\n * // views on different products or internal applications that are considered completely separate\n * mixpanel.track_pageview({'page': 'customer-search'}, {'event_name': '[internal] Admin Page View'});\n *\n * ### Notes:\n *\n * The `config.track_pageview` option for mixpanel.init()\n * may be turned on for tracking page loads automatically.\n *\n * // track only page loads\n * mixpanel.init(PROJECT_TOKEN, {track_pageview: true});\n *\n * // track when the URL changes in any manner\n * mixpanel.init(PROJECT_TOKEN, {track_pageview: 'full-url'});\n *\n * // track when the URL changes, ignoring any changes in the hash part\n * mixpanel.init(PROJECT_TOKEN, {track_pageview: 'url-with-path-and-query-string'});\n *\n * // track when the path changes, ignoring any query parameter or hash changes\n * mixpanel.init(PROJECT_TOKEN, {track_pageview: 'url-with-path'});\n *\n * @param {Object} [properties] An optional set of additional properties to send with the page view event\n * @param {Object} [options] Page view tracking options\n * @param {String} [options.event_name] - Alternate name for the tracking event\n * @returns {Boolean|Object} If the tracking request was successfully initiated/queued, an object\n * with the tracking payload sent to the API server is returned; otherwise false.\n */\nMixpanelLib.prototype.track_pageview = addOptOutCheckMixpanelLib(function(properties, options) {\n if (typeof properties !== 'object') {\n properties = {};\n }\n options = options || {};\n var event_name = options['event_name'] || '$mp_web_page_view';\n\n var default_page_properties = _.extend(\n _.info.mpPageViewProperties(),\n _.info.campaignParams(),\n _.info.clickParams()\n );\n\n var event_properties = _.extend(\n {},\n default_page_properties,\n properties\n );\n\n return this.track(event_name, event_properties);\n});\n\n/**\n * Track clicks on a set of document elements. Selector must be a\n * valid query. Elements must exist on the page at the time track_links is called.\n *\n * ### Usage:\n *\n * // track click for link id #nav\n * mixpanel.track_links('#nav', 'Clicked Nav Link');\n *\n * ### Notes:\n *\n * This function will wait up to 300 ms for the Mixpanel\n * servers to respond. If they have not responded by that time\n * it will head to the link without ensuring that your event\n * has been tracked. To configure this timeout please see the\n * set_config() documentation below.\n *\n * If you pass a function in as the properties argument, the\n * function will receive the DOMElement that triggered the\n * event as an argument. You are expected to return an object\n * from the function; any properties defined on this object\n * will be sent to mixpanel as event properties.\n *\n * @type {Function}\n * @param {Object|String} query A valid DOM query, element or jQuery-esque list\n * @param {String} event_name The name of the event to track\n * @param {Object|Function} [properties] A properties object or function that returns a dictionary of properties when passed a DOMElement\n */\nMixpanelLib.prototype.track_links = function() {\n return this._track_dom.call(this, LinkTracker, arguments);\n};\n\n/**\n * Track form submissions. Selector must be a valid query.\n *\n * ### Usage:\n *\n * // track submission for form id 'register'\n * mixpanel.track_forms('#register', 'Created Account');\n *\n * ### Notes:\n *\n * This function will wait up to 300 ms for the mixpanel\n * servers to respond, if they have not responded by that time\n * it will head to the link without ensuring that your event\n * has been tracked. To configure this timeout please see the\n * set_config() documentation below.\n *\n * If you pass a function in as the properties argument, the\n * function will receive the DOMElement that triggered the\n * event as an argument. You are expected to return an object\n * from the function; any properties defined on this object\n * will be sent to mixpanel as event properties.\n *\n * @type {Function}\n * @param {Object|String} query A valid DOM query, element or jQuery-esque list\n * @param {String} event_name The name of the event to track\n * @param {Object|Function} [properties] This can be a set of properties, or a function that returns a set of properties after being passed a DOMElement\n */\nMixpanelLib.prototype.track_forms = function() {\n return this._track_dom.call(this, FormTracker, arguments);\n};\n\n/**\n * Time an event by including the time between this call and a\n * later 'track' call for the same event in the properties sent\n * with the event.\n *\n * ### Usage:\n *\n * // time an event named 'Registered'\n * mixpanel.time_event('Registered');\n * mixpanel.track('Registered', {'Gender': 'Male', 'Age': 21});\n *\n * When called for a particular event name, the next track call for that event\n * name will include the elapsed time between the 'time_event' and 'track'\n * calls. This value is stored as seconds in the '$duration' property.\n *\n * @param {String} event_name The name of the event.\n */\nMixpanelLib.prototype.time_event = function(event_name) {\n if (_.isUndefined(event_name)) {\n this.report_error('No event name provided to mixpanel.time_event');\n return;\n }\n\n if (this._event_is_disabled(event_name)) {\n return;\n }\n\n this['persistence'].set_event_timer(event_name, new Date().getTime());\n};\n\nvar REGISTER_DEFAULTS = {\n 'persistent': true\n};\n/**\n * Helper to parse options param for register methods, maintaining\n * legacy support for plain \"days\" param instead of options object\n * @param {Number|Object} [days_or_options] 'days' option (Number), or Options object for register methods\n * @returns {Object} options object\n */\nvar options_for_register = function(days_or_options) {\n var options;\n if (_.isObject(days_or_options)) {\n options = days_or_options;\n } else if (!_.isUndefined(days_or_options)) {\n options = {'days': days_or_options};\n } else {\n options = {};\n }\n return _.extend({}, REGISTER_DEFAULTS, options);\n};\n\n/**\n * Register a set of super properties, which are included with all\n * events. This will overwrite previous super property values.\n *\n * ### Usage:\n *\n * // register 'Gender' as a super property\n * mixpanel.register({'Gender': 'Female'});\n *\n * // register several super properties when a user signs up\n * mixpanel.register({\n * 'Email': 'jdoe@example.com',\n * 'Account Type': 'Free'\n * });\n *\n * // register only for the current pageload\n * mixpanel.register({'Name': 'Pat'}, {persistent: false});\n *\n * @param {Object} properties An associative array of properties to store about the user\n * @param {Number|Object} [days_or_options] Options object or number of days since the user's last visit to store the super properties (only valid for persisted props)\n * @param {boolean} [days_or_options.days] - number of days since the user's last visit to store the super properties (only valid for persisted props)\n * @param {boolean} [days_or_options.persistent=true] - whether to put in persistent storage (cookie/localStorage)\n */\nMixpanelLib.prototype.register = function(props, days_or_options) {\n var options = options_for_register(days_or_options);\n if (options['persistent']) {\n this['persistence'].register(props, options['days']);\n } else {\n _.extend(this.unpersisted_superprops, props);\n }\n};\n\n/**\n * Register a set of super properties only once. This will not\n * overwrite previous super property values, unlike register().\n *\n * ### Usage:\n *\n * // register a super property for the first time only\n * mixpanel.register_once({\n * 'First Login Date': new Date().toISOString()\n * });\n *\n * // register once, only for the current pageload\n * mixpanel.register_once({\n * 'First interaction time': new Date().toISOString()\n * }, 'None', {persistent: false});\n *\n * ### Notes:\n *\n * If default_value is specified, current super properties\n * with that value will be overwritten.\n *\n * @param {Object} properties An associative array of properties to store about the user\n * @param {*} [default_value] Value to override if already set in super properties (ex: 'False') Default: 'None'\n * @param {Number|Object} [days_or_options] Options object or number of days since the user's last visit to store the super properties (only valid for persisted props)\n * @param {boolean} [days_or_options.days] - number of days since the user's last visit to store the super properties (only valid for persisted props)\n * @param {boolean} [days_or_options.persistent=true] - whether to put in persistent storage (cookie/localStorage)\n */\nMixpanelLib.prototype.register_once = function(props, default_value, days_or_options) {\n var options = options_for_register(days_or_options);\n if (options['persistent']) {\n this['persistence'].register_once(props, default_value, options['days']);\n } else {\n if (typeof(default_value) === 'undefined') {\n default_value = 'None';\n }\n _.each(props, function(val, prop) {\n if (!this.unpersisted_superprops.hasOwnProperty(prop) || this.unpersisted_superprops[prop] === default_value) {\n this.unpersisted_superprops[prop] = val;\n }\n }, this);\n }\n};\n\n/**\n * Delete a super property stored with the current user.\n *\n * @param {String} property The name of the super property to remove\n * @param {Object} [options]\n * @param {boolean} [options.persistent=true] - whether to look in persistent storage (cookie/localStorage)\n */\nMixpanelLib.prototype.unregister = function(property, options) {\n options = options_for_register(options);\n if (options['persistent']) {\n this['persistence'].unregister(property);\n } else {\n delete this.unpersisted_superprops[property];\n }\n};\n\nMixpanelLib.prototype._register_single = function(prop, value) {\n var props = {};\n props[prop] = value;\n this.register(props);\n};\n\n/**\n * Identify a user with a unique ID to track user activity across\n * devices, tie a user to their events, and create a user profile.\n * If you never call this method, unique visitors are tracked using\n * a UUID generated the first time they visit the site.\n *\n * Call identify when you know the identity of the current user,\n * typically after login or signup. We recommend against using\n * identify for anonymous visitors to your site.\n *\n * ### Notes:\n * If your project has\n * ID Merge\n * enabled, the identify method will connect pre- and\n * post-authentication events when appropriate.\n *\n * If your project does not have ID Merge enabled, identify will\n * change the user's local distinct_id to the unique ID you pass.\n * Events tracked prior to authentication will not be connected\n * to the same user identity. If ID Merge is disabled, alias can\n * be used to connect pre- and post-registration events.\n *\n * @param {String} [unique_id] A string that uniquely identifies a user. If not provided, the distinct_id currently in the persistent store (cookie or localStorage) will be used.\n */\nMixpanelLib.prototype.identify = function(\n new_distinct_id, _set_callback, _add_callback, _append_callback, _set_once_callback, _union_callback, _unset_callback, _remove_callback\n) {\n // Optional Parameters\n // _set_callback:function A callback to be run if and when the People set queue is flushed\n // _add_callback:function A callback to be run if and when the People add queue is flushed\n // _append_callback:function A callback to be run if and when the People append queue is flushed\n // _set_once_callback:function A callback to be run if and when the People set_once queue is flushed\n // _union_callback:function A callback to be run if and when the People union queue is flushed\n // _unset_callback:function A callback to be run if and when the People unset queue is flushed\n\n var previous_distinct_id = this.get_distinct_id();\n if (new_distinct_id && previous_distinct_id !== new_distinct_id) {\n // we allow the following condition if previous distinct_id is same as new_distinct_id\n // so that you can force flush people updates for anonymous profiles.\n if (typeof new_distinct_id === 'string' && new_distinct_id.indexOf(DEVICE_ID_PREFIX) === 0) {\n this.report_error('distinct_id cannot have $device: prefix');\n return -1;\n }\n this.register({'$user_id': new_distinct_id});\n }\n\n if (!this.get_property('$device_id')) {\n // The persisted distinct id might not actually be a device id at all\n // it might be a distinct id of the user from before\n var device_id = previous_distinct_id;\n this.register_once({\n '$had_persisted_distinct_id': true,\n '$device_id': device_id\n }, '');\n }\n\n // identify only changes the distinct id if it doesn't match either the existing or the alias;\n // if it's new, blow away the alias as well.\n if (new_distinct_id !== previous_distinct_id && new_distinct_id !== this.get_property(ALIAS_ID_KEY)) {\n this.unregister(ALIAS_ID_KEY);\n this.register({'distinct_id': new_distinct_id});\n }\n this._flags.identify_called = true;\n // Flush any queued up people requests\n this['people']._flush(_set_callback, _add_callback, _append_callback, _set_once_callback, _union_callback, _unset_callback, _remove_callback);\n\n // send an $identify event any time the distinct_id is changing - logic on the server\n // will determine whether or not to do anything with it.\n if (new_distinct_id !== previous_distinct_id) {\n this.track('$identify', {\n 'distinct_id': new_distinct_id,\n '$anon_distinct_id': previous_distinct_id\n }, {skip_hooks: true});\n }\n};\n\n/**\n * Clears super properties and generates a new random distinct_id for this instance.\n * Useful for clearing data when a user logs out.\n */\nMixpanelLib.prototype.reset = function() {\n this['persistence'].clear();\n this._flags.identify_called = false;\n var uuid = _.UUID();\n this.register_once({\n 'distinct_id': DEVICE_ID_PREFIX + uuid,\n '$device_id': uuid\n }, '');\n};\n\n/**\n * Returns the current distinct id of the user. This is either the id automatically\n * generated by the library or the id that has been passed by a call to identify().\n *\n * ### Notes:\n *\n * get_distinct_id() can only be called after the Mixpanel library has finished loading.\n * init() has a loaded function available to handle this automatically. For example:\n *\n * // set distinct_id after the mixpanel library has loaded\n * mixpanel.init('YOUR PROJECT TOKEN', {\n * loaded: function(mixpanel) {\n * distinct_id = mixpanel.get_distinct_id();\n * }\n * });\n */\nMixpanelLib.prototype.get_distinct_id = function() {\n return this.get_property('distinct_id');\n};\n\n/**\n * The alias method creates an alias which Mixpanel will use to\n * remap one id to another. Multiple aliases can point to the\n * same identifier.\n *\n * The following is a valid use of alias:\n *\n * mixpanel.alias('new_id', 'existing_id');\n * // You can add multiple id aliases to the existing ID\n * mixpanel.alias('newer_id', 'existing_id');\n *\n * Aliases can also be chained - the following is a valid example:\n *\n * mixpanel.alias('new_id', 'existing_id');\n * // chain newer_id - new_id - existing_id\n * mixpanel.alias('newer_id', 'new_id');\n *\n * Aliases cannot point to multiple identifiers - the following\n * example will not work:\n *\n * mixpanel.alias('new_id', 'existing_id');\n * // this is invalid as 'new_id' already points to 'existing_id'\n * mixpanel.alias('new_id', 'newer_id');\n *\n * ### Notes:\n *\n * If your project does not have\n * ID Merge\n * enabled, the best practice is to call alias once when a unique\n * ID is first created for a user (e.g., when a user first registers\n * for an account). Do not use alias multiple times for a single\n * user without ID Merge enabled.\n *\n * @param {String} alias A unique identifier that you want to use for this user in the future.\n * @param {String} [original] The current identifier being used for this user.\n */\nMixpanelLib.prototype.alias = function(alias, original) {\n // If the $people_distinct_id key exists in persistence, there has been a previous\n // mixpanel.people.identify() call made for this user. It is VERY BAD to make an alias with\n // this ID, as it will duplicate users.\n if (alias === this.get_property(PEOPLE_DISTINCT_ID_KEY)) {\n this.report_error('Attempting to create alias for existing People user - aborting.');\n return -2;\n }\n\n var _this = this;\n if (_.isUndefined(original)) {\n original = this.get_distinct_id();\n }\n if (alias !== original) {\n this._register_single(ALIAS_ID_KEY, alias);\n return this.track('$create_alias', {\n 'alias': alias,\n 'distinct_id': original\n }, {\n skip_hooks: true\n }, function() {\n // Flush the people queue\n _this.identify(alias);\n });\n } else {\n this.report_error('alias matches current distinct_id - skipping api call.');\n this.identify(alias);\n return -1;\n }\n};\n\n/**\n * Provide a string to recognize the user by. The string passed to\n * this method will appear in the Mixpanel Streams product rather\n * than an automatically generated name. Name tags do not have to\n * be unique.\n *\n * This value will only be included in Streams data.\n *\n * @param {String} name_tag A human readable name for the user\n * @deprecated\n */\nMixpanelLib.prototype.name_tag = function(name_tag) {\n this._register_single('mp_name_tag', name_tag);\n};\n\n/**\n * Update the configuration of a mixpanel library instance.\n *\n * The default config is:\n *\n * {\n * // host for requests (customizable for e.g. a local proxy)\n * api_host: 'https://api-js.mixpanel.com',\n *\n * // endpoints for different types of requests\n * api_routes: {\n * track: 'track/',\n * engage: 'engage/',\n * groups: 'groups/',\n * }\n *\n * // HTTP method for tracking requests\n * api_method: 'POST'\n *\n * // transport for sending requests ('XHR' or 'sendBeacon')\n * // NB: sendBeacon should only be used for scenarios such as\n * // page unload where a \"best-effort\" attempt to send is\n * // acceptable; the sendBeacon API does not support callbacks\n * // or any way to know the result of the request. Mixpanel\n * // tracking via sendBeacon will not support any event-\n * // batching or retry mechanisms.\n * api_transport: 'XHR'\n *\n * // request-batching/queueing/retry\n * batch_requests: true,\n *\n * // maximum number of events/updates to send in a single\n * // network request\n * batch_size: 50,\n *\n * // milliseconds to wait between sending batch requests\n * batch_flush_interval_ms: 5000,\n *\n * // milliseconds to wait for network responses to batch requests\n * // before they are considered timed-out and retried\n * batch_request_timeout_ms: 90000,\n *\n * // override value for cookie domain, only useful for ensuring\n * // correct cross-subdomain cookies on unusual domains like\n * // subdomain.mainsite.avocat.fr; NB this cannot be used to\n * // set cookies on a different domain than the current origin\n * cookie_domain: ''\n *\n * // super properties cookie expiration (in days)\n * cookie_expiration: 365\n *\n * // if true, cookie will be set with SameSite=None; Secure\n * // this is only useful in special situations, like embedded\n * // 3rd-party iframes that set up a Mixpanel instance\n * cross_site_cookie: false\n *\n * // super properties span subdomains\n * cross_subdomain_cookie: true\n *\n * // debug mode\n * debug: false\n *\n * // if this is true, the mixpanel cookie or localStorage entry\n * // will be deleted, and no user persistence will take place\n * disable_persistence: false\n *\n * // if this is true, Mixpanel will automatically determine\n * // City, Region and Country data using the IP address of\n * //the client\n * ip: true\n *\n * // opt users out of tracking by this Mixpanel instance by default\n * opt_out_tracking_by_default: false\n *\n * // opt users out of browser data storage by this Mixpanel instance by default\n * opt_out_persistence_by_default: false\n *\n * // persistence mechanism used by opt-in/opt-out methods - cookie\n * // or localStorage - falls back to cookie if localStorage is unavailable\n * opt_out_tracking_persistence_type: 'localStorage'\n *\n * // customize the name of cookie/localStorage set by opt-in/opt-out methods\n * opt_out_tracking_cookie_prefix: null\n *\n * // type of persistent store for super properties (cookie/\n * // localStorage) if set to 'localStorage', any existing\n * // mixpanel cookie value with the same persistence_name\n * // will be transferred to localStorage and deleted\n * persistence: 'cookie'\n *\n * // name for super properties persistent store\n * persistence_name: ''\n *\n * // names of properties/superproperties which should never\n * // be sent with track() calls\n * property_blacklist: []\n *\n * // if this is true, mixpanel cookies will be marked as\n * // secure, meaning they will only be transmitted over https\n * secure_cookie: false\n *\n * // disables enriching user profiles with first touch marketing data\n * skip_first_touch_marketing: false\n *\n * // the amount of time track_links will\n * // wait for Mixpanel's servers to respond\n * track_links_timeout: 300\n *\n * // adds any UTM parameters and click IDs present on the page to any events fired\n * track_marketing: true\n *\n * // enables automatic page view tracking using default page view events through\n * // the track_pageview() method\n * track_pageview: false\n *\n * // if you set upgrade to be true, the library will check for\n * // a cookie from our old js library and import super\n * // properties from it, then the old cookie is deleted\n * // The upgrade config option only works in the initialization,\n * // so make sure you set it when you create the library.\n * upgrade: false\n *\n * // extra HTTP request headers to set for each API request, in\n * // the format {'Header-Name': value}\n * xhr_headers: {}\n *\n * // whether to ignore or respect the web browser's Do Not Track setting\n * ignore_dnt: false\n * }\n *\n *\n * @param {Object} config A dictionary of new configuration values to update\n */\nMixpanelLib.prototype.set_config = function(config) {\n if (_.isObject(config)) {\n _.extend(this['config'], config);\n\n var new_batch_size = config['batch_size'];\n if (new_batch_size) {\n _.each(this.request_batchers, function(batcher) {\n batcher.resetBatchSize();\n });\n }\n\n if (!this.get_config('persistence_name')) {\n this['config']['persistence_name'] = this['config']['cookie_name'];\n }\n if (!this.get_config('disable_persistence')) {\n this['config']['disable_persistence'] = this['config']['disable_cookie'];\n }\n\n if (this['persistence']) {\n this['persistence'].update_config(this['config']);\n }\n Config.DEBUG = Config.DEBUG || this.get_config('debug');\n }\n};\n\n/**\n * returns the current config object for the library.\n */\nMixpanelLib.prototype.get_config = function(prop_name) {\n return this['config'][prop_name];\n};\n\n/**\n * Fetch a hook function from config, with safe default, and run it\n * against the given arguments\n * @param {string} hook_name which hook to retrieve\n * @returns {any|null} return value of user-provided hook, or null if nothing was returned\n */\nMixpanelLib.prototype._run_hook = function(hook_name) {\n var ret = (this['config']['hooks'][hook_name] || IDENTITY_FUNC).apply(this, slice.call(arguments, 1));\n if (typeof ret === 'undefined') {\n this.report_error(hook_name + ' hook did not return a value');\n ret = null;\n }\n return ret;\n};\n\n/**\n * Returns the value of the super property named property_name. If no such\n * property is set, get_property() will return the undefined value.\n *\n * ### Notes:\n *\n * get_property() can only be called after the Mixpanel library has finished loading.\n * init() has a loaded function available to handle this automatically. For example:\n *\n * // grab value for 'user_id' after the mixpanel library has loaded\n * mixpanel.init('YOUR PROJECT TOKEN', {\n * loaded: function(mixpanel) {\n * user_id = mixpanel.get_property('user_id');\n * }\n * });\n *\n * @param {String} property_name The name of the super property you want to retrieve\n */\nMixpanelLib.prototype.get_property = function(property_name) {\n return this['persistence'].load_prop([property_name]);\n};\n\nMixpanelLib.prototype.toString = function() {\n var name = this.get_config('name');\n if (name !== PRIMARY_INSTANCE_NAME) {\n name = PRIMARY_INSTANCE_NAME + '.' + name;\n }\n return name;\n};\n\nMixpanelLib.prototype._event_is_disabled = function(event_name) {\n return _.isBlockedUA(userAgent) ||\n this._flags.disable_all_events ||\n _.include(this.__disabled_events, event_name);\n};\n\n// perform some housekeeping around GDPR opt-in/out state\nMixpanelLib.prototype._gdpr_init = function() {\n var is_localStorage_requested = this.get_config('opt_out_tracking_persistence_type') === 'localStorage';\n\n // try to convert opt-in/out cookies to localStorage if possible\n if (is_localStorage_requested && _.localStorage.is_supported()) {\n if (!this.has_opted_in_tracking() && this.has_opted_in_tracking({'persistence_type': 'cookie'})) {\n this.opt_in_tracking({'enable_persistence': false});\n }\n if (!this.has_opted_out_tracking() && this.has_opted_out_tracking({'persistence_type': 'cookie'})) {\n this.opt_out_tracking({'clear_persistence': false});\n }\n this.clear_opt_in_out_tracking({\n 'persistence_type': 'cookie',\n 'enable_persistence': false\n });\n }\n\n // check whether the user has already opted out - if so, clear & disable persistence\n if (this.has_opted_out_tracking()) {\n this._gdpr_update_persistence({'clear_persistence': true});\n\n // check whether we should opt out by default\n // note: we don't clear persistence here by default since opt-out default state is often\n // used as an initial state while GDPR information is being collected\n } else if (!this.has_opted_in_tracking() && (\n this.get_config('opt_out_tracking_by_default') || _.cookie.get('mp_optout')\n )) {\n _.cookie.remove('mp_optout');\n this.opt_out_tracking({\n 'clear_persistence': this.get_config('opt_out_persistence_by_default')\n });\n }\n};\n\n/**\n * Enable or disable persistence based on options\n * only enable/disable if persistence is not already in this state\n * @param {boolean} [options.clear_persistence] If true, will delete all data stored by the sdk in persistence and disable it\n * @param {boolean} [options.enable_persistence] If true, will re-enable sdk persistence\n */\nMixpanelLib.prototype._gdpr_update_persistence = function(options) {\n var disabled;\n if (options && options['clear_persistence']) {\n disabled = true;\n } else if (options && options['enable_persistence']) {\n disabled = false;\n } else {\n return;\n }\n\n if (!this.get_config('disable_persistence') && this['persistence'].disabled !== disabled) {\n this['persistence'].set_disabled(disabled);\n }\n\n if (disabled) {\n this.stop_batch_senders();\n } else {\n // only start batchers after opt-in if they have previously been started\n // in order to avoid unintentionally starting up batching for the first time\n if (this._batchers_were_started) {\n this.start_batch_senders();\n }\n }\n};\n\n// call a base gdpr function after constructing the appropriate token and options args\nMixpanelLib.prototype._gdpr_call_func = function(func, options) {\n options = _.extend({\n 'track': _.bind(this.track, this),\n 'persistence_type': this.get_config('opt_out_tracking_persistence_type'),\n 'cookie_prefix': this.get_config('opt_out_tracking_cookie_prefix'),\n 'cookie_expiration': this.get_config('cookie_expiration'),\n 'cross_site_cookie': this.get_config('cross_site_cookie'),\n 'cross_subdomain_cookie': this.get_config('cross_subdomain_cookie'),\n 'cookie_domain': this.get_config('cookie_domain'),\n 'secure_cookie': this.get_config('secure_cookie'),\n 'ignore_dnt': this.get_config('ignore_dnt')\n }, options);\n\n // check if localStorage can be used for recording opt out status, fall back to cookie if not\n if (!_.localStorage.is_supported()) {\n options['persistence_type'] = 'cookie';\n }\n\n return func(this.get_config('token'), {\n track: options['track'],\n trackEventName: options['track_event_name'],\n trackProperties: options['track_properties'],\n persistenceType: options['persistence_type'],\n persistencePrefix: options['cookie_prefix'],\n cookieDomain: options['cookie_domain'],\n cookieExpiration: options['cookie_expiration'],\n crossSiteCookie: options['cross_site_cookie'],\n crossSubdomainCookie: options['cross_subdomain_cookie'],\n secureCookie: options['secure_cookie'],\n ignoreDnt: options['ignore_dnt']\n });\n};\n\n/**\n * Opt the user in to data tracking and cookies/localstorage for this Mixpanel instance\n *\n * ### Usage:\n *\n * // opt user in\n * mixpanel.opt_in_tracking();\n *\n * // opt user in with specific event name, properties, cookie configuration\n * mixpanel.opt_in_tracking({\n * track_event_name: 'User opted in',\n * track_event_properties: {\n * 'Email': 'jdoe@example.com'\n * },\n * cookie_expiration: 30,\n * secure_cookie: true\n * });\n *\n * @param {Object} [options] A dictionary of config options to override\n * @param {function} [options.track] Function used for tracking a Mixpanel event to record the opt-in action (default is this Mixpanel instance's track method)\n * @param {string} [options.track_event_name=$opt_in] Event name to be used for tracking the opt-in action\n * @param {Object} [options.track_properties] Set of properties to be tracked along with the opt-in action\n * @param {boolean} [options.enable_persistence=true] If true, will re-enable sdk persistence\n * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable\n * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name\n * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this Mixpanel instance's config)\n * @param {string} [options.cookie_domain] Custom cookie domain (overrides value specified in this Mixpanel instance's config)\n * @param {boolean} [options.cross_site_cookie] Whether the opt-in cookie is set as cross-site-enabled (overrides value specified in this Mixpanel instance's config)\n * @param {boolean} [options.cross_subdomain_cookie] Whether the opt-in cookie is set as cross-subdomain or not (overrides value specified in this Mixpanel instance's config)\n * @param {boolean} [options.secure_cookie] Whether the opt-in cookie is set as secure or not (overrides value specified in this Mixpanel instance's config)\n */\nMixpanelLib.prototype.opt_in_tracking = function(options) {\n options = _.extend({\n 'enable_persistence': true\n }, options);\n\n this._gdpr_call_func(optIn, options);\n this._gdpr_update_persistence(options);\n};\n\n/**\n * Opt the user out of data tracking and cookies/localstorage for this Mixpanel instance\n *\n * ### Usage:\n *\n * // opt user out\n * mixpanel.opt_out_tracking();\n *\n * // opt user out with different cookie configuration from Mixpanel instance\n * mixpanel.opt_out_tracking({\n * cookie_expiration: 30,\n * secure_cookie: true\n * });\n *\n * @param {Object} [options] A dictionary of config options to override\n * @param {boolean} [options.delete_user=true] If true, will delete the currently identified user's profile and clear all charges after opting the user out\n * @param {boolean} [options.clear_persistence=true] If true, will delete all data stored by the sdk in persistence\n * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable\n * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name\n * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this Mixpanel instance's config)\n * @param {string} [options.cookie_domain] Custom cookie domain (overrides value specified in this Mixpanel instance's config)\n * @param {boolean} [options.cross_site_cookie] Whether the opt-in cookie is set as cross-site-enabled (overrides value specified in this Mixpanel instance's config)\n * @param {boolean} [options.cross_subdomain_cookie] Whether the opt-in cookie is set as cross-subdomain or not (overrides value specified in this Mixpanel instance's config)\n * @param {boolean} [options.secure_cookie] Whether the opt-in cookie is set as secure or not (overrides value specified in this Mixpanel instance's config)\n */\nMixpanelLib.prototype.opt_out_tracking = function(options) {\n options = _.extend({\n 'clear_persistence': true,\n 'delete_user': true\n }, options);\n\n // delete user and clear charges since these methods may be disabled by opt-out\n if (options['delete_user'] && this['people'] && this['people']._identify_called()) {\n this['people'].delete_user();\n this['people'].clear_charges();\n }\n\n this._gdpr_call_func(optOut, options);\n this._gdpr_update_persistence(options);\n};\n\n/**\n * Check whether the user has opted in to data tracking and cookies/localstorage for this Mixpanel instance\n *\n * ### Usage:\n *\n * var has_opted_in = mixpanel.has_opted_in_tracking();\n * // use has_opted_in value\n *\n * @param {Object} [options] A dictionary of config options to override\n * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable\n * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name\n * @returns {boolean} current opt-in status\n */\nMixpanelLib.prototype.has_opted_in_tracking = function(options) {\n return this._gdpr_call_func(hasOptedIn, options);\n};\n\n/**\n * Check whether the user has opted out of data tracking and cookies/localstorage for this Mixpanel instance\n *\n * ### Usage:\n *\n * var has_opted_out = mixpanel.has_opted_out_tracking();\n * // use has_opted_out value\n *\n * @param {Object} [options] A dictionary of config options to override\n * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable\n * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name\n * @returns {boolean} current opt-out status\n */\nMixpanelLib.prototype.has_opted_out_tracking = function(options) {\n return this._gdpr_call_func(hasOptedOut, options);\n};\n\n/**\n * Clear the user's opt in/out status of data tracking and cookies/localstorage for this Mixpanel instance\n *\n * ### Usage:\n *\n * // clear user's opt-in/out status\n * mixpanel.clear_opt_in_out_tracking();\n *\n * // clear user's opt-in/out status with specific cookie configuration - should match\n * // configuration used when opt_in_tracking/opt_out_tracking methods were called.\n * mixpanel.clear_opt_in_out_tracking({\n * cookie_expiration: 30,\n * secure_cookie: true\n * });\n *\n * @param {Object} [options] A dictionary of config options to override\n * @param {boolean} [options.enable_persistence=true] If true, will re-enable sdk persistence\n * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable\n * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name\n * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this Mixpanel instance's config)\n * @param {string} [options.cookie_domain] Custom cookie domain (overrides value specified in this Mixpanel instance's config)\n * @param {boolean} [options.cross_site_cookie] Whether the opt-in cookie is set as cross-site-enabled (overrides value specified in this Mixpanel instance's config)\n * @param {boolean} [options.cross_subdomain_cookie] Whether the opt-in cookie is set as cross-subdomain or not (overrides value specified in this Mixpanel instance's config)\n * @param {boolean} [options.secure_cookie] Whether the opt-in cookie is set as secure or not (overrides value specified in this Mixpanel instance's config)\n */\nMixpanelLib.prototype.clear_opt_in_out_tracking = function(options) {\n options = _.extend({\n 'enable_persistence': true\n }, options);\n\n this._gdpr_call_func(clearOptInOut, options);\n this._gdpr_update_persistence(options);\n};\n\nMixpanelLib.prototype.report_error = function(msg, err) {\n console$1.error.apply(console$1.error, arguments);\n try {\n if (!err && !(msg instanceof Error)) {\n msg = new Error(msg);\n }\n this.get_config('error_reporter')(msg, err);\n } catch(err) {\n console$1.error(err);\n }\n};\n\n// EXPORTS (for closure compiler)\n\n// MixpanelLib Exports\nMixpanelLib.prototype['init'] = MixpanelLib.prototype.init;\nMixpanelLib.prototype['reset'] = MixpanelLib.prototype.reset;\nMixpanelLib.prototype['disable'] = MixpanelLib.prototype.disable;\nMixpanelLib.prototype['time_event'] = MixpanelLib.prototype.time_event;\nMixpanelLib.prototype['track'] = MixpanelLib.prototype.track;\nMixpanelLib.prototype['track_links'] = MixpanelLib.prototype.track_links;\nMixpanelLib.prototype['track_forms'] = MixpanelLib.prototype.track_forms;\nMixpanelLib.prototype['track_pageview'] = MixpanelLib.prototype.track_pageview;\nMixpanelLib.prototype['register'] = MixpanelLib.prototype.register;\nMixpanelLib.prototype['register_once'] = MixpanelLib.prototype.register_once;\nMixpanelLib.prototype['unregister'] = MixpanelLib.prototype.unregister;\nMixpanelLib.prototype['identify'] = MixpanelLib.prototype.identify;\nMixpanelLib.prototype['alias'] = MixpanelLib.prototype.alias;\nMixpanelLib.prototype['name_tag'] = MixpanelLib.prototype.name_tag;\nMixpanelLib.prototype['set_config'] = MixpanelLib.prototype.set_config;\nMixpanelLib.prototype['get_config'] = MixpanelLib.prototype.get_config;\nMixpanelLib.prototype['get_property'] = MixpanelLib.prototype.get_property;\nMixpanelLib.prototype['get_distinct_id'] = MixpanelLib.prototype.get_distinct_id;\nMixpanelLib.prototype['toString'] = MixpanelLib.prototype.toString;\nMixpanelLib.prototype['opt_out_tracking'] = MixpanelLib.prototype.opt_out_tracking;\nMixpanelLib.prototype['opt_in_tracking'] = MixpanelLib.prototype.opt_in_tracking;\nMixpanelLib.prototype['has_opted_out_tracking'] = MixpanelLib.prototype.has_opted_out_tracking;\nMixpanelLib.prototype['has_opted_in_tracking'] = MixpanelLib.prototype.has_opted_in_tracking;\nMixpanelLib.prototype['clear_opt_in_out_tracking'] = MixpanelLib.prototype.clear_opt_in_out_tracking;\nMixpanelLib.prototype['get_group'] = MixpanelLib.prototype.get_group;\nMixpanelLib.prototype['set_group'] = MixpanelLib.prototype.set_group;\nMixpanelLib.prototype['add_group'] = MixpanelLib.prototype.add_group;\nMixpanelLib.prototype['remove_group'] = MixpanelLib.prototype.remove_group;\nMixpanelLib.prototype['track_with_groups'] = MixpanelLib.prototype.track_with_groups;\nMixpanelLib.prototype['start_batch_senders'] = MixpanelLib.prototype.start_batch_senders;\nMixpanelLib.prototype['stop_batch_senders'] = MixpanelLib.prototype.stop_batch_senders;\nMixpanelLib.prototype['start_session_recording'] = MixpanelLib.prototype.start_session_recording;\nMixpanelLib.prototype['stop_session_recording'] = MixpanelLib.prototype.stop_session_recording;\nMixpanelLib.prototype['get_session_recording_properties'] = MixpanelLib.prototype.get_session_recording_properties;\nMixpanelLib.prototype['get_session_replay_url'] = MixpanelLib.prototype.get_session_replay_url;\nMixpanelLib.prototype['DEFAULT_API_ROUTES'] = DEFAULT_API_ROUTES;\n\n// MixpanelPersistence Exports\nMixpanelPersistence.prototype['properties'] = MixpanelPersistence.prototype.properties;\nMixpanelPersistence.prototype['update_search_keyword'] = MixpanelPersistence.prototype.update_search_keyword;\nMixpanelPersistence.prototype['update_referrer_info'] = MixpanelPersistence.prototype.update_referrer_info;\nMixpanelPersistence.prototype['get_cross_subdomain'] = MixpanelPersistence.prototype.get_cross_subdomain;\nMixpanelPersistence.prototype['clear'] = MixpanelPersistence.prototype.clear;\n\n\nvar instances = {};\nvar extend_mp = function() {\n // add all the sub mixpanel instances\n _.each(instances, function(instance, name) {\n if (name !== PRIMARY_INSTANCE_NAME) { mixpanel_master[name] = instance; }\n });\n\n // add private functions as _\n mixpanel_master['_'] = _;\n};\n\nvar override_mp_init_func = function() {\n // we override the snippets init function to handle the case where a\n // user initializes the mixpanel library after the script loads & runs\n mixpanel_master['init'] = function(token, config, name) {\n if (name) {\n // initialize a sub library\n if (!mixpanel_master[name]) {\n mixpanel_master[name] = instances[name] = create_mplib(token, config, name);\n mixpanel_master[name]._loaded();\n }\n return mixpanel_master[name];\n } else {\n var instance = mixpanel_master;\n\n if (instances[PRIMARY_INSTANCE_NAME]) {\n // main mixpanel lib already initialized\n instance = instances[PRIMARY_INSTANCE_NAME];\n } else if (token) {\n // intialize the main mixpanel lib\n instance = create_mplib(token, config, PRIMARY_INSTANCE_NAME);\n instance._loaded();\n instances[PRIMARY_INSTANCE_NAME] = instance;\n }\n\n mixpanel_master = instance;\n if (init_type === INIT_SNIPPET) {\n win[PRIMARY_INSTANCE_NAME] = mixpanel_master;\n }\n extend_mp();\n }\n };\n};\n\nvar add_dom_loaded_handler = function() {\n // Cross browser DOM Loaded support\n function dom_loaded_handler() {\n // function flag since we only want to execute this once\n if (dom_loaded_handler.done) { return; }\n dom_loaded_handler.done = true;\n\n DOM_LOADED = true;\n ENQUEUE_REQUESTS = false;\n\n _.each(instances, function(inst) {\n inst._dom_loaded();\n });\n }\n\n function do_scroll_check() {\n try {\n document$1.documentElement.doScroll('left');\n } catch(e) {\n setTimeout(do_scroll_check, 1);\n return;\n }\n\n dom_loaded_handler();\n }\n\n if (document$1.addEventListener) {\n if (document$1.readyState === 'complete') {\n // safari 4 can fire the DOMContentLoaded event before loading all\n // external JS (including this file). you will see some copypasta\n // on the internet that checks for 'complete' and 'loaded', but\n // 'loaded' is an IE thing\n dom_loaded_handler();\n } else {\n document$1.addEventListener('DOMContentLoaded', dom_loaded_handler, false);\n }\n } else if (document$1.attachEvent) {\n // IE\n document$1.attachEvent('onreadystatechange', dom_loaded_handler);\n\n // check to make sure we arn't in a frame\n var toplevel = false;\n try {\n toplevel = win.frameElement === null;\n } catch(e) {\n // noop\n }\n\n if (document$1.documentElement.doScroll && toplevel) {\n do_scroll_check();\n }\n }\n\n // fallback handler, always will work\n _.register_event(win, 'load', dom_loaded_handler, true);\n};\n\nfunction init_as_module(bundle_loader) {\n load_extra_bundle = bundle_loader;\n init_type = INIT_MODULE;\n mixpanel_master = new MixpanelLib();\n\n override_mp_init_func();\n mixpanel_master['init']();\n add_dom_loaded_handler();\n\n return mixpanel_master;\n}\n\n// For loading separate bundles asynchronously via script tag\n\n// For builds that have everything in one bundle, no extra work.\nfunction loadNoop (_src, onload) {\n onload();\n}\n\n/* eslint camelcase: \"off\" */\n\nvar mixpanel = init_as_module(loadNoop);\n\nexport { mixpanel as default };\n","/*\nobject-assign\n(c) Sindre Sorhus\n@license MIT\n*/\n\n'use strict';\n/* eslint-disable no-unused-vars */\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar propIsEnumerable = Object.prototype.propertyIsEnumerable;\n\nfunction toObject(val) {\n\tif (val === null || val === undefined) {\n\t\tthrow new TypeError('Object.assign cannot be called with null or undefined');\n\t}\n\n\treturn Object(val);\n}\n\nfunction shouldUseNative() {\n\ttry {\n\t\tif (!Object.assign) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Detect buggy property enumeration order in older V8 versions.\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=4118\n\t\tvar test1 = new String('abc'); // eslint-disable-line no-new-wrappers\n\t\ttest1[5] = 'de';\n\t\tif (Object.getOwnPropertyNames(test1)[0] === '5') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test2 = {};\n\t\tfor (var i = 0; i < 10; i++) {\n\t\t\ttest2['_' + String.fromCharCode(i)] = i;\n\t\t}\n\t\tvar order2 = Object.getOwnPropertyNames(test2).map(function (n) {\n\t\t\treturn test2[n];\n\t\t});\n\t\tif (order2.join('') !== '0123456789') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test3 = {};\n\t\t'abcdefghijklmnopqrst'.split('').forEach(function (letter) {\n\t\t\ttest3[letter] = letter;\n\t\t});\n\t\tif (Object.keys(Object.assign({}, test3)).join('') !==\n\t\t\t\t'abcdefghijklmnopqrst') {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t} catch (err) {\n\t\t// We don't expect any of the above to throw, but better to be safe.\n\t\treturn false;\n\t}\n}\n\nmodule.exports = shouldUseNative() ? Object.assign : function (target, source) {\n\tvar from;\n\tvar to = toObject(target);\n\tvar symbols;\n\n\tfor (var s = 1; s < arguments.length; s++) {\n\t\tfrom = Object(arguments[s]);\n\n\t\tfor (var key in from) {\n\t\t\tif (hasOwnProperty.call(from, key)) {\n\t\t\t\tto[key] = from[key];\n\t\t\t}\n\t\t}\n\n\t\tif (getOwnPropertySymbols) {\n\t\t\tsymbols = getOwnPropertySymbols(from);\n\t\t\tfor (var i = 0; i < symbols.length; i++) {\n\t\t\t\tif (propIsEnumerable.call(from, symbols[i])) {\n\t\t\t\t\tto[symbols[i]] = from[symbols[i]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn to;\n};\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');\n\nfunction emptyFunction() {}\nfunction emptyFunctionWithReset() {}\nemptyFunctionWithReset.resetWarningCache = emptyFunction;\n\nmodule.exports = function() {\n function shim(props, propName, componentName, location, propFullName, secret) {\n if (secret === ReactPropTypesSecret) {\n // It is still safe when called from React.\n return;\n }\n var err = new Error(\n 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +\n 'Use PropTypes.checkPropTypes() to call them. ' +\n 'Read more at http://fb.me/use-check-prop-types'\n );\n err.name = 'Invariant Violation';\n throw err;\n };\n shim.isRequired = shim;\n function getShim() {\n return shim;\n };\n // Important!\n // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.\n var ReactPropTypes = {\n array: shim,\n bigint: shim,\n bool: shim,\n func: shim,\n number: shim,\n object: shim,\n string: shim,\n symbol: shim,\n\n any: shim,\n arrayOf: getShim,\n element: shim,\n elementType: shim,\n instanceOf: getShim,\n node: shim,\n objectOf: getShim,\n oneOf: getShim,\n oneOfType: getShim,\n shape: getShim,\n exact: getShim,\n\n checkPropTypes: emptyFunctionWithReset,\n resetWarningCache: emptyFunction\n };\n\n ReactPropTypes.PropTypes = ReactPropTypes;\n\n return ReactPropTypes;\n};\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nif (process.env.NODE_ENV !== 'production') {\n var ReactIs = require('react-is');\n\n // By explicitly using `prop-types` you are opting into new development behavior.\n // http://fb.me/prop-types-in-prod\n var throwOnDirectAccess = true;\n module.exports = require('./factoryWithTypeCheckers')(ReactIs.isElement, throwOnDirectAccess);\n} else {\n // By explicitly using `prop-types` you are opting into new production behavior.\n // http://fb.me/prop-types-in-prod\n module.exports = require('./factoryWithThrowingShims')();\n}\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';\n\nmodule.exports = ReactPropTypesSecret;\n","/**\n * Based on Kendo UI Core expression code \n */\n'use strict'\n\nfunction Cache(maxSize) {\n this._maxSize = maxSize\n this.clear()\n}\nCache.prototype.clear = function () {\n this._size = 0\n this._values = Object.create(null)\n}\nCache.prototype.get = function (key) {\n return this._values[key]\n}\nCache.prototype.set = function (key, value) {\n this._size >= this._maxSize && this.clear()\n if (!(key in this._values)) this._size++\n\n return (this._values[key] = value)\n}\n\nvar SPLIT_REGEX = /[^.^\\]^[]+|(?=\\[\\]|\\.\\.)/g,\n DIGIT_REGEX = /^\\d+$/,\n LEAD_DIGIT_REGEX = /^\\d/,\n SPEC_CHAR_REGEX = /[~`!#$%\\^&*+=\\-\\[\\]\\\\';,/{}|\\\\\":<>\\?]/g,\n CLEAN_QUOTES_REGEX = /^\\s*(['\"]?)(.*?)(\\1)\\s*$/,\n MAX_CACHE_SIZE = 512\n\nvar pathCache = new Cache(MAX_CACHE_SIZE),\n setCache = new Cache(MAX_CACHE_SIZE),\n getCache = new Cache(MAX_CACHE_SIZE)\n\nvar config\n\nmodule.exports = {\n Cache: Cache,\n\n split: split,\n\n normalizePath: normalizePath,\n\n setter: function (path) {\n var parts = normalizePath(path)\n\n return (\n setCache.get(path) ||\n setCache.set(path, function setter(obj, value) {\n var index = 0\n var len = parts.length\n var data = obj\n\n while (index < len - 1) {\n var part = parts[index]\n if (\n part === '__proto__' ||\n part === 'constructor' ||\n part === 'prototype'\n ) {\n return obj\n }\n\n data = data[parts[index++]]\n }\n data[parts[index]] = value\n })\n )\n },\n\n getter: function (path, safe) {\n var parts = normalizePath(path)\n return (\n getCache.get(path) ||\n getCache.set(path, function getter(data) {\n var index = 0,\n len = parts.length\n while (index < len) {\n if (data != null || !safe) data = data[parts[index++]]\n else return\n }\n return data\n })\n )\n },\n\n join: function (segments) {\n return segments.reduce(function (path, part) {\n return (\n path +\n (isQuoted(part) || DIGIT_REGEX.test(part)\n ? '[' + part + ']'\n : (path ? '.' : '') + part)\n )\n }, '')\n },\n\n forEach: function (path, cb, thisArg) {\n forEach(Array.isArray(path) ? path : split(path), cb, thisArg)\n },\n}\n\nfunction normalizePath(path) {\n return (\n pathCache.get(path) ||\n pathCache.set(\n path,\n split(path).map(function (part) {\n return part.replace(CLEAN_QUOTES_REGEX, '$2')\n })\n )\n )\n}\n\nfunction split(path) {\n return path.match(SPLIT_REGEX) || ['']\n}\n\nfunction forEach(parts, iter, thisArg) {\n var len = parts.length,\n part,\n idx,\n isArray,\n isBracket\n\n for (idx = 0; idx < len; idx++) {\n part = parts[idx]\n\n if (part) {\n if (shouldBeQuoted(part)) {\n part = '\"' + part + '\"'\n }\n\n isBracket = isQuoted(part)\n isArray = !isBracket && /^\\d+$/.test(part)\n\n iter.call(thisArg, part, isBracket, isArray, idx, parts)\n }\n }\n}\n\nfunction isQuoted(str) {\n return (\n typeof str === 'string' && str && [\"'\", '\"'].indexOf(str.charAt(0)) !== -1\n )\n}\n\nfunction hasLeadingNumber(part) {\n return part.match(LEAD_DIGIT_REGEX) && !part.match(DIGIT_REGEX)\n}\n\nfunction hasSpecialChars(part) {\n return SPEC_CHAR_REGEX.test(part)\n}\n\nfunction shouldBeQuoted(part) {\n return !isQuoted(part) && (hasLeadingNumber(part) || hasSpecialChars(part))\n}\n","import { jsx, jsxs, Fragment } from 'react/jsx-runtime';\nimport { createContext, useContext, useState, forwardRef, useEffect, useRef, useLayoutEffect } from 'react';\nimport { format, startOfMonth, endOfMonth, startOfDay, isSameYear, setMonth, setYear, startOfYear, differenceInCalendarMonths, addMonths, isSameMonth, isBefore, startOfISOWeek, startOfWeek, addDays, isSameDay, isAfter, subDays, differenceInCalendarDays, isDate, max, min, addWeeks, addYears, endOfISOWeek, endOfWeek, getUnixTime, getISOWeek, getWeek, getWeeksInMonth, parse } from 'date-fns';\nimport { enUS } from 'date-fns/locale';\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\n\r\nvar __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n return __assign.apply(this, arguments);\r\n};\r\n\r\nfunction __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nfunction __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\ntypeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\n\n/** Returns true when the props are of type {@link DayPickerMultipleProps}. */\nfunction isDayPickerMultiple(props) {\n return props.mode === 'multiple';\n}\n\n/** Returns true when the props are of type {@link DayPickerRangeProps}. */\nfunction isDayPickerRange(props) {\n return props.mode === 'range';\n}\n\n/** Returns true when the props are of type {@link DayPickerSingleProps}. */\nfunction isDayPickerSingle(props) {\n return props.mode === 'single';\n}\n\n/**\n * The name of the default CSS classes.\n */\nvar defaultClassNames = {\n root: 'rdp',\n multiple_months: 'rdp-multiple_months',\n with_weeknumber: 'rdp-with_weeknumber',\n vhidden: 'rdp-vhidden',\n button_reset: 'rdp-button_reset',\n button: 'rdp-button',\n caption: 'rdp-caption',\n caption_start: 'rdp-caption_start',\n caption_end: 'rdp-caption_end',\n caption_between: 'rdp-caption_between',\n caption_label: 'rdp-caption_label',\n caption_dropdowns: 'rdp-caption_dropdowns',\n dropdown: 'rdp-dropdown',\n dropdown_month: 'rdp-dropdown_month',\n dropdown_year: 'rdp-dropdown_year',\n dropdown_icon: 'rdp-dropdown_icon',\n months: 'rdp-months',\n month: 'rdp-month',\n table: 'rdp-table',\n tbody: 'rdp-tbody',\n tfoot: 'rdp-tfoot',\n head: 'rdp-head',\n head_row: 'rdp-head_row',\n head_cell: 'rdp-head_cell',\n nav: 'rdp-nav',\n nav_button: 'rdp-nav_button',\n nav_button_previous: 'rdp-nav_button_previous',\n nav_button_next: 'rdp-nav_button_next',\n nav_icon: 'rdp-nav_icon',\n row: 'rdp-row',\n weeknumber: 'rdp-weeknumber',\n cell: 'rdp-cell',\n day: 'rdp-day',\n day_today: 'rdp-day_today',\n day_outside: 'rdp-day_outside',\n day_selected: 'rdp-day_selected',\n day_disabled: 'rdp-day_disabled',\n day_hidden: 'rdp-day_hidden',\n day_range_start: 'rdp-day_range_start',\n day_range_end: 'rdp-day_range_end',\n day_range_middle: 'rdp-day_range_middle'\n};\n\n/**\n * The default formatter for the caption.\n */\nfunction formatCaption(month, options) {\n return format(month, 'LLLL y', options);\n}\n\n/**\n * The default formatter for the Day button.\n */\nfunction formatDay(day, options) {\n return format(day, 'd', options);\n}\n\n/**\n * The default formatter for the Month caption.\n */\nfunction formatMonthCaption(month, options) {\n return format(month, 'LLLL', options);\n}\n\n/**\n * The default formatter for the week number.\n */\nfunction formatWeekNumber(weekNumber) {\n return \"\".concat(weekNumber);\n}\n\n/**\n * The default formatter for the name of the weekday.\n */\nfunction formatWeekdayName(weekday, options) {\n return format(weekday, 'cccccc', options);\n}\n\n/**\n * The default formatter for the Year caption.\n */\nfunction formatYearCaption(year, options) {\n return format(year, 'yyyy', options);\n}\n\nvar formatters = /*#__PURE__*/Object.freeze({\n __proto__: null,\n formatCaption: formatCaption,\n formatDay: formatDay,\n formatMonthCaption: formatMonthCaption,\n formatWeekNumber: formatWeekNumber,\n formatWeekdayName: formatWeekdayName,\n formatYearCaption: formatYearCaption\n});\n\n/**\n * The default ARIA label for the day button.\n */\nvar labelDay = function (day, activeModifiers, options) {\n return format(day, 'do MMMM (EEEE)', options);\n};\n\n/**\n * The default ARIA label for the WeekNumber element.\n */\nvar labelMonthDropdown = function () {\n return 'Month: ';\n};\n\n/**\n * The default ARIA label for next month button in navigation\n */\nvar labelNext = function () {\n return 'Go to next month';\n};\n\n/**\n * The default ARIA label for previous month button in navigation\n */\nvar labelPrevious = function () {\n return 'Go to previous month';\n};\n\n/**\n * The default ARIA label for the Weekday element.\n */\nvar labelWeekday = function (day, options) {\n return format(day, 'cccc', options);\n};\n\n/**\n * The default ARIA label for the WeekNumber element.\n */\nvar labelWeekNumber = function (n) {\n return \"Week n. \".concat(n);\n};\n\n/**\n * The default ARIA label for the WeekNumber element.\n */\nvar labelYearDropdown = function () {\n return 'Year: ';\n};\n\nvar labels = /*#__PURE__*/Object.freeze({\n __proto__: null,\n labelDay: labelDay,\n labelMonthDropdown: labelMonthDropdown,\n labelNext: labelNext,\n labelPrevious: labelPrevious,\n labelWeekNumber: labelWeekNumber,\n labelWeekday: labelWeekday,\n labelYearDropdown: labelYearDropdown\n});\n\n/**\n * Returns the default values to use in the DayPickerContext, in case they are\n * not passed down with the DayPicker initial props.\n */\nfunction getDefaultContextValues() {\n var captionLayout = 'buttons';\n var classNames = defaultClassNames;\n var locale = enUS;\n var modifiersClassNames = {};\n var modifiers = {};\n var numberOfMonths = 1;\n var styles = {};\n var today = new Date();\n return {\n captionLayout: captionLayout,\n classNames: classNames,\n formatters: formatters,\n labels: labels,\n locale: locale,\n modifiersClassNames: modifiersClassNames,\n modifiers: modifiers,\n numberOfMonths: numberOfMonths,\n styles: styles,\n today: today,\n mode: 'default'\n };\n}\n\n/** Return the `fromDate` and `toDate` prop values values parsing the DayPicker props. */\nfunction parseFromToProps(props) {\n var fromYear = props.fromYear, toYear = props.toYear, fromMonth = props.fromMonth, toMonth = props.toMonth;\n var fromDate = props.fromDate, toDate = props.toDate;\n if (fromMonth) {\n fromDate = startOfMonth(fromMonth);\n }\n else if (fromYear) {\n fromDate = new Date(fromYear, 0, 1);\n }\n if (toMonth) {\n toDate = endOfMonth(toMonth);\n }\n else if (toYear) {\n toDate = new Date(toYear, 11, 31);\n }\n return {\n fromDate: fromDate ? startOfDay(fromDate) : undefined,\n toDate: toDate ? startOfDay(toDate) : undefined\n };\n}\n\n/**\n * The DayPicker context shares the props passed to DayPicker within internal\n * and custom components. It is used to set the default values and perform\n * one-time calculations required to render the days.\n *\n * Access to this context from the {@link useDayPicker} hook.\n */\nvar DayPickerContext = createContext(undefined);\n/**\n * The provider for the {@link DayPickerContext}, assigning the defaults from the\n * initial DayPicker props.\n */\nfunction DayPickerProvider(props) {\n var _a;\n var initialProps = props.initialProps;\n var defaultContextValues = getDefaultContextValues();\n var _b = parseFromToProps(initialProps), fromDate = _b.fromDate, toDate = _b.toDate;\n var captionLayout = (_a = initialProps.captionLayout) !== null && _a !== void 0 ? _a : defaultContextValues.captionLayout;\n if (captionLayout !== 'buttons' && (!fromDate || !toDate)) {\n // When no from/to dates are set, the caption is always buttons\n captionLayout = 'buttons';\n }\n var onSelect;\n if (isDayPickerSingle(initialProps) ||\n isDayPickerMultiple(initialProps) ||\n isDayPickerRange(initialProps)) {\n onSelect = initialProps.onSelect;\n }\n var value = __assign(__assign(__assign({}, defaultContextValues), initialProps), { captionLayout: captionLayout, classNames: __assign(__assign({}, defaultContextValues.classNames), initialProps.classNames), components: __assign({}, initialProps.components), formatters: __assign(__assign({}, defaultContextValues.formatters), initialProps.formatters), fromDate: fromDate, labels: __assign(__assign({}, defaultContextValues.labels), initialProps.labels), mode: initialProps.mode || defaultContextValues.mode, modifiers: __assign(__assign({}, defaultContextValues.modifiers), initialProps.modifiers), modifiersClassNames: __assign(__assign({}, defaultContextValues.modifiersClassNames), initialProps.modifiersClassNames), onSelect: onSelect, styles: __assign(__assign({}, defaultContextValues.styles), initialProps.styles), toDate: toDate });\n return (jsx(DayPickerContext.Provider, { value: value, children: props.children }));\n}\n/**\n * Hook to access the {@link DayPickerContextValue}.\n *\n * Use the DayPicker context to access to the props passed to DayPicker inside\n * internal or custom components.\n */\nfunction useDayPicker() {\n var context = useContext(DayPickerContext);\n if (!context) {\n throw new Error(\"useDayPicker must be used within a DayPickerProvider.\");\n }\n return context;\n}\n\n/** Render the caption for the displayed month. This component is used when `captionLayout=\"buttons\"`. */\nfunction CaptionLabel(props) {\n var _a = useDayPicker(), locale = _a.locale, classNames = _a.classNames, styles = _a.styles, formatCaption = _a.formatters.formatCaption;\n return (jsx(\"div\", { className: classNames.caption_label, style: styles.caption_label, \"aria-live\": \"polite\", role: \"presentation\", id: props.id, children: formatCaption(props.displayMonth, { locale: locale }) }));\n}\n\n/**\n * Render the icon in the styled drop-down.\n */\nfunction IconDropdown(props) {\n return (jsx(\"svg\", __assign({ width: \"8px\", height: \"8px\", viewBox: \"0 0 120 120\", \"data-testid\": \"iconDropdown\" }, props, { children: jsx(\"path\", { d: \"M4.22182541,48.2218254 C8.44222828,44.0014225 15.2388494,43.9273804 19.5496459,47.9996989 L19.7781746,48.2218254 L60,88.443 L100.221825,48.2218254 C104.442228,44.0014225 111.238849,43.9273804 115.549646,47.9996989 L115.778175,48.2218254 C119.998577,52.4422283 120.07262,59.2388494 116.000301,63.5496459 L115.778175,63.7781746 L67.7781746,111.778175 C63.5577717,115.998577 56.7611506,116.07262 52.4503541,112.000301 L52.2218254,111.778175 L4.22182541,63.7781746 C-0.0739418023,59.4824074 -0.0739418023,52.5175926 4.22182541,48.2218254 Z\", fill: \"currentColor\", fillRule: \"nonzero\" }) })));\n}\n\n/**\n * Render a styled select component – displaying a caption and a custom\n * drop-down icon.\n */\nfunction Dropdown(props) {\n var _a, _b;\n var onChange = props.onChange, value = props.value, children = props.children, caption = props.caption, className = props.className, style = props.style;\n var dayPicker = useDayPicker();\n var IconDropdownComponent = (_b = (_a = dayPicker.components) === null || _a === void 0 ? void 0 : _a.IconDropdown) !== null && _b !== void 0 ? _b : IconDropdown;\n return (jsxs(\"div\", { className: className, style: style, children: [jsx(\"span\", { className: dayPicker.classNames.vhidden, children: props['aria-label'] }), jsx(\"select\", { name: props.name, \"aria-label\": props['aria-label'], className: dayPicker.classNames.dropdown, style: dayPicker.styles.dropdown, value: value, onChange: onChange, children: children }), jsxs(\"div\", { className: dayPicker.classNames.caption_label, style: dayPicker.styles.caption_label, \"aria-hidden\": \"true\", children: [caption, jsx(IconDropdownComponent, { className: dayPicker.classNames.dropdown_icon, style: dayPicker.styles.dropdown_icon })] })] }));\n}\n\n/** Render the dropdown to navigate between months. */\nfunction MonthsDropdown(props) {\n var _a;\n var _b = useDayPicker(), fromDate = _b.fromDate, toDate = _b.toDate, styles = _b.styles, locale = _b.locale, formatMonthCaption = _b.formatters.formatMonthCaption, classNames = _b.classNames, components = _b.components, labelMonthDropdown = _b.labels.labelMonthDropdown;\n // Dropdown should appear only when both from/toDate is set\n if (!fromDate)\n return jsx(Fragment, {});\n if (!toDate)\n return jsx(Fragment, {});\n var dropdownMonths = [];\n if (isSameYear(fromDate, toDate)) {\n // only display the months included in the range\n var date = startOfMonth(fromDate);\n for (var month = fromDate.getMonth(); month <= toDate.getMonth(); month++) {\n dropdownMonths.push(setMonth(date, month));\n }\n }\n else {\n // display all the 12 months\n var date = startOfMonth(new Date()); // Any date should be OK, as we just need the year\n for (var month = 0; month <= 11; month++) {\n dropdownMonths.push(setMonth(date, month));\n }\n }\n var handleChange = function (e) {\n var selectedMonth = Number(e.target.value);\n var newMonth = setMonth(startOfMonth(props.displayMonth), selectedMonth);\n props.onChange(newMonth);\n };\n var DropdownComponent = (_a = components === null || components === void 0 ? void 0 : components.Dropdown) !== null && _a !== void 0 ? _a : Dropdown;\n return (jsx(DropdownComponent, { name: \"months\", \"aria-label\": labelMonthDropdown(), className: classNames.dropdown_month, style: styles.dropdown_month, onChange: handleChange, value: props.displayMonth.getMonth(), caption: formatMonthCaption(props.displayMonth, { locale: locale }), children: dropdownMonths.map(function (m) { return (jsx(\"option\", { value: m.getMonth(), children: formatMonthCaption(m, { locale: locale }) }, m.getMonth())); }) }));\n}\n\n/**\n * Render a dropdown to change the year. Take in account the `nav.fromDate` and\n * `toDate` from context.\n */\nfunction YearsDropdown(props) {\n var _a;\n var displayMonth = props.displayMonth;\n var _b = useDayPicker(), fromDate = _b.fromDate, toDate = _b.toDate, locale = _b.locale, styles = _b.styles, classNames = _b.classNames, components = _b.components, formatYearCaption = _b.formatters.formatYearCaption, labelYearDropdown = _b.labels.labelYearDropdown;\n var years = [];\n // Dropdown should appear only when both from/toDate is set\n if (!fromDate)\n return jsx(Fragment, {});\n if (!toDate)\n return jsx(Fragment, {});\n var fromYear = fromDate.getFullYear();\n var toYear = toDate.getFullYear();\n for (var year = fromYear; year <= toYear; year++) {\n years.push(setYear(startOfYear(new Date()), year));\n }\n var handleChange = function (e) {\n var newMonth = setYear(startOfMonth(displayMonth), Number(e.target.value));\n props.onChange(newMonth);\n };\n var DropdownComponent = (_a = components === null || components === void 0 ? void 0 : components.Dropdown) !== null && _a !== void 0 ? _a : Dropdown;\n return (jsx(DropdownComponent, { name: \"years\", \"aria-label\": labelYearDropdown(), className: classNames.dropdown_year, style: styles.dropdown_year, onChange: handleChange, value: displayMonth.getFullYear(), caption: formatYearCaption(displayMonth, { locale: locale }), children: years.map(function (year) { return (jsx(\"option\", { value: year.getFullYear(), children: formatYearCaption(year, { locale: locale }) }, year.getFullYear())); }) }));\n}\n\n/**\n * Helper hook for using controlled/uncontrolled values from a component props.\n *\n * When the value is not controlled, pass `undefined` as `controlledValue` and\n * use the returned setter to update it.\n *\n * When the value is controlled, pass the controlled value as second\n * argument, which will be always returned as `value`.\n */\nfunction useControlledValue(defaultValue, controlledValue) {\n var _a = useState(defaultValue), uncontrolledValue = _a[0], setValue = _a[1];\n var value = controlledValue === undefined ? uncontrolledValue : controlledValue;\n return [value, setValue];\n}\n\n/** Return the initial month according to the given options. */\nfunction getInitialMonth(context) {\n var month = context.month, defaultMonth = context.defaultMonth, today = context.today;\n var initialMonth = month || defaultMonth || today || new Date();\n var toDate = context.toDate, fromDate = context.fromDate, _a = context.numberOfMonths, numberOfMonths = _a === void 0 ? 1 : _a;\n // Fix the initialMonth if is after the to-date\n if (toDate && differenceInCalendarMonths(toDate, initialMonth) < 0) {\n var offset = -1 * (numberOfMonths - 1);\n initialMonth = addMonths(toDate, offset);\n }\n // Fix the initialMonth if is before the from-date\n if (fromDate && differenceInCalendarMonths(initialMonth, fromDate) < 0) {\n initialMonth = fromDate;\n }\n return startOfMonth(initialMonth);\n}\n\n/** Controls the navigation state. */\nfunction useNavigationState() {\n var context = useDayPicker();\n var initialMonth = getInitialMonth(context);\n var _a = useControlledValue(initialMonth, context.month), month = _a[0], setMonth = _a[1];\n var goToMonth = function (date) {\n var _a;\n if (context.disableNavigation)\n return;\n var month = startOfMonth(date);\n setMonth(month);\n (_a = context.onMonthChange) === null || _a === void 0 ? void 0 : _a.call(context, month);\n };\n return [month, goToMonth];\n}\n\n/**\n * Return the months to display in the component according to the number of\n * months and the from/to date.\n */\nfunction getDisplayMonths(month, _a) {\n var reverseMonths = _a.reverseMonths, numberOfMonths = _a.numberOfMonths;\n var start = startOfMonth(month);\n var end = startOfMonth(addMonths(start, numberOfMonths));\n var monthsDiff = differenceInCalendarMonths(end, start);\n var months = [];\n for (var i = 0; i < monthsDiff; i++) {\n var nextMonth = addMonths(start, i);\n months.push(nextMonth);\n }\n if (reverseMonths)\n months = months.reverse();\n return months;\n}\n\n/**\n * Returns the next month the user can navigate to according to the given\n * options.\n *\n * Please note that the next month is not always the next calendar month:\n *\n * - if after the `toDate` range, is undefined;\n * - if the navigation is paged, is the number of months displayed ahead.\n *\n */\nfunction getNextMonth(startingMonth, options) {\n if (options.disableNavigation) {\n return undefined;\n }\n var toDate = options.toDate, pagedNavigation = options.pagedNavigation, _a = options.numberOfMonths, numberOfMonths = _a === void 0 ? 1 : _a;\n var offset = pagedNavigation ? numberOfMonths : 1;\n var month = startOfMonth(startingMonth);\n if (!toDate) {\n return addMonths(month, offset);\n }\n var monthsDiff = differenceInCalendarMonths(toDate, startingMonth);\n if (monthsDiff < numberOfMonths) {\n return undefined;\n }\n // Jump forward as the number of months when paged navigation\n return addMonths(month, offset);\n}\n\n/**\n * Returns the next previous the user can navigate to, according to the given\n * options.\n *\n * Please note that the previous month is not always the previous calendar\n * month:\n *\n * - if before the `fromDate` date, is `undefined`;\n * - if the navigation is paged, is the number of months displayed before.\n *\n */\nfunction getPreviousMonth(startingMonth, options) {\n if (options.disableNavigation) {\n return undefined;\n }\n var fromDate = options.fromDate, pagedNavigation = options.pagedNavigation, _a = options.numberOfMonths, numberOfMonths = _a === void 0 ? 1 : _a;\n var offset = pagedNavigation ? numberOfMonths : 1;\n var month = startOfMonth(startingMonth);\n if (!fromDate) {\n return addMonths(month, -offset);\n }\n var monthsDiff = differenceInCalendarMonths(month, fromDate);\n if (monthsDiff <= 0) {\n return undefined;\n }\n // Jump back as the number of months when paged navigation\n return addMonths(month, -offset);\n}\n\n/**\n * The Navigation context shares details and methods to navigate the months in DayPicker.\n * Access this context from the {@link useNavigation} hook.\n */\nvar NavigationContext = createContext(undefined);\n/** Provides the values for the {@link NavigationContext}. */\nfunction NavigationProvider(props) {\n var dayPicker = useDayPicker();\n var _a = useNavigationState(), currentMonth = _a[0], goToMonth = _a[1];\n var displayMonths = getDisplayMonths(currentMonth, dayPicker);\n var nextMonth = getNextMonth(currentMonth, dayPicker);\n var previousMonth = getPreviousMonth(currentMonth, dayPicker);\n var isDateDisplayed = function (date) {\n return displayMonths.some(function (displayMonth) {\n return isSameMonth(date, displayMonth);\n });\n };\n var goToDate = function (date, refDate) {\n if (isDateDisplayed(date)) {\n return;\n }\n if (refDate && isBefore(date, refDate)) {\n goToMonth(addMonths(date, 1 + dayPicker.numberOfMonths * -1));\n }\n else {\n goToMonth(date);\n }\n };\n var value = {\n currentMonth: currentMonth,\n displayMonths: displayMonths,\n goToMonth: goToMonth,\n goToDate: goToDate,\n previousMonth: previousMonth,\n nextMonth: nextMonth,\n isDateDisplayed: isDateDisplayed\n };\n return (jsx(NavigationContext.Provider, { value: value, children: props.children }));\n}\n/**\n * Hook to access the {@link NavigationContextValue}. Use this hook to navigate\n * between months or years in DayPicker.\n *\n * This hook is meant to be used inside internal or custom components.\n */\nfunction useNavigation() {\n var context = useContext(NavigationContext);\n if (!context) {\n throw new Error('useNavigation must be used within a NavigationProvider');\n }\n return context;\n}\n\n/**\n * Render a caption with the dropdowns to navigate between months and years.\n */\nfunction CaptionDropdowns(props) {\n var _a;\n var _b = useDayPicker(), classNames = _b.classNames, styles = _b.styles, components = _b.components;\n var goToMonth = useNavigation().goToMonth;\n var handleMonthChange = function (newMonth) {\n goToMonth(addMonths(newMonth, props.displayIndex ? -props.displayIndex : 0));\n };\n var CaptionLabelComponent = (_a = components === null || components === void 0 ? void 0 : components.CaptionLabel) !== null && _a !== void 0 ? _a : CaptionLabel;\n var captionLabel = (jsx(CaptionLabelComponent, { id: props.id, displayMonth: props.displayMonth }));\n return (jsxs(\"div\", { className: classNames.caption_dropdowns, style: styles.caption_dropdowns, children: [jsx(\"div\", { className: classNames.vhidden, children: captionLabel }), jsx(MonthsDropdown, { onChange: handleMonthChange, displayMonth: props.displayMonth }), jsx(YearsDropdown, { onChange: handleMonthChange, displayMonth: props.displayMonth })] }));\n}\n\n/**\n * Render the \"previous month\" button in the navigation.\n */\nfunction IconLeft(props) {\n return (jsx(\"svg\", __assign({ width: \"16px\", height: \"16px\", viewBox: \"0 0 120 120\" }, props, { children: jsx(\"path\", { d: \"M69.490332,3.34314575 C72.6145263,0.218951416 77.6798462,0.218951416 80.8040405,3.34314575 C83.8617626,6.40086786 83.9268205,11.3179931 80.9992143,14.4548388 L80.8040405,14.6568542 L35.461,60 L80.8040405,105.343146 C83.8617626,108.400868 83.9268205,113.317993 80.9992143,116.454839 L80.8040405,116.656854 C77.7463184,119.714576 72.8291931,119.779634 69.6923475,116.852028 L69.490332,116.656854 L18.490332,65.6568542 C15.4326099,62.5991321 15.367552,57.6820069 18.2951583,54.5451612 L18.490332,54.3431458 L69.490332,3.34314575 Z\", fill: \"currentColor\", fillRule: \"nonzero\" }) })));\n}\n\n/**\n * Render the \"next month\" button in the navigation.\n */\nfunction IconRight(props) {\n return (jsx(\"svg\", __assign({ width: \"16px\", height: \"16px\", viewBox: \"0 0 120 120\" }, props, { children: jsx(\"path\", { d: \"M49.8040405,3.34314575 C46.6798462,0.218951416 41.6145263,0.218951416 38.490332,3.34314575 C35.4326099,6.40086786 35.367552,11.3179931 38.2951583,14.4548388 L38.490332,14.6568542 L83.8333725,60 L38.490332,105.343146 C35.4326099,108.400868 35.367552,113.317993 38.2951583,116.454839 L38.490332,116.656854 C41.5480541,119.714576 46.4651794,119.779634 49.602025,116.852028 L49.8040405,116.656854 L100.804041,65.6568542 C103.861763,62.5991321 103.926821,57.6820069 100.999214,54.5451612 L100.804041,54.3431458 L49.8040405,3.34314575 Z\", fill: \"currentColor\" }) })));\n}\n\n/** Render a button HTML element applying the reset class name. */\nvar Button = forwardRef(function (props, ref) {\n var _a = useDayPicker(), classNames = _a.classNames, styles = _a.styles;\n var classNamesArr = [classNames.button_reset, classNames.button];\n if (props.className) {\n classNamesArr.push(props.className);\n }\n var className = classNamesArr.join(' ');\n var style = __assign(__assign({}, styles.button_reset), styles.button);\n if (props.style) {\n Object.assign(style, props.style);\n }\n return (jsx(\"button\", __assign({}, props, { ref: ref, type: \"button\", className: className, style: style })));\n});\n\n/** A component rendering the navigation buttons or the drop-downs. */\nfunction Navigation(props) {\n var _a, _b;\n var _c = useDayPicker(), dir = _c.dir, locale = _c.locale, classNames = _c.classNames, styles = _c.styles, _d = _c.labels, labelPrevious = _d.labelPrevious, labelNext = _d.labelNext, components = _c.components;\n if (!props.nextMonth && !props.previousMonth) {\n return jsx(Fragment, {});\n }\n var previousLabel = labelPrevious(props.previousMonth, { locale: locale });\n var previousClassName = [\n classNames.nav_button,\n classNames.nav_button_previous\n ].join(' ');\n var nextLabel = labelNext(props.nextMonth, { locale: locale });\n var nextClassName = [\n classNames.nav_button,\n classNames.nav_button_next\n ].join(' ');\n var IconRightComponent = (_a = components === null || components === void 0 ? void 0 : components.IconRight) !== null && _a !== void 0 ? _a : IconRight;\n var IconLeftComponent = (_b = components === null || components === void 0 ? void 0 : components.IconLeft) !== null && _b !== void 0 ? _b : IconLeft;\n return (jsxs(\"div\", { className: classNames.nav, style: styles.nav, children: [!props.hidePrevious && (jsx(Button, { name: \"previous-month\", \"aria-label\": previousLabel, className: previousClassName, style: styles.nav_button_previous, disabled: !props.previousMonth, onClick: props.onPreviousClick, children: dir === 'rtl' ? (jsx(IconRightComponent, { className: classNames.nav_icon, style: styles.nav_icon })) : (jsx(IconLeftComponent, { className: classNames.nav_icon, style: styles.nav_icon })) })), !props.hideNext && (jsx(Button, { name: \"next-month\", \"aria-label\": nextLabel, className: nextClassName, style: styles.nav_button_next, disabled: !props.nextMonth, onClick: props.onNextClick, children: dir === 'rtl' ? (jsx(IconLeftComponent, { className: classNames.nav_icon, style: styles.nav_icon })) : (jsx(IconRightComponent, { className: classNames.nav_icon, style: styles.nav_icon })) }))] }));\n}\n\n/**\n * Render a caption with a button-based navigation.\n */\nfunction CaptionNavigation(props) {\n var numberOfMonths = useDayPicker().numberOfMonths;\n var _a = useNavigation(), previousMonth = _a.previousMonth, nextMonth = _a.nextMonth, goToMonth = _a.goToMonth, displayMonths = _a.displayMonths;\n var displayIndex = displayMonths.findIndex(function (month) {\n return isSameMonth(props.displayMonth, month);\n });\n var isFirst = displayIndex === 0;\n var isLast = displayIndex === displayMonths.length - 1;\n var hideNext = numberOfMonths > 1 && (isFirst || !isLast);\n var hidePrevious = numberOfMonths > 1 && (isLast || !isFirst);\n var handlePreviousClick = function () {\n if (!previousMonth)\n return;\n goToMonth(previousMonth);\n };\n var handleNextClick = function () {\n if (!nextMonth)\n return;\n goToMonth(nextMonth);\n };\n return (jsx(Navigation, { displayMonth: props.displayMonth, hideNext: hideNext, hidePrevious: hidePrevious, nextMonth: nextMonth, previousMonth: previousMonth, onPreviousClick: handlePreviousClick, onNextClick: handleNextClick }));\n}\n\n/**\n * Render the caption of a month. The caption has a different layout when\n * setting the {@link DayPickerBase.captionLayout} prop.\n */\nfunction Caption(props) {\n var _a;\n var _b = useDayPicker(), classNames = _b.classNames, disableNavigation = _b.disableNavigation, styles = _b.styles, captionLayout = _b.captionLayout, components = _b.components;\n var CaptionLabelComponent = (_a = components === null || components === void 0 ? void 0 : components.CaptionLabel) !== null && _a !== void 0 ? _a : CaptionLabel;\n var caption;\n if (disableNavigation) {\n caption = (jsx(CaptionLabelComponent, { id: props.id, displayMonth: props.displayMonth }));\n }\n else if (captionLayout === 'dropdown') {\n caption = (jsx(CaptionDropdowns, { displayMonth: props.displayMonth, id: props.id }));\n }\n else if (captionLayout === 'dropdown-buttons') {\n caption = (jsxs(Fragment, { children: [jsx(CaptionDropdowns, { displayMonth: props.displayMonth, displayIndex: props.displayIndex, id: props.id }), jsx(CaptionNavigation, { displayMonth: props.displayMonth, displayIndex: props.displayIndex, id: props.id })] }));\n }\n else {\n caption = (jsxs(Fragment, { children: [jsx(CaptionLabelComponent, { id: props.id, displayMonth: props.displayMonth, displayIndex: props.displayIndex }), jsx(CaptionNavigation, { displayMonth: props.displayMonth, id: props.id })] }));\n }\n return (jsx(\"div\", { className: classNames.caption, style: styles.caption, children: caption }));\n}\n\n/** Render the Footer component (empty as default).*/\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction Footer(props) {\n var _a = useDayPicker(), footer = _a.footer, styles = _a.styles, tfoot = _a.classNames.tfoot;\n if (!footer)\n return jsx(Fragment, {});\n return (jsx(\"tfoot\", { className: tfoot, style: styles.tfoot, children: jsx(\"tr\", { children: jsx(\"td\", { colSpan: 8, children: footer }) }) }));\n}\n\n/**\n * Generate a series of 7 days, starting from the week, to use for formatting\n * the weekday names (Monday, Tuesday, etc.).\n */\nfunction getWeekdays(locale, \n/** The index of the first day of the week (0 - Sunday). */\nweekStartsOn, \n/** Use ISOWeek instead of locale/ */\nISOWeek) {\n var start = ISOWeek\n ? startOfISOWeek(new Date())\n : startOfWeek(new Date(), { locale: locale, weekStartsOn: weekStartsOn });\n var days = [];\n for (var i = 0; i < 7; i++) {\n var day = addDays(start, i);\n days.push(day);\n }\n return days;\n}\n\n/**\n * Render the HeadRow component - i.e. the table head row with the weekday names.\n */\nfunction HeadRow() {\n var _a = useDayPicker(), classNames = _a.classNames, styles = _a.styles, showWeekNumber = _a.showWeekNumber, locale = _a.locale, weekStartsOn = _a.weekStartsOn, ISOWeek = _a.ISOWeek, formatWeekdayName = _a.formatters.formatWeekdayName, labelWeekday = _a.labels.labelWeekday;\n var weekdays = getWeekdays(locale, weekStartsOn, ISOWeek);\n return (jsxs(\"tr\", { style: styles.head_row, className: classNames.head_row, children: [showWeekNumber && (jsx(\"td\", { style: styles.head_cell, className: classNames.head_cell })), weekdays.map(function (weekday, i) { return (jsx(\"th\", { scope: \"col\", className: classNames.head_cell, style: styles.head_cell, \"aria-label\": labelWeekday(weekday, { locale: locale }), children: formatWeekdayName(weekday, { locale: locale }) }, i)); })] }));\n}\n\n/** Render the table head. */\nfunction Head() {\n var _a;\n var _b = useDayPicker(), classNames = _b.classNames, styles = _b.styles, components = _b.components;\n var HeadRowComponent = (_a = components === null || components === void 0 ? void 0 : components.HeadRow) !== null && _a !== void 0 ? _a : HeadRow;\n return (jsx(\"thead\", { style: styles.head, className: classNames.head, children: jsx(HeadRowComponent, {}) }));\n}\n\n/** Render the content of the day cell. */\nfunction DayContent(props) {\n var _a = useDayPicker(), locale = _a.locale, formatDay = _a.formatters.formatDay;\n return jsx(Fragment, { children: formatDay(props.date, { locale: locale }) });\n}\n\n/**\n * The SelectMultiple context shares details about the selected days when in\n * multiple selection mode.\n *\n * Access this context from the {@link useSelectMultiple} hook.\n */\nvar SelectMultipleContext = createContext(undefined);\n/** Provides the values for the {@link SelectMultipleContext}. */\nfunction SelectMultipleProvider(props) {\n if (!isDayPickerMultiple(props.initialProps)) {\n var emptyContextValue = {\n selected: undefined,\n modifiers: {\n disabled: []\n }\n };\n return (jsx(SelectMultipleContext.Provider, { value: emptyContextValue, children: props.children }));\n }\n return (jsx(SelectMultipleProviderInternal, { initialProps: props.initialProps, children: props.children }));\n}\nfunction SelectMultipleProviderInternal(_a) {\n var initialProps = _a.initialProps, children = _a.children;\n var selected = initialProps.selected, min = initialProps.min, max = initialProps.max;\n var onDayClick = function (day, activeModifiers, e) {\n var _a, _b;\n (_a = initialProps.onDayClick) === null || _a === void 0 ? void 0 : _a.call(initialProps, day, activeModifiers, e);\n var isMinSelected = Boolean(activeModifiers.selected && min && (selected === null || selected === void 0 ? void 0 : selected.length) === min);\n if (isMinSelected) {\n return;\n }\n var isMaxSelected = Boolean(!activeModifiers.selected && max && (selected === null || selected === void 0 ? void 0 : selected.length) === max);\n if (isMaxSelected) {\n return;\n }\n var selectedDays = selected ? __spreadArray([], selected, true) : [];\n if (activeModifiers.selected) {\n var index = selectedDays.findIndex(function (selectedDay) {\n return isSameDay(day, selectedDay);\n });\n selectedDays.splice(index, 1);\n }\n else {\n selectedDays.push(day);\n }\n (_b = initialProps.onSelect) === null || _b === void 0 ? void 0 : _b.call(initialProps, selectedDays, day, activeModifiers, e);\n };\n var modifiers = {\n disabled: []\n };\n if (selected) {\n modifiers.disabled.push(function (day) {\n var isMaxSelected = max && selected.length > max - 1;\n var isSelected = selected.some(function (selectedDay) {\n return isSameDay(selectedDay, day);\n });\n return Boolean(isMaxSelected && !isSelected);\n });\n }\n var contextValue = {\n selected: selected,\n onDayClick: onDayClick,\n modifiers: modifiers\n };\n return (jsx(SelectMultipleContext.Provider, { value: contextValue, children: children }));\n}\n/**\n * Hook to access the {@link SelectMultipleContextValue}.\n *\n * This hook is meant to be used inside internal or custom components.\n */\nfunction useSelectMultiple() {\n var context = useContext(SelectMultipleContext);\n if (!context) {\n throw new Error('useSelectMultiple must be used within a SelectMultipleProvider');\n }\n return context;\n}\n\n/**\n * Add a day to an existing range.\n *\n * The returned range takes in account the `undefined` values and if the added\n * day is already present in the range.\n */\nfunction addToRange(day, range) {\n var _a = range || {}, from = _a.from, to = _a.to;\n if (from && to) {\n if (isSameDay(to, day) && isSameDay(from, day)) {\n return undefined;\n }\n if (isSameDay(to, day)) {\n return { from: to, to: undefined };\n }\n if (isSameDay(from, day)) {\n return undefined;\n }\n if (isAfter(from, day)) {\n return { from: day, to: to };\n }\n return { from: from, to: day };\n }\n if (to) {\n if (isAfter(day, to)) {\n return { from: to, to: day };\n }\n return { from: day, to: to };\n }\n if (from) {\n if (isBefore(day, from)) {\n return { from: day, to: from };\n }\n return { from: from, to: day };\n }\n return { from: day, to: undefined };\n}\n\n/**\n * The SelectRange context shares details about the selected days when in\n * range selection mode.\n *\n * Access this context from the {@link useSelectRange} hook.\n */\nvar SelectRangeContext = createContext(undefined);\n/** Provides the values for the {@link SelectRangeProvider}. */\nfunction SelectRangeProvider(props) {\n if (!isDayPickerRange(props.initialProps)) {\n var emptyContextValue = {\n selected: undefined,\n modifiers: {\n range_start: [],\n range_end: [],\n range_middle: [],\n disabled: []\n }\n };\n return (jsx(SelectRangeContext.Provider, { value: emptyContextValue, children: props.children }));\n }\n return (jsx(SelectRangeProviderInternal, { initialProps: props.initialProps, children: props.children }));\n}\nfunction SelectRangeProviderInternal(_a) {\n var initialProps = _a.initialProps, children = _a.children;\n var selected = initialProps.selected;\n var _b = selected || {}, selectedFrom = _b.from, selectedTo = _b.to;\n var min = initialProps.min;\n var max = initialProps.max;\n var onDayClick = function (day, activeModifiers, e) {\n var _a, _b;\n (_a = initialProps.onDayClick) === null || _a === void 0 ? void 0 : _a.call(initialProps, day, activeModifiers, e);\n var newRange = addToRange(day, selected);\n (_b = initialProps.onSelect) === null || _b === void 0 ? void 0 : _b.call(initialProps, newRange, day, activeModifiers, e);\n };\n var modifiers = {\n range_start: [],\n range_end: [],\n range_middle: [],\n disabled: []\n };\n if (selectedFrom) {\n modifiers.range_start = [selectedFrom];\n if (!selectedTo) {\n modifiers.range_end = [selectedFrom];\n }\n else {\n modifiers.range_end = [selectedTo];\n if (!isSameDay(selectedFrom, selectedTo)) {\n modifiers.range_middle = [\n {\n after: selectedFrom,\n before: selectedTo\n }\n ];\n }\n }\n }\n else if (selectedTo) {\n modifiers.range_start = [selectedTo];\n modifiers.range_end = [selectedTo];\n }\n if (min) {\n if (selectedFrom && !selectedTo) {\n modifiers.disabled.push({\n after: subDays(selectedFrom, min - 1),\n before: addDays(selectedFrom, min - 1)\n });\n }\n if (selectedFrom && selectedTo) {\n modifiers.disabled.push({\n after: selectedFrom,\n before: addDays(selectedFrom, min - 1)\n });\n }\n if (!selectedFrom && selectedTo) {\n modifiers.disabled.push({\n after: subDays(selectedTo, min - 1),\n before: addDays(selectedTo, min - 1)\n });\n }\n }\n if (max) {\n if (selectedFrom && !selectedTo) {\n modifiers.disabled.push({\n before: addDays(selectedFrom, -max + 1)\n });\n modifiers.disabled.push({\n after: addDays(selectedFrom, max - 1)\n });\n }\n if (selectedFrom && selectedTo) {\n var selectedCount = differenceInCalendarDays(selectedTo, selectedFrom) + 1;\n var offset = max - selectedCount;\n modifiers.disabled.push({\n before: subDays(selectedFrom, offset)\n });\n modifiers.disabled.push({\n after: addDays(selectedTo, offset)\n });\n }\n if (!selectedFrom && selectedTo) {\n modifiers.disabled.push({\n before: addDays(selectedTo, -max + 1)\n });\n modifiers.disabled.push({\n after: addDays(selectedTo, max - 1)\n });\n }\n }\n return (jsx(SelectRangeContext.Provider, { value: { selected: selected, onDayClick: onDayClick, modifiers: modifiers }, children: children }));\n}\n/**\n * Hook to access the {@link SelectRangeContextValue}.\n *\n * This hook is meant to be used inside internal or custom components.\n */\nfunction useSelectRange() {\n var context = useContext(SelectRangeContext);\n if (!context) {\n throw new Error('useSelectRange must be used within a SelectRangeProvider');\n }\n return context;\n}\n\n/** Normalize to array a matcher input. */\nfunction matcherToArray(matcher) {\n if (Array.isArray(matcher)) {\n return __spreadArray([], matcher, true);\n }\n else if (matcher !== undefined) {\n return [matcher];\n }\n else {\n return [];\n }\n}\n\n/** Create CustomModifiers from dayModifiers */\nfunction getCustomModifiers(dayModifiers) {\n var customModifiers = {};\n Object.entries(dayModifiers).forEach(function (_a) {\n var modifier = _a[0], matcher = _a[1];\n customModifiers[modifier] = matcherToArray(matcher);\n });\n return customModifiers;\n}\n\n/** The name of the modifiers that are used internally by DayPicker. */\nvar InternalModifier;\n(function (InternalModifier) {\n InternalModifier[\"Outside\"] = \"outside\";\n /** Name of the modifier applied to the disabled days, using the `disabled` prop. */\n InternalModifier[\"Disabled\"] = \"disabled\";\n /** Name of the modifier applied to the selected days using the `selected` prop). */\n InternalModifier[\"Selected\"] = \"selected\";\n /** Name of the modifier applied to the hidden days using the `hidden` prop). */\n InternalModifier[\"Hidden\"] = \"hidden\";\n /** Name of the modifier applied to the day specified using the `today` prop). */\n InternalModifier[\"Today\"] = \"today\";\n /** The modifier applied to the day starting a selected range, when in range selection mode. */\n InternalModifier[\"RangeStart\"] = \"range_start\";\n /** The modifier applied to the day ending a selected range, when in range selection mode. */\n InternalModifier[\"RangeEnd\"] = \"range_end\";\n /** The modifier applied to the days between the start and the end of a selected range, when in range selection mode. */\n InternalModifier[\"RangeMiddle\"] = \"range_middle\";\n})(InternalModifier || (InternalModifier = {}));\n\nvar Selected = InternalModifier.Selected, Disabled = InternalModifier.Disabled, Hidden = InternalModifier.Hidden, Today = InternalModifier.Today, RangeEnd = InternalModifier.RangeEnd, RangeMiddle = InternalModifier.RangeMiddle, RangeStart = InternalModifier.RangeStart, Outside = InternalModifier.Outside;\n/** Return the {@link InternalModifiers} from the DayPicker and select contexts. */\nfunction getInternalModifiers(dayPicker, selectMultiple, selectRange) {\n var _a;\n var internalModifiers = (_a = {},\n _a[Selected] = matcherToArray(dayPicker.selected),\n _a[Disabled] = matcherToArray(dayPicker.disabled),\n _a[Hidden] = matcherToArray(dayPicker.hidden),\n _a[Today] = [dayPicker.today],\n _a[RangeEnd] = [],\n _a[RangeMiddle] = [],\n _a[RangeStart] = [],\n _a[Outside] = [],\n _a);\n if (dayPicker.fromDate) {\n internalModifiers[Disabled].push({ before: dayPicker.fromDate });\n }\n if (dayPicker.toDate) {\n internalModifiers[Disabled].push({ after: dayPicker.toDate });\n }\n if (isDayPickerMultiple(dayPicker)) {\n internalModifiers[Disabled] = internalModifiers[Disabled].concat(selectMultiple.modifiers[Disabled]);\n }\n else if (isDayPickerRange(dayPicker)) {\n internalModifiers[Disabled] = internalModifiers[Disabled].concat(selectRange.modifiers[Disabled]);\n internalModifiers[RangeStart] = selectRange.modifiers[RangeStart];\n internalModifiers[RangeMiddle] = selectRange.modifiers[RangeMiddle];\n internalModifiers[RangeEnd] = selectRange.modifiers[RangeEnd];\n }\n return internalModifiers;\n}\n\n/** The Modifiers context store the modifiers used in DayPicker. To access the value of this context, use {@link useModifiers}. */\nvar ModifiersContext = createContext(undefined);\n/** Provide the value for the {@link ModifiersContext}. */\nfunction ModifiersProvider(props) {\n var dayPicker = useDayPicker();\n var selectMultiple = useSelectMultiple();\n var selectRange = useSelectRange();\n var internalModifiers = getInternalModifiers(dayPicker, selectMultiple, selectRange);\n var customModifiers = getCustomModifiers(dayPicker.modifiers);\n var modifiers = __assign(__assign({}, internalModifiers), customModifiers);\n return (jsx(ModifiersContext.Provider, { value: modifiers, children: props.children }));\n}\n/**\n * Return the modifiers used by DayPicker.\n *\n * This hook is meant to be used inside internal or custom components.\n * Requires to be wrapped into {@link ModifiersProvider}.\n *\n */\nfunction useModifiers() {\n var context = useContext(ModifiersContext);\n if (!context) {\n throw new Error('useModifiers must be used within a ModifiersProvider');\n }\n return context;\n}\n\n/** Returns true if `matcher` is of type {@link DateInterval}. */\nfunction isDateInterval(matcher) {\n return Boolean(matcher &&\n typeof matcher === 'object' &&\n 'before' in matcher &&\n 'after' in matcher);\n}\n/** Returns true if `value` is a {@link DateRange} type. */\nfunction isDateRange(value) {\n return Boolean(value && typeof value === 'object' && 'from' in value);\n}\n/** Returns true if `value` is of type {@link DateAfter}. */\nfunction isDateAfterType(value) {\n return Boolean(value && typeof value === 'object' && 'after' in value);\n}\n/** Returns true if `value` is of type {@link DateBefore}. */\nfunction isDateBeforeType(value) {\n return Boolean(value && typeof value === 'object' && 'before' in value);\n}\n/** Returns true if `value` is a {@link DayOfWeek} type. */\nfunction isDayOfWeekType(value) {\n return Boolean(value && typeof value === 'object' && 'dayOfWeek' in value);\n}\n\n/** Return `true` whether `date` is inside `range`. */\nfunction isDateInRange(date, range) {\n var _a;\n var from = range.from, to = range.to;\n if (from && to) {\n var isRangeInverted = differenceInCalendarDays(to, from) < 0;\n if (isRangeInverted) {\n _a = [to, from], from = _a[0], to = _a[1];\n }\n var isInRange = differenceInCalendarDays(date, from) >= 0 &&\n differenceInCalendarDays(to, date) >= 0;\n return isInRange;\n }\n if (to) {\n return isSameDay(to, date);\n }\n if (from) {\n return isSameDay(from, date);\n }\n return false;\n}\n\n/** Returns true if `value` is a Date type. */\nfunction isDateType(value) {\n return isDate(value);\n}\n/** Returns true if `value` is an array of valid dates. */\nfunction isArrayOfDates(value) {\n return Array.isArray(value) && value.every(isDate);\n}\n/**\n * Returns whether a day matches against at least one of the given Matchers.\n *\n * ```\n * const day = new Date(2022, 5, 19);\n * const matcher1: DateRange = {\n * from: new Date(2021, 12, 21),\n * to: new Date(2021, 12, 30)\n * }\n * const matcher2: DateRange = {\n * from: new Date(2022, 5, 1),\n * to: new Date(2022, 5, 23)\n * }\n *\n * const isMatch(day, [matcher1, matcher2]); // true, since day is in the matcher1 range.\n * ```\n * */\nfunction isMatch(day, matchers) {\n return matchers.some(function (matcher) {\n if (typeof matcher === 'boolean') {\n return matcher;\n }\n if (isDateType(matcher)) {\n return isSameDay(day, matcher);\n }\n if (isArrayOfDates(matcher)) {\n return matcher.includes(day);\n }\n if (isDateRange(matcher)) {\n return isDateInRange(day, matcher);\n }\n if (isDayOfWeekType(matcher)) {\n return matcher.dayOfWeek.includes(day.getDay());\n }\n if (isDateInterval(matcher)) {\n var diffBefore = differenceInCalendarDays(matcher.before, day);\n var diffAfter = differenceInCalendarDays(matcher.after, day);\n var isDayBefore = diffBefore > 0;\n var isDayAfter = diffAfter < 0;\n var isClosedInterval = isAfter(matcher.before, matcher.after);\n if (isClosedInterval) {\n return isDayAfter && isDayBefore;\n }\n else {\n return isDayBefore || isDayAfter;\n }\n }\n if (isDateAfterType(matcher)) {\n return differenceInCalendarDays(day, matcher.after) > 0;\n }\n if (isDateBeforeType(matcher)) {\n return differenceInCalendarDays(matcher.before, day) > 0;\n }\n if (typeof matcher === 'function') {\n return matcher(day);\n }\n return false;\n });\n}\n\n/** Return the active modifiers for the given day. */\nfunction getActiveModifiers(day, \n/** The modifiers to match for the given date. */\nmodifiers, \n/** The month where the day is displayed, to add the \"outside\" modifiers. */\ndisplayMonth) {\n var matchedModifiers = Object.keys(modifiers).reduce(function (result, key) {\n var modifier = modifiers[key];\n if (isMatch(day, modifier)) {\n result.push(key);\n }\n return result;\n }, []);\n var activeModifiers = {};\n matchedModifiers.forEach(function (modifier) { return (activeModifiers[modifier] = true); });\n if (displayMonth && !isSameMonth(day, displayMonth)) {\n activeModifiers.outside = true;\n }\n return activeModifiers;\n}\n\n/**\n * Returns the day that should be the target of the focus when DayPicker is\n * rendered the first time.\n *\n * TODO: this function doesn't consider if the day is outside the month. We\n * implemented this check in `useDayRender` but it should probably go here. See\n * https://github.com/gpbl/react-day-picker/pull/1576\n */\nfunction getInitialFocusTarget(displayMonths, modifiers) {\n var firstDayInMonth = startOfMonth(displayMonths[0]);\n var lastDayInMonth = endOfMonth(displayMonths[displayMonths.length - 1]);\n // TODO: cleanup code\n var firstFocusableDay;\n var today;\n var date = firstDayInMonth;\n while (date <= lastDayInMonth) {\n var activeModifiers = getActiveModifiers(date, modifiers);\n var isFocusable = !activeModifiers.disabled && !activeModifiers.hidden;\n if (!isFocusable) {\n date = addDays(date, 1);\n continue;\n }\n if (activeModifiers.selected) {\n return date;\n }\n if (activeModifiers.today && !today) {\n today = date;\n }\n if (!firstFocusableDay) {\n firstFocusableDay = date;\n }\n date = addDays(date, 1);\n }\n if (today) {\n return today;\n }\n else {\n return firstFocusableDay;\n }\n}\n\nvar MAX_RETRY = 365;\n/** Return the next date to be focused. */\nfunction getNextFocus(focusedDay, options) {\n var moveBy = options.moveBy, direction = options.direction, context = options.context, modifiers = options.modifiers, _a = options.retry, retry = _a === void 0 ? { count: 0, lastFocused: focusedDay } : _a;\n var weekStartsOn = context.weekStartsOn, fromDate = context.fromDate, toDate = context.toDate, locale = context.locale;\n var moveFns = {\n day: addDays,\n week: addWeeks,\n month: addMonths,\n year: addYears,\n startOfWeek: function (date) {\n return context.ISOWeek\n ? startOfISOWeek(date)\n : startOfWeek(date, { locale: locale, weekStartsOn: weekStartsOn });\n },\n endOfWeek: function (date) {\n return context.ISOWeek\n ? endOfISOWeek(date)\n : endOfWeek(date, { locale: locale, weekStartsOn: weekStartsOn });\n }\n };\n var newFocusedDay = moveFns[moveBy](focusedDay, direction === 'after' ? 1 : -1);\n if (direction === 'before' && fromDate) {\n newFocusedDay = max([fromDate, newFocusedDay]);\n }\n else if (direction === 'after' && toDate) {\n newFocusedDay = min([toDate, newFocusedDay]);\n }\n var isFocusable = true;\n if (modifiers) {\n var activeModifiers = getActiveModifiers(newFocusedDay, modifiers);\n isFocusable = !activeModifiers.disabled && !activeModifiers.hidden;\n }\n if (isFocusable) {\n return newFocusedDay;\n }\n else {\n if (retry.count > MAX_RETRY) {\n return retry.lastFocused;\n }\n return getNextFocus(newFocusedDay, {\n moveBy: moveBy,\n direction: direction,\n context: context,\n modifiers: modifiers,\n retry: __assign(__assign({}, retry), { count: retry.count + 1 })\n });\n }\n}\n\n/**\n * The Focus context shares details about the focused day for the keyboard\n *\n * Access this context from the {@link useFocusContext} hook.\n */\nvar FocusContext = createContext(undefined);\n/** The provider for the {@link FocusContext}. */\nfunction FocusProvider(props) {\n var navigation = useNavigation();\n var modifiers = useModifiers();\n var _a = useState(), focusedDay = _a[0], setFocusedDay = _a[1];\n var _b = useState(), lastFocused = _b[0], setLastFocused = _b[1];\n var initialFocusTarget = getInitialFocusTarget(navigation.displayMonths, modifiers);\n // TODO: cleanup and test obscure code below\n var focusTarget = (focusedDay !== null && focusedDay !== void 0 ? focusedDay : (lastFocused && navigation.isDateDisplayed(lastFocused)))\n ? lastFocused\n : initialFocusTarget;\n var blur = function () {\n setLastFocused(focusedDay);\n setFocusedDay(undefined);\n };\n var focus = function (date) {\n setFocusedDay(date);\n };\n var context = useDayPicker();\n var moveFocus = function (moveBy, direction) {\n if (!focusedDay)\n return;\n var nextFocused = getNextFocus(focusedDay, {\n moveBy: moveBy,\n direction: direction,\n context: context,\n modifiers: modifiers\n });\n if (isSameDay(focusedDay, nextFocused))\n return undefined;\n navigation.goToDate(nextFocused, focusedDay);\n focus(nextFocused);\n };\n var value = {\n focusedDay: focusedDay,\n focusTarget: focusTarget,\n blur: blur,\n focus: focus,\n focusDayAfter: function () { return moveFocus('day', 'after'); },\n focusDayBefore: function () { return moveFocus('day', 'before'); },\n focusWeekAfter: function () { return moveFocus('week', 'after'); },\n focusWeekBefore: function () { return moveFocus('week', 'before'); },\n focusMonthBefore: function () { return moveFocus('month', 'before'); },\n focusMonthAfter: function () { return moveFocus('month', 'after'); },\n focusYearBefore: function () { return moveFocus('year', 'before'); },\n focusYearAfter: function () { return moveFocus('year', 'after'); },\n focusStartOfWeek: function () { return moveFocus('startOfWeek', 'before'); },\n focusEndOfWeek: function () { return moveFocus('endOfWeek', 'after'); }\n };\n return (jsx(FocusContext.Provider, { value: value, children: props.children }));\n}\n/**\n * Hook to access the {@link FocusContextValue}. Use this hook to handle the\n * focus state of the elements.\n *\n * This hook is meant to be used inside internal or custom components.\n */\nfunction useFocusContext() {\n var context = useContext(FocusContext);\n if (!context) {\n throw new Error('useFocusContext must be used within a FocusProvider');\n }\n return context;\n}\n\n/**\n * Return the active modifiers for the specified day.\n *\n * This hook is meant to be used inside internal or custom components.\n *\n * @param day\n * @param displayMonth\n */\nfunction useActiveModifiers(day, \n/**\n * The month where the date is displayed. If not the same as `date`, the day\n * is an \"outside day\".\n */\ndisplayMonth) {\n var modifiers = useModifiers();\n var activeModifiers = getActiveModifiers(day, modifiers, displayMonth);\n return activeModifiers;\n}\n\n/**\n * The SelectSingle context shares details about the selected days when in\n * single selection mode.\n *\n * Access this context from the {@link useSelectSingle} hook.\n */\nvar SelectSingleContext = createContext(undefined);\n/** Provides the values for the {@link SelectSingleProvider}. */\nfunction SelectSingleProvider(props) {\n if (!isDayPickerSingle(props.initialProps)) {\n var emptyContextValue = {\n selected: undefined\n };\n return (jsx(SelectSingleContext.Provider, { value: emptyContextValue, children: props.children }));\n }\n return (jsx(SelectSingleProviderInternal, { initialProps: props.initialProps, children: props.children }));\n}\nfunction SelectSingleProviderInternal(_a) {\n var initialProps = _a.initialProps, children = _a.children;\n var onDayClick = function (day, activeModifiers, e) {\n var _a, _b, _c;\n (_a = initialProps.onDayClick) === null || _a === void 0 ? void 0 : _a.call(initialProps, day, activeModifiers, e);\n if (activeModifiers.selected && !initialProps.required) {\n (_b = initialProps.onSelect) === null || _b === void 0 ? void 0 : _b.call(initialProps, undefined, day, activeModifiers, e);\n return;\n }\n (_c = initialProps.onSelect) === null || _c === void 0 ? void 0 : _c.call(initialProps, day, day, activeModifiers, e);\n };\n var contextValue = {\n selected: initialProps.selected,\n onDayClick: onDayClick\n };\n return (jsx(SelectSingleContext.Provider, { value: contextValue, children: children }));\n}\n/**\n * Hook to access the {@link SelectSingleContextValue}.\n *\n * This hook is meant to be used inside internal or custom components.\n */\nfunction useSelectSingle() {\n var context = useContext(SelectSingleContext);\n if (!context) {\n throw new Error('useSelectSingle must be used within a SelectSingleProvider');\n }\n return context;\n}\n\n/**\n * This hook returns details about the content to render in the day cell.\n *\n *\n * When a day cell is rendered in the table, DayPicker can either:\n *\n * - render nothing: when the day is outside the month or has matched the\n * \"hidden\" modifier.\n * - render a button when `onDayClick` or a selection mode is set.\n * - render a non-interactive element: when no selection mode is set, the day\n * cell shouldn’t respond to any interaction. DayPicker should render a `div`\n * or a `span`.\n *\n * ### Usage\n *\n * Use this hook to customize the behavior of the {@link Day} component. Create a\n * new `Day` component using this hook and pass it to the `components` prop.\n * The source of {@link Day} can be a good starting point.\n *\n */\nfunction useDayEventHandlers(date, activeModifiers) {\n var dayPicker = useDayPicker();\n var single = useSelectSingle();\n var multiple = useSelectMultiple();\n var range = useSelectRange();\n var _a = useFocusContext(), focusDayAfter = _a.focusDayAfter, focusDayBefore = _a.focusDayBefore, focusWeekAfter = _a.focusWeekAfter, focusWeekBefore = _a.focusWeekBefore, blur = _a.blur, focus = _a.focus, focusMonthBefore = _a.focusMonthBefore, focusMonthAfter = _a.focusMonthAfter, focusYearBefore = _a.focusYearBefore, focusYearAfter = _a.focusYearAfter, focusStartOfWeek = _a.focusStartOfWeek, focusEndOfWeek = _a.focusEndOfWeek;\n var onClick = function (e) {\n var _a, _b, _c, _d;\n if (isDayPickerSingle(dayPicker)) {\n (_a = single.onDayClick) === null || _a === void 0 ? void 0 : _a.call(single, date, activeModifiers, e);\n }\n else if (isDayPickerMultiple(dayPicker)) {\n (_b = multiple.onDayClick) === null || _b === void 0 ? void 0 : _b.call(multiple, date, activeModifiers, e);\n }\n else if (isDayPickerRange(dayPicker)) {\n (_c = range.onDayClick) === null || _c === void 0 ? void 0 : _c.call(range, date, activeModifiers, e);\n }\n else {\n (_d = dayPicker.onDayClick) === null || _d === void 0 ? void 0 : _d.call(dayPicker, date, activeModifiers, e);\n }\n };\n var onFocus = function (e) {\n var _a;\n focus(date);\n (_a = dayPicker.onDayFocus) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);\n };\n var onBlur = function (e) {\n var _a;\n blur();\n (_a = dayPicker.onDayBlur) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);\n };\n var onMouseEnter = function (e) {\n var _a;\n (_a = dayPicker.onDayMouseEnter) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);\n };\n var onMouseLeave = function (e) {\n var _a;\n (_a = dayPicker.onDayMouseLeave) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);\n };\n var onPointerEnter = function (e) {\n var _a;\n (_a = dayPicker.onDayPointerEnter) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);\n };\n var onPointerLeave = function (e) {\n var _a;\n (_a = dayPicker.onDayPointerLeave) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);\n };\n var onTouchCancel = function (e) {\n var _a;\n (_a = dayPicker.onDayTouchCancel) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);\n };\n var onTouchEnd = function (e) {\n var _a;\n (_a = dayPicker.onDayTouchEnd) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);\n };\n var onTouchMove = function (e) {\n var _a;\n (_a = dayPicker.onDayTouchMove) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);\n };\n var onTouchStart = function (e) {\n var _a;\n (_a = dayPicker.onDayTouchStart) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);\n };\n var onKeyUp = function (e) {\n var _a;\n (_a = dayPicker.onDayKeyUp) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);\n };\n var onKeyDown = function (e) {\n var _a;\n switch (e.key) {\n case 'ArrowLeft':\n e.preventDefault();\n e.stopPropagation();\n dayPicker.dir === 'rtl' ? focusDayAfter() : focusDayBefore();\n break;\n case 'ArrowRight':\n e.preventDefault();\n e.stopPropagation();\n dayPicker.dir === 'rtl' ? focusDayBefore() : focusDayAfter();\n break;\n case 'ArrowDown':\n e.preventDefault();\n e.stopPropagation();\n focusWeekAfter();\n break;\n case 'ArrowUp':\n e.preventDefault();\n e.stopPropagation();\n focusWeekBefore();\n break;\n case 'PageUp':\n e.preventDefault();\n e.stopPropagation();\n e.shiftKey ? focusYearBefore() : focusMonthBefore();\n break;\n case 'PageDown':\n e.preventDefault();\n e.stopPropagation();\n e.shiftKey ? focusYearAfter() : focusMonthAfter();\n break;\n case 'Home':\n e.preventDefault();\n e.stopPropagation();\n focusStartOfWeek();\n break;\n case 'End':\n e.preventDefault();\n e.stopPropagation();\n focusEndOfWeek();\n break;\n }\n (_a = dayPicker.onDayKeyDown) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);\n };\n var eventHandlers = {\n onClick: onClick,\n onFocus: onFocus,\n onBlur: onBlur,\n onKeyDown: onKeyDown,\n onKeyUp: onKeyUp,\n onMouseEnter: onMouseEnter,\n onMouseLeave: onMouseLeave,\n onPointerEnter: onPointerEnter,\n onPointerLeave: onPointerLeave,\n onTouchCancel: onTouchCancel,\n onTouchEnd: onTouchEnd,\n onTouchMove: onTouchMove,\n onTouchStart: onTouchStart\n };\n return eventHandlers;\n}\n\n/**\n * Return the current selected days when DayPicker is in selection mode. Days\n * selected by the custom selection mode are not returned.\n *\n * This hook is meant to be used inside internal or custom components.\n *\n */\nfunction useSelectedDays() {\n var dayPicker = useDayPicker();\n var single = useSelectSingle();\n var multiple = useSelectMultiple();\n var range = useSelectRange();\n var selectedDays = isDayPickerSingle(dayPicker)\n ? single.selected\n : isDayPickerMultiple(dayPicker)\n ? multiple.selected\n : isDayPickerRange(dayPicker)\n ? range.selected\n : undefined;\n return selectedDays;\n}\n\nfunction isInternalModifier(modifier) {\n return Object.values(InternalModifier).includes(modifier);\n}\n/**\n * Return the class names for the Day element, according to the given active\n * modifiers.\n *\n * Custom class names are set via `modifiersClassNames` or `classNames`,\n * where the first have the precedence.\n */\nfunction getDayClassNames(dayPicker, activeModifiers) {\n var classNames = [dayPicker.classNames.day];\n Object.keys(activeModifiers).forEach(function (modifier) {\n var customClassName = dayPicker.modifiersClassNames[modifier];\n if (customClassName) {\n classNames.push(customClassName);\n }\n else if (isInternalModifier(modifier)) {\n var internalClassName = dayPicker.classNames[\"day_\".concat(modifier)];\n if (internalClassName) {\n classNames.push(internalClassName);\n }\n }\n });\n return classNames;\n}\n\n/** Return the style for the Day element, according to the given active modifiers. */\nfunction getDayStyle(dayPicker, activeModifiers) {\n var style = __assign({}, dayPicker.styles.day);\n Object.keys(activeModifiers).forEach(function (modifier) {\n var _a;\n style = __assign(__assign({}, style), (_a = dayPicker.modifiersStyles) === null || _a === void 0 ? void 0 : _a[modifier]);\n });\n return style;\n}\n\n/**\n * Return props and data used to render the {@link Day} component.\n *\n * Use this hook when creating a component to replace the built-in `Day`\n * component.\n */\nfunction useDayRender(\n/** The date to render. */\nday, \n/** The month where the date is displayed (if not the same as `date`, it means it is an \"outside\" day). */\ndisplayMonth, \n/** A ref to the button element that will be target of focus when rendered (if required). */\nbuttonRef) {\n var _a;\n var _b, _c;\n var dayPicker = useDayPicker();\n var focusContext = useFocusContext();\n var activeModifiers = useActiveModifiers(day, displayMonth);\n var eventHandlers = useDayEventHandlers(day, activeModifiers);\n var selectedDays = useSelectedDays();\n var isButton = Boolean(dayPicker.onDayClick || dayPicker.mode !== 'default');\n // Focus the button if the day is focused according to the focus context\n useEffect(function () {\n var _a;\n if (activeModifiers.outside)\n return;\n if (!focusContext.focusedDay)\n return;\n if (!isButton)\n return;\n if (isSameDay(focusContext.focusedDay, day)) {\n (_a = buttonRef.current) === null || _a === void 0 ? void 0 : _a.focus();\n }\n }, [\n focusContext.focusedDay,\n day,\n buttonRef,\n isButton,\n activeModifiers.outside\n ]);\n var className = getDayClassNames(dayPicker, activeModifiers).join(' ');\n var style = getDayStyle(dayPicker, activeModifiers);\n var isHidden = Boolean((activeModifiers.outside && !dayPicker.showOutsideDays) ||\n activeModifiers.hidden);\n var DayContentComponent = (_c = (_b = dayPicker.components) === null || _b === void 0 ? void 0 : _b.DayContent) !== null && _c !== void 0 ? _c : DayContent;\n var children = (jsx(DayContentComponent, { date: day, displayMonth: displayMonth, activeModifiers: activeModifiers }));\n var divProps = {\n style: style,\n className: className,\n children: children,\n role: 'gridcell'\n };\n var isFocusTarget = focusContext.focusTarget &&\n isSameDay(focusContext.focusTarget, day) &&\n !activeModifiers.outside;\n var isFocused = focusContext.focusedDay && isSameDay(focusContext.focusedDay, day);\n var buttonProps = __assign(__assign(__assign({}, divProps), (_a = { disabled: activeModifiers.disabled, role: 'gridcell' }, _a['aria-selected'] = activeModifiers.selected, _a.tabIndex = isFocused || isFocusTarget ? 0 : -1, _a)), eventHandlers);\n var dayRender = {\n isButton: isButton,\n isHidden: isHidden,\n activeModifiers: activeModifiers,\n selectedDays: selectedDays,\n buttonProps: buttonProps,\n divProps: divProps\n };\n return dayRender;\n}\n\n/**\n * The content of a day cell – as a button or span element according to its\n * modifiers.\n */\nfunction Day(props) {\n var buttonRef = useRef(null);\n var dayRender = useDayRender(props.date, props.displayMonth, buttonRef);\n if (dayRender.isHidden) {\n return jsx(\"div\", { role: \"gridcell\" });\n }\n if (!dayRender.isButton) {\n return jsx(\"div\", __assign({}, dayRender.divProps));\n }\n return jsx(Button, __assign({ name: \"day\", ref: buttonRef }, dayRender.buttonProps));\n}\n\n/**\n * Render the week number element. If `onWeekNumberClick` is passed to DayPicker, it\n * renders a button, otherwise a span element.\n */\nfunction WeekNumber(props) {\n var weekNumber = props.number, dates = props.dates;\n var _a = useDayPicker(), onWeekNumberClick = _a.onWeekNumberClick, styles = _a.styles, classNames = _a.classNames, locale = _a.locale, labelWeekNumber = _a.labels.labelWeekNumber, formatWeekNumber = _a.formatters.formatWeekNumber;\n var content = formatWeekNumber(Number(weekNumber), { locale: locale });\n if (!onWeekNumberClick) {\n return (jsx(\"span\", { className: classNames.weeknumber, style: styles.weeknumber, children: content }));\n }\n var label = labelWeekNumber(Number(weekNumber), { locale: locale });\n var handleClick = function (e) {\n onWeekNumberClick(weekNumber, dates, e);\n };\n return (jsx(Button, { name: \"week-number\", \"aria-label\": label, className: classNames.weeknumber, style: styles.weeknumber, onClick: handleClick, children: content }));\n}\n\n/** Render a row in the calendar, with the days and the week number. */\nfunction Row(props) {\n var _a, _b;\n var _c = useDayPicker(), styles = _c.styles, classNames = _c.classNames, showWeekNumber = _c.showWeekNumber, components = _c.components;\n var DayComponent = (_a = components === null || components === void 0 ? void 0 : components.Day) !== null && _a !== void 0 ? _a : Day;\n var WeeknumberComponent = (_b = components === null || components === void 0 ? void 0 : components.WeekNumber) !== null && _b !== void 0 ? _b : WeekNumber;\n var weekNumberCell;\n if (showWeekNumber) {\n weekNumberCell = (jsx(\"td\", { className: classNames.cell, style: styles.cell, children: jsx(WeeknumberComponent, { number: props.weekNumber, dates: props.dates }) }));\n }\n return (jsxs(\"tr\", { className: classNames.row, style: styles.row, children: [weekNumberCell, props.dates.map(function (date) { return (jsx(\"td\", { className: classNames.cell, style: styles.cell, role: \"presentation\", children: jsx(DayComponent, { displayMonth: props.displayMonth, date: date }) }, getUnixTime(date))); })] }));\n}\n\n/** Return the weeks between two dates. */\nfunction daysToMonthWeeks(fromDate, toDate, options) {\n var toWeek = (options === null || options === void 0 ? void 0 : options.ISOWeek)\n ? endOfISOWeek(toDate)\n : endOfWeek(toDate, options);\n var fromWeek = (options === null || options === void 0 ? void 0 : options.ISOWeek)\n ? startOfISOWeek(fromDate)\n : startOfWeek(fromDate, options);\n var nOfDays = differenceInCalendarDays(toWeek, fromWeek);\n var days = [];\n for (var i = 0; i <= nOfDays; i++) {\n days.push(addDays(fromWeek, i));\n }\n var weeksInMonth = days.reduce(function (result, date) {\n var weekNumber = (options === null || options === void 0 ? void 0 : options.ISOWeek)\n ? getISOWeek(date)\n : getWeek(date, options);\n var existingWeek = result.find(function (value) { return value.weekNumber === weekNumber; });\n if (existingWeek) {\n existingWeek.dates.push(date);\n return result;\n }\n result.push({\n weekNumber: weekNumber,\n dates: [date]\n });\n return result;\n }, []);\n return weeksInMonth;\n}\n\n/**\n * Return the weeks belonging to the given month, adding the \"outside days\" to\n * the first and last week.\n */\nfunction getMonthWeeks(month, options) {\n var weeksInMonth = daysToMonthWeeks(startOfMonth(month), endOfMonth(month), options);\n if (options === null || options === void 0 ? void 0 : options.useFixedWeeks) {\n // Add extra weeks to the month, up to 6 weeks\n var nrOfMonthWeeks = getWeeksInMonth(month, options);\n if (nrOfMonthWeeks < 6) {\n var lastWeek = weeksInMonth[weeksInMonth.length - 1];\n var lastDate = lastWeek.dates[lastWeek.dates.length - 1];\n var toDate = addWeeks(lastDate, 6 - nrOfMonthWeeks);\n var extraWeeks = daysToMonthWeeks(addWeeks(lastDate, 1), toDate, options);\n weeksInMonth.push.apply(weeksInMonth, extraWeeks);\n }\n }\n return weeksInMonth;\n}\n\n/** Render the table with the calendar. */\nfunction Table(props) {\n var _a, _b, _c;\n var _d = useDayPicker(), locale = _d.locale, classNames = _d.classNames, styles = _d.styles, hideHead = _d.hideHead, fixedWeeks = _d.fixedWeeks, components = _d.components, weekStartsOn = _d.weekStartsOn, firstWeekContainsDate = _d.firstWeekContainsDate, ISOWeek = _d.ISOWeek;\n var weeks = getMonthWeeks(props.displayMonth, {\n useFixedWeeks: Boolean(fixedWeeks),\n ISOWeek: ISOWeek,\n locale: locale,\n weekStartsOn: weekStartsOn,\n firstWeekContainsDate: firstWeekContainsDate\n });\n var HeadComponent = (_a = components === null || components === void 0 ? void 0 : components.Head) !== null && _a !== void 0 ? _a : Head;\n var RowComponent = (_b = components === null || components === void 0 ? void 0 : components.Row) !== null && _b !== void 0 ? _b : Row;\n var FooterComponent = (_c = components === null || components === void 0 ? void 0 : components.Footer) !== null && _c !== void 0 ? _c : Footer;\n return (jsxs(\"table\", { id: props.id, className: classNames.table, style: styles.table, role: \"grid\", \"aria-labelledby\": props['aria-labelledby'], children: [!hideHead && jsx(HeadComponent, {}), jsx(\"tbody\", { className: classNames.tbody, style: styles.tbody, children: weeks.map(function (week) { return (jsx(RowComponent, { displayMonth: props.displayMonth, dates: week.dates, weekNumber: week.weekNumber }, week.weekNumber)); }) }), jsx(FooterComponent, { displayMonth: props.displayMonth })] }));\n}\n\n/*\nThe MIT License (MIT)\n\nCopyright (c) 2018-present, React Training LLC\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n/* eslint-disable prefer-const */\n/* eslint-disable @typescript-eslint/ban-ts-comment */\n/*\n * Welcome to @reach/auto-id!\n * Let's see if we can make sense of why this hook exists and its\n * implementation.\n *\n * Some background:\n * 1. Accessibility APIs rely heavily on element IDs\n * 2. Requiring developers to put IDs on every element in Reach UI is both\n * cumbersome and error-prone\n * 3. With a component model, we can generate IDs for them!\n *\n * Solution 1: Generate random IDs.\n *\n * This works great as long as you don't server render your app. When React (in\n * the client) tries to reuse the markup from the server, the IDs won't match\n * and React will then recreate the entire DOM tree.\n *\n * Solution 2: Increment an integer\n *\n * This sounds great. Since we're rendering the exact same tree on the server\n * and client, we can increment a counter and get a deterministic result between\n * client and server. Also, JS integers can go up to nine-quadrillion. I'm\n * pretty sure the tab will be closed before an app never needs\n * 10 quadrillion IDs!\n *\n * Problem solved, right?\n *\n * Ah, but there's a catch! React's concurrent rendering makes this approach\n * non-deterministic. While the client and server will end up with the same\n * elements in the end, depending on suspense boundaries (and possibly some user\n * input during the initial render) the incrementing integers won't always match\n * up.\n *\n * Solution 3: Don't use IDs at all on the server; patch after first render.\n *\n * What we've done here is solution 2 with some tricks. With this approach, the\n * ID returned is an empty string on the first render. This way the server and\n * client have the same markup no matter how wild the concurrent rendering may\n * have gotten.\n *\n * After the render, we patch up the components with an incremented ID. This\n * causes a double render on any components with `useId`. Shouldn't be a problem\n * since the components using this hook should be small, and we're only updating\n * the ID attribute on the DOM, nothing big is happening.\n *\n * It doesn't have to be an incremented number, though--we could do generate\n * random strings instead, but incrementing a number is probably the cheapest\n * thing we can do.\n *\n * Additionally, we only do this patchup on the very first client render ever.\n * Any calls to `useId` that happen dynamically in the client will be\n * populated immediately with a value. So, we only get the double render after\n * server hydration and never again, SO BACK OFF ALRIGHT?\n */\nfunction canUseDOM() {\n return !!(typeof window !== 'undefined' &&\n window.document &&\n window.document.createElement);\n}\n/**\n * React currently throws a warning when using useLayoutEffect on the server. To\n * get around it, we can conditionally useEffect on the server (no-op) and\n * useLayoutEffect in the browser. We occasionally need useLayoutEffect to\n * ensure we don't get a render flash for certain operations, but we may also\n * need affected components to render on the server. One example is when setting\n * a component's descendants to retrieve their index values.\n *\n * Important to note that using this hook as an escape hatch will break the\n * eslint dependency warnings unless you rename the import to `useLayoutEffect`.\n * Use sparingly only when the effect won't effect the rendered HTML to avoid\n * any server/client mismatch.\n *\n * If a useLayoutEffect is needed and the result would create a mismatch, it's\n * likely that the component in question shouldn't be rendered on the server at\n * all, so a better approach would be to lazily render those in a parent\n * component after client-side hydration.\n *\n * https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85\n * https://github.com/reduxjs/react-redux/blob/master/src/utils/useIsomorphicLayoutEffect.js\n *\n * @param effect\n * @param deps\n */\nvar useIsomorphicLayoutEffect = canUseDOM() ? useLayoutEffect : useEffect;\nvar serverHandoffComplete = false;\nvar id = 0;\nfunction genId() {\n return \"react-day-picker-\".concat(++id);\n}\nfunction useId(providedId) {\n // TODO: Remove error flag when updating internal deps to React 18. None of\n // our tricks will play well with concurrent rendering anyway.\n var _a;\n // If this instance isn't part of the initial render, we don't have to do the\n // double render/patch-up dance. We can just generate the ID and return it.\n var initialId = providedId !== null && providedId !== void 0 ? providedId : (serverHandoffComplete ? genId() : null);\n var _b = useState(initialId), id = _b[0], setId = _b[1];\n useIsomorphicLayoutEffect(function () {\n if (id === null) {\n // Patch the ID after render. We do this in `useLayoutEffect` to avoid any\n // rendering flicker, though it'll make the first render slower (unlikely\n // to matter, but you're welcome to measure your app and let us know if\n // it's a problem).\n setId(genId());\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n useEffect(function () {\n if (serverHandoffComplete === false) {\n // Flag all future uses of `useId` to skip the update dance. This is in\n // `useEffect` because it goes after `useLayoutEffect`, ensuring we don't\n // accidentally bail out of the patch-up dance prematurely.\n serverHandoffComplete = true;\n }\n }, []);\n return (_a = providedId !== null && providedId !== void 0 ? providedId : id) !== null && _a !== void 0 ? _a : undefined;\n}\n\n/** Render a month. */\nfunction Month(props) {\n var _a;\n var _b;\n var dayPicker = useDayPicker();\n var dir = dayPicker.dir, classNames = dayPicker.classNames, styles = dayPicker.styles, components = dayPicker.components;\n var displayMonths = useNavigation().displayMonths;\n var captionId = useId(dayPicker.id ? \"\".concat(dayPicker.id, \"-\").concat(props.displayIndex) : undefined);\n var tableId = dayPicker.id\n ? \"\".concat(dayPicker.id, \"-grid-\").concat(props.displayIndex)\n : undefined;\n var className = [classNames.month];\n var style = styles.month;\n var isStart = props.displayIndex === 0;\n var isEnd = props.displayIndex === displayMonths.length - 1;\n var isCenter = !isStart && !isEnd;\n if (dir === 'rtl') {\n _a = [isStart, isEnd], isEnd = _a[0], isStart = _a[1];\n }\n if (isStart) {\n className.push(classNames.caption_start);\n style = __assign(__assign({}, style), styles.caption_start);\n }\n if (isEnd) {\n className.push(classNames.caption_end);\n style = __assign(__assign({}, style), styles.caption_end);\n }\n if (isCenter) {\n className.push(classNames.caption_between);\n style = __assign(__assign({}, style), styles.caption_between);\n }\n var CaptionComponent = (_b = components === null || components === void 0 ? void 0 : components.Caption) !== null && _b !== void 0 ? _b : Caption;\n return (jsxs(\"div\", { className: className.join(' '), style: style, children: [jsx(CaptionComponent, { id: captionId, displayMonth: props.displayMonth, displayIndex: props.displayIndex }), jsx(Table, { id: tableId, \"aria-labelledby\": captionId, displayMonth: props.displayMonth })] }, props.displayIndex));\n}\n\n/**\n * Render the wrapper for the month grids.\n */\nfunction Months(props) {\n var _a = useDayPicker(), classNames = _a.classNames, styles = _a.styles;\n return (jsx(\"div\", { className: classNames.months, style: styles.months, children: props.children }));\n}\n\n/** Render the container with the months according to the number of months to display. */\nfunction Root(_a) {\n var _b, _c;\n var initialProps = _a.initialProps;\n var dayPicker = useDayPicker();\n var focusContext = useFocusContext();\n var navigation = useNavigation();\n var _d = useState(false), hasInitialFocus = _d[0], setHasInitialFocus = _d[1];\n // Focus the focus target when initialFocus is passed in\n useEffect(function () {\n if (!dayPicker.initialFocus)\n return;\n if (!focusContext.focusTarget)\n return;\n if (hasInitialFocus)\n return;\n focusContext.focus(focusContext.focusTarget);\n setHasInitialFocus(true);\n }, [\n dayPicker.initialFocus,\n hasInitialFocus,\n focusContext.focus,\n focusContext.focusTarget,\n focusContext\n ]);\n // Apply classnames according to props\n var classNames = [dayPicker.classNames.root, dayPicker.className];\n if (dayPicker.numberOfMonths > 1) {\n classNames.push(dayPicker.classNames.multiple_months);\n }\n if (dayPicker.showWeekNumber) {\n classNames.push(dayPicker.classNames.with_weeknumber);\n }\n var style = __assign(__assign({}, dayPicker.styles.root), dayPicker.style);\n var dataAttributes = Object.keys(initialProps)\n .filter(function (key) { return key.startsWith('data-'); })\n .reduce(function (attrs, key) {\n var _a;\n return __assign(__assign({}, attrs), (_a = {}, _a[key] = initialProps[key], _a));\n }, {});\n var MonthsComponent = (_c = (_b = initialProps.components) === null || _b === void 0 ? void 0 : _b.Months) !== null && _c !== void 0 ? _c : Months;\n return (jsx(\"div\", __assign({ className: classNames.join(' '), style: style, dir: dayPicker.dir, id: dayPicker.id, nonce: initialProps.nonce, title: initialProps.title, lang: initialProps.lang }, dataAttributes, { children: jsx(MonthsComponent, { children: navigation.displayMonths.map(function (month, i) { return (jsx(Month, { displayIndex: i, displayMonth: month }, i)); }) }) })));\n}\n\n/** Provide the value for all the context providers. */\nfunction RootProvider(props) {\n var children = props.children, initialProps = __rest(props, [\"children\"]);\n return (jsx(DayPickerProvider, { initialProps: initialProps, children: jsx(NavigationProvider, { children: jsx(SelectSingleProvider, { initialProps: initialProps, children: jsx(SelectMultipleProvider, { initialProps: initialProps, children: jsx(SelectRangeProvider, { initialProps: initialProps, children: jsx(ModifiersProvider, { children: jsx(FocusProvider, { children: children }) }) }) }) }) }) }));\n}\n\n/**\n * DayPicker render a date picker component to let users pick dates from a\n * calendar. See http://react-day-picker.js.org for updated documentation and\n * examples.\n *\n * ### Customization\n *\n * DayPicker offers different customization props. For example,\n *\n * - show multiple months using `numberOfMonths`\n * - display a dropdown to navigate the months via `captionLayout`\n * - display the week numbers with `showWeekNumbers`\n * - disable or hide days with `disabled` or `hidden`\n *\n * ### Controlling the months\n *\n * Change the initially displayed month using the `defaultMonth` prop. The\n * displayed months are controlled by DayPicker and stored in its internal\n * state. To control the months yourself, use `month` instead of `defaultMonth`\n * and use the `onMonthChange` event to set it.\n *\n * To limit the months the user can navigate to, use\n * `fromDate`/`fromMonth`/`fromYear` or `toDate`/`toMonth`/`toYear`.\n *\n * ### Selection modes\n *\n * DayPicker supports different selection mode that can be toggled using the\n * `mode` prop:\n *\n * - `mode=\"single\"`: only one day can be selected. Use `required` to make the\n * selection required. Use the `onSelect` event handler to get the selected\n * days.\n * - `mode=\"multiple\"`: users can select one or more days. Limit the amount of\n * days that can be selected with the `min` or the `max` props.\n * - `mode=\"range\"`: users can select a range of days. Limit the amount of days\n * in the range with the `min` or the `max` props.\n * - `mode=\"default\"` (default): the built-in selections are disabled. Implement\n * your own selection mode with `onDayClick`.\n *\n * The selection modes should cover the most common use cases. In case you\n * need a more refined way of selecting days, use `mode=\"default\"`. Use the\n * `selected` props and add the day event handlers to add/remove days from the\n * selection.\n *\n * ### Modifiers\n *\n * A _modifier_ represents different styles or states for the days displayed in\n * the calendar (like \"selected\" or \"disabled\"). Define custom modifiers using\n * the `modifiers` prop.\n *\n * ### Formatters and custom component\n *\n * You can customize how the content is displayed in the date picker by using\n * either the formatters or replacing the internal components.\n *\n * For the most common cases you want to use the `formatters` prop to change how\n * the content is formatted in the calendar. Use the `components` prop to\n * replace the internal components, like the navigation icons.\n *\n * ### Styling\n *\n * DayPicker comes with a default, basic style in `react-day-picker/style` – use\n * it as template for your own style.\n *\n * If you are using CSS modules, pass the imported styles object the\n * `classNames` props.\n *\n * You can also style the elements via inline styles using the `styles` prop.\n *\n * ### Form fields\n *\n * If you need to bind the date picker to a form field, you can use the\n * `useInput` hooks for a basic behavior. See the `useInput` source as an\n * example to bind the date picker with form fields.\n *\n * ### Localization\n *\n * To localize DayPicker, import the locale from `date-fns` package and use the\n * `locale` prop.\n *\n * For example, to use Spanish locale:\n *\n * ```\n * import { es } from 'date-fns/locale';\n * \n * ```\n */\nfunction DayPicker(props) {\n return (jsx(RootProvider, __assign({}, props, { children: jsx(Root, { initialProps: props }) })));\n}\n\n/** @private */\nfunction isValidDate(day) {\n return !isNaN(day.getTime());\n}\n\n/** Return props and setters for binding an input field to DayPicker. */\nfunction useInput(options) {\n if (options === void 0) { options = {}; }\n var _a = options.locale, locale = _a === void 0 ? enUS : _a, required = options.required, _b = options.format, format$1 = _b === void 0 ? 'PP' : _b, defaultSelected = options.defaultSelected, _c = options.today, today = _c === void 0 ? new Date() : _c;\n var _d = parseFromToProps(options), fromDate = _d.fromDate, toDate = _d.toDate;\n // Shortcut to the DateFns functions\n var parseValue = function (value) { return parse(value, format$1, today, { locale: locale }); };\n // Initialize states\n var _e = useState(defaultSelected !== null && defaultSelected !== void 0 ? defaultSelected : today), month = _e[0], setMonth = _e[1];\n var _f = useState(defaultSelected), selectedDay = _f[0], setSelectedDay = _f[1];\n var defaultInputValue = defaultSelected\n ? format(defaultSelected, format$1, { locale: locale })\n : '';\n var _g = useState(defaultInputValue), inputValue = _g[0], setInputValue = _g[1];\n var reset = function () {\n setSelectedDay(defaultSelected);\n setMonth(defaultSelected !== null && defaultSelected !== void 0 ? defaultSelected : today);\n setInputValue(defaultInputValue !== null && defaultInputValue !== void 0 ? defaultInputValue : '');\n };\n var setSelected = function (date) {\n setSelectedDay(date);\n setMonth(date !== null && date !== void 0 ? date : today);\n setInputValue(date ? format(date, format$1, { locale: locale }) : '');\n };\n var handleDayClick = function (day, _a) {\n var selected = _a.selected;\n if (!required && selected) {\n setSelectedDay(undefined);\n setInputValue('');\n return;\n }\n setSelectedDay(day);\n setInputValue(day ? format(day, format$1, { locale: locale }) : '');\n };\n var handleMonthChange = function (month) {\n setMonth(month);\n };\n // When changing the input field, save its value in state and check if the\n // string is a valid date. If it is a valid day, set it as selected and update\n // the calendar’s month.\n var handleChange = function (e) {\n setInputValue(e.target.value);\n var day = parseValue(e.target.value);\n var isBefore = fromDate && differenceInCalendarDays(fromDate, day) > 0;\n var isAfter = toDate && differenceInCalendarDays(day, toDate) > 0;\n if (!isValidDate(day) || isBefore || isAfter) {\n setSelectedDay(undefined);\n return;\n }\n setSelectedDay(day);\n setMonth(day);\n };\n // Special case for _required_ fields: on blur, if the value of the input is not\n // a valid date, reset the calendar and the input value.\n var handleBlur = function (e) {\n var day = parseValue(e.target.value);\n if (!isValidDate(day)) {\n reset();\n }\n };\n // When focusing, make sure DayPicker visualizes the month of the date in the\n // input field.\n var handleFocus = function (e) {\n if (!e.target.value) {\n reset();\n return;\n }\n var day = parseValue(e.target.value);\n if (isValidDate(day)) {\n setMonth(day);\n }\n };\n var dayPickerProps = {\n month: month,\n onDayClick: handleDayClick,\n onMonthChange: handleMonthChange,\n selected: selectedDay,\n locale: locale,\n fromDate: fromDate,\n toDate: toDate,\n today: today\n };\n var inputProps = {\n onBlur: handleBlur,\n onChange: handleChange,\n onFocus: handleFocus,\n value: inputValue,\n placeholder: format(new Date(), format$1, { locale: locale })\n };\n return { dayPickerProps: dayPickerProps, inputProps: inputProps, reset: reset, setSelected: setSelected };\n}\n\n/** Returns true when the props are of type {@link DayPickerDefaultProps}. */\nfunction isDayPickerDefault(props) {\n return props.mode === undefined || props.mode === 'default';\n}\n\nexport { Button, Caption, CaptionDropdowns, CaptionLabel, CaptionNavigation, Day, DayContent, DayPicker, DayPickerContext, DayPickerProvider, Dropdown, FocusContext, FocusProvider, Footer, Head, HeadRow, IconDropdown, IconLeft, IconRight, InternalModifier, Months, NavigationContext, NavigationProvider, RootProvider, Row, SelectMultipleContext, SelectMultipleProvider, SelectMultipleProviderInternal, SelectRangeContext, SelectRangeProvider, SelectRangeProviderInternal, SelectSingleContext, SelectSingleProvider, SelectSingleProviderInternal, WeekNumber, addToRange, isDateAfterType, isDateBeforeType, isDateInterval, isDateRange, isDayOfWeekType, isDayPickerDefault, isDayPickerMultiple, isDayPickerRange, isDayPickerSingle, isMatch, useActiveModifiers, useDayPicker, useDayRender, useFocusContext, useInput, useNavigation, useSelectMultiple, useSelectRange, useSelectSingle };\n//# sourceMappingURL=index.esm.js.map\n","import toDate from \"../toDate/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\n/**\n * @name startOfMonth\n * @category Month Helpers\n * @summary Return the start of a month for the given date.\n *\n * @description\n * Return the start of a month for the given date.\n * The result will be in the local timezone.\n *\n * @param {Date|Number} date - the original date\n * @returns {Date} the start of a month\n * @throws {TypeError} 1 argument required\n *\n * @example\n * // The start of a month for 2 September 2014 11:55:00:\n * const result = startOfMonth(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Mon Sep 01 2014 00:00:00\n */\nexport default function startOfMonth(dirtyDate) {\n requiredArgs(1, arguments);\n var date = toDate(dirtyDate);\n date.setDate(1);\n date.setHours(0, 0, 0, 0);\n return date;\n}","import toDate from \"../toDate/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\n/**\n * @name endOfMonth\n * @category Month Helpers\n * @summary Return the end of a month for the given date.\n *\n * @description\n * Return the end of a month for the given date.\n * The result will be in the local timezone.\n *\n * @param {Date|Number} date - the original date\n * @returns {Date} the end of a month\n * @throws {TypeError} 1 argument required\n *\n * @example\n * // The end of a month for 2 September 2014 11:55:00:\n * const result = endOfMonth(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 30 2014 23:59:59.999\n */\nexport default function endOfMonth(dirtyDate) {\n requiredArgs(1, arguments);\n var date = toDate(dirtyDate);\n var month = date.getMonth();\n date.setFullYear(date.getFullYear(), month + 1, 0);\n date.setHours(23, 59, 59, 999);\n return date;\n}","import toInteger from \"../_lib/toInteger/index.js\";\nimport toDate from \"../toDate/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\n/**\n * @name setYear\n * @category Year Helpers\n * @summary Set the year to the given date.\n *\n * @description\n * Set the year to the given date.\n *\n * @param {Date|Number} date - the date to be changed\n * @param {Number} year - the year of the new date\n * @returns {Date} the new date with the year set\n * @throws {TypeError} 2 arguments required\n *\n * @example\n * // Set year 2013 to 1 September 2014:\n * const result = setYear(new Date(2014, 8, 1), 2013)\n * //=> Sun Sep 01 2013 00:00:00\n */\nexport default function setYear(dirtyDate, dirtyYear) {\n requiredArgs(2, arguments);\n var date = toDate(dirtyDate);\n var year = toInteger(dirtyYear);\n\n // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date\n if (isNaN(date.getTime())) {\n return new Date(NaN);\n }\n date.setFullYear(year);\n return date;\n}","import toDate from \"../toDate/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\n/**\n * @name differenceInCalendarMonths\n * @category Month Helpers\n * @summary Get the number of calendar months between the given dates.\n *\n * @description\n * Get the number of calendar months between the given dates.\n *\n * @param {Date|Number} dateLeft - the later date\n * @param {Date|Number} dateRight - the earlier date\n * @returns {Number} the number of calendar months\n * @throws {TypeError} 2 arguments required\n *\n * @example\n * // How many calendar months are between 31 January 2014 and 1 September 2014?\n * const result = differenceInCalendarMonths(\n * new Date(2014, 8, 1),\n * new Date(2014, 0, 31)\n * )\n * //=> 8\n */\nexport default function differenceInCalendarMonths(dirtyDateLeft, dirtyDateRight) {\n requiredArgs(2, arguments);\n var dateLeft = toDate(dirtyDateLeft);\n var dateRight = toDate(dirtyDateRight);\n var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear();\n var monthDiff = dateLeft.getMonth() - dateRight.getMonth();\n return yearDiff * 12 + monthDiff;\n}","import toDate from \"../toDate/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\n/**\n * @name isSameMonth\n * @category Month Helpers\n * @summary Are the given dates in the same month (and year)?\n *\n * @description\n * Are the given dates in the same month (and year)?\n *\n * @param {Date|Number} dateLeft - the first date to check\n * @param {Date|Number} dateRight - the second date to check\n * @returns {Boolean} the dates are in the same month (and year)\n * @throws {TypeError} 2 arguments required\n *\n * @example\n * // Are 2 September 2014 and 25 September 2014 in the same month?\n * const result = isSameMonth(new Date(2014, 8, 2), new Date(2014, 8, 25))\n * //=> true\n *\n * @example\n * // Are 2 September 2014 and 25 September 2015 in the same month?\n * const result = isSameMonth(new Date(2014, 8, 2), new Date(2015, 8, 25))\n * //=> false\n */\nexport default function isSameMonth(dirtyDateLeft, dirtyDateRight) {\n requiredArgs(2, arguments);\n var dateLeft = toDate(dirtyDateLeft);\n var dateRight = toDate(dirtyDateRight);\n return dateLeft.getFullYear() === dateRight.getFullYear() && dateLeft.getMonth() === dateRight.getMonth();\n}","import toDate from \"../toDate/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\n/**\n * @name isBefore\n * @category Common Helpers\n * @summary Is the first date before the second one?\n *\n * @description\n * Is the first date before the second one?\n *\n * @param {Date|Number} date - the date that should be before the other one to return true\n * @param {Date|Number} dateToCompare - the date to compare with\n * @returns {Boolean} the first date is before the second date\n * @throws {TypeError} 2 arguments required\n *\n * @example\n * // Is 10 July 1989 before 11 February 1987?\n * const result = isBefore(new Date(1989, 6, 10), new Date(1987, 1, 11))\n * //=> false\n */\nexport default function isBefore(dirtyDate, dirtyDateToCompare) {\n requiredArgs(2, arguments);\n var date = toDate(dirtyDate);\n var dateToCompare = toDate(dirtyDateToCompare);\n return date.getTime() < dateToCompare.getTime();\n}","import toDate from \"../toDate/index.js\";\nimport toInteger from \"../_lib/toInteger/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\nimport { getDefaultOptions } from \"../_lib/defaultOptions/index.js\";\n/**\n * @name startOfWeek\n * @category Week Helpers\n * @summary Return the start of a week for the given date.\n *\n * @description\n * Return the start of a week for the given date.\n * The result will be in the local timezone.\n *\n * @param {Date|Number} date - the original date\n * @param {Object} [options] - an object with options.\n * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}\n * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)\n * @returns {Date} the start of a week\n * @throws {TypeError} 1 argument required\n * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6\n *\n * @example\n * // The start of a week for 2 September 2014 11:55:00:\n * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Sun Aug 31 2014 00:00:00\n *\n * @example\n * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00:\n * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })\n * //=> Mon Sep 01 2014 00:00:00\n */\nexport default function startOfWeek(dirtyDate, options) {\n var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;\n requiredArgs(1, arguments);\n var defaultOptions = getDefaultOptions();\n var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0);\n\n // Test if weekStartsOn is between 0 and 6 _and_ is not NaN\n if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {\n throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');\n }\n var date = toDate(dirtyDate);\n var day = date.getDay();\n var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;\n date.setDate(date.getDate() - diff);\n date.setHours(0, 0, 0, 0);\n return date;\n}","import startOfWeek from \"../startOfWeek/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\n/**\n * @name startOfISOWeek\n * @category ISO Week Helpers\n * @summary Return the start of an ISO week for the given date.\n *\n * @description\n * Return the start of an ISO week for the given date.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param {Date|Number} date - the original date\n * @returns {Date} the start of an ISO week\n * @throws {TypeError} 1 argument required\n *\n * @example\n * // The start of an ISO week for 2 September 2014 11:55:00:\n * const result = startOfISOWeek(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Mon Sep 01 2014 00:00:00\n */\nexport default function startOfISOWeek(dirtyDate) {\n requiredArgs(1, arguments);\n return startOfWeek(dirtyDate, {\n weekStartsOn: 1\n });\n}","import toInteger from \"../_lib/toInteger/index.js\";\nimport addDays from \"../addDays/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\n/**\n * @name addWeeks\n * @category Week Helpers\n * @summary Add the specified number of weeks to the given date.\n *\n * @description\n * Add the specified number of week to the given date.\n *\n * @param {Date|Number} date - the date to be changed\n * @param {Number} amount - the amount of weeks to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.\n * @returns {Date} the new date with the weeks added\n * @throws {TypeError} 2 arguments required\n *\n * @example\n * // Add 4 weeks to 1 September 2014:\n * const result = addWeeks(new Date(2014, 8, 1), 4)\n * //=> Mon Sep 29 2014 00:00:00\n */\nexport default function addWeeks(dirtyDate, dirtyAmount) {\n requiredArgs(2, arguments);\n var amount = toInteger(dirtyAmount);\n var days = amount * 7;\n return addDays(dirtyDate, days);\n}","import toInteger from \"../_lib/toInteger/index.js\";\nimport addMonths from \"../addMonths/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\n/**\n * @name addYears\n * @category Year Helpers\n * @summary Add the specified number of years to the given date.\n *\n * @description\n * Add the specified number of years to the given date.\n *\n * @param {Date|Number} date - the date to be changed\n * @param {Number} amount - the amount of years to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.\n * @returns {Date} the new date with the years added\n * @throws {TypeError} 2 arguments required\n *\n * @example\n * // Add 5 years to 1 September 2014:\n * const result = addYears(new Date(2014, 8, 1), 5)\n * //=> Sun Sep 01 2019 00:00:00\n */\nexport default function addYears(dirtyDate, dirtyAmount) {\n requiredArgs(2, arguments);\n var amount = toInteger(dirtyAmount);\n return addMonths(dirtyDate, amount * 12);\n}","import { getDefaultOptions } from \"../_lib/defaultOptions/index.js\";\nimport toDate from \"../toDate/index.js\";\nimport toInteger from \"../_lib/toInteger/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\n/**\n * @name endOfWeek\n * @category Week Helpers\n * @summary Return the end of a week for the given date.\n *\n * @description\n * Return the end of a week for the given date.\n * The result will be in the local timezone.\n *\n * @param {Date|Number} date - the original date\n * @param {Object} [options] - an object with options.\n * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}\n * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)\n * @returns {Date} the end of a week\n * @throws {TypeError} 1 argument required\n * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6\n *\n * @example\n * // The end of a week for 2 September 2014 11:55:00:\n * const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Sat Sep 06 2014 23:59:59.999\n *\n * @example\n * // If the week starts on Monday, the end of the week for 2 September 2014 11:55:00:\n * const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })\n * //=> Sun Sep 07 2014 23:59:59.999\n */\nexport default function endOfWeek(dirtyDate, options) {\n var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;\n requiredArgs(1, arguments);\n var defaultOptions = getDefaultOptions();\n var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0);\n\n // Test if weekStartsOn is between 0 and 6 _and_ is not NaN\n if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {\n throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');\n }\n var date = toDate(dirtyDate);\n var day = date.getDay();\n var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn);\n date.setDate(date.getDate() + diff);\n date.setHours(23, 59, 59, 999);\n return date;\n}","import endOfWeek from \"../endOfWeek/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\n/**\n * @name endOfISOWeek\n * @category ISO Week Helpers\n * @summary Return the end of an ISO week for the given date.\n *\n * @description\n * Return the end of an ISO week for the given date.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param {Date|Number} date - the original date\n * @returns {Date} the end of an ISO week\n * @throws {TypeError} 1 argument required\n *\n * @example\n * // The end of an ISO week for 2 September 2014 11:55:00:\n * const result = endOfISOWeek(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Sun Sep 07 2014 23:59:59.999\n */\nexport default function endOfISOWeek(dirtyDate) {\n requiredArgs(1, arguments);\n return endOfWeek(dirtyDate, {\n weekStartsOn: 1\n });\n}","import toDate from \"../toDate/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\n/**\n * @name isSameYear\n * @category Year Helpers\n * @summary Are the given dates in the same year?\n *\n * @description\n * Are the given dates in the same year?\n *\n * @param {Date|Number} dateLeft - the first date to check\n * @param {Date|Number} dateRight - the second date to check\n * @returns {Boolean} the dates are in the same year\n * @throws {TypeError} 2 arguments required\n *\n * @example\n * // Are 2 September 2014 and 25 September 2014 in the same year?\n * const result = isSameYear(new Date(2014, 8, 2), new Date(2014, 8, 25))\n * //=> true\n */\nexport default function isSameYear(dirtyDateLeft, dirtyDateRight) {\n requiredArgs(2, arguments);\n var dateLeft = toDate(dirtyDateLeft);\n var dateRight = toDate(dirtyDateRight);\n return dateLeft.getFullYear() === dateRight.getFullYear();\n}","import toDate from \"../toDate/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\n/**\n * @name startOfYear\n * @category Year Helpers\n * @summary Return the start of a year for the given date.\n *\n * @description\n * Return the start of a year for the given date.\n * The result will be in the local timezone.\n *\n * @param {Date|Number} date - the original date\n * @returns {Date} the start of a year\n * @throws {TypeError} 1 argument required\n *\n * @example\n * // The start of a year for 2 September 2014 11:55:00:\n * const result = startOfYear(new Date(2014, 8, 2, 11, 55, 00))\n * //=> Wed Jan 01 2014 00:00:00\n */\nexport default function startOfYear(dirtyDate) {\n requiredArgs(1, arguments);\n var cleanDate = toDate(dirtyDate);\n var date = new Date(0);\n date.setFullYear(cleanDate.getFullYear(), 0, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n}","import _typeof from \"@babel/runtime/helpers/esm/typeof\";\nimport toDate from \"../toDate/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\n/**\n * @name max\n * @category Common Helpers\n * @summary Return the latest of the given dates.\n *\n * @description\n * Return the latest of the given dates.\n *\n * @param {Date[]|Number[]} datesArray - the dates to compare\n * @returns {Date} the latest of the dates\n * @throws {TypeError} 1 argument required\n *\n * @example\n * // Which of these dates is the latest?\n * const result = max([\n * new Date(1989, 6, 10),\n * new Date(1987, 1, 11),\n * new Date(1995, 6, 2),\n * new Date(1990, 0, 1)\n * ])\n * //=> Sun Jul 02 1995 00:00:00\n */\nexport default function max(dirtyDatesArray) {\n requiredArgs(1, arguments);\n var datesArray;\n // `dirtyDatesArray` is Array, Set or Map, or object with custom `forEach` method\n if (dirtyDatesArray && typeof dirtyDatesArray.forEach === 'function') {\n datesArray = dirtyDatesArray;\n\n // If `dirtyDatesArray` is Array-like Object, convert to Array.\n } else if (_typeof(dirtyDatesArray) === 'object' && dirtyDatesArray !== null) {\n datesArray = Array.prototype.slice.call(dirtyDatesArray);\n } else {\n // `dirtyDatesArray` is non-iterable, return Invalid Date\n return new Date(NaN);\n }\n var result;\n datesArray.forEach(function (dirtyDate) {\n var currentDate = toDate(dirtyDate);\n if (result === undefined || result < currentDate || isNaN(Number(currentDate))) {\n result = currentDate;\n }\n });\n return result || new Date(NaN);\n}","import _typeof from \"@babel/runtime/helpers/esm/typeof\";\nimport toDate from \"../toDate/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\n/**\n * @name min\n * @category Common Helpers\n * @summary Returns the earliest of the given dates.\n *\n * @description\n * Returns the earliest of the given dates.\n *\n * @param {Date[]|Number[]} datesArray - the dates to compare\n * @returns {Date} - the earliest of the dates\n * @throws {TypeError} 1 argument required\n *\n * @example\n * // Which of these dates is the earliest?\n * const result = min([\n * new Date(1989, 6, 10),\n * new Date(1987, 1, 11),\n * new Date(1995, 6, 2),\n * new Date(1990, 0, 1)\n * ])\n * //=> Wed Feb 11 1987 00:00:00\n */\nexport default function min(dirtyDatesArray) {\n requiredArgs(1, arguments);\n var datesArray;\n // `dirtyDatesArray` is Array, Set or Map, or object with custom `forEach` method\n if (dirtyDatesArray && typeof dirtyDatesArray.forEach === 'function') {\n datesArray = dirtyDatesArray;\n // If `dirtyDatesArray` is Array-like Object, convert to Array.\n } else if (_typeof(dirtyDatesArray) === 'object' && dirtyDatesArray !== null) {\n datesArray = Array.prototype.slice.call(dirtyDatesArray);\n } else {\n // `dirtyDatesArray` is non-iterable, return Invalid Date\n return new Date(NaN);\n }\n var result;\n datesArray.forEach(function (dirtyDate) {\n var currentDate = toDate(dirtyDate);\n if (result === undefined || result > currentDate || isNaN(currentDate.getDate())) {\n result = currentDate;\n }\n });\n return result || new Date(NaN);\n}","import getTime from \"../getTime/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\n/**\n * @name getUnixTime\n * @category Timestamp Helpers\n * @summary Get the seconds timestamp of the given date.\n *\n * @description\n * Get the seconds timestamp of the given date.\n *\n * @param {Date|Number} date - the given date\n * @returns {Number} the timestamp\n * @throws {TypeError} 1 argument required\n *\n * @example\n * // Get the timestamp of 29 February 2012 11:45:05 CET:\n * const result = getUnixTime(new Date(2012, 1, 29, 11, 45, 5))\n * //=> 1330512305\n */\nexport default function getUnixTime(dirtyDate) {\n requiredArgs(1, arguments);\n return Math.floor(getTime(dirtyDate) / 1000);\n}","import toDate from \"../toDate/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\n/**\n * @name getTime\n * @category Timestamp Helpers\n * @summary Get the milliseconds timestamp of the given date.\n *\n * @description\n * Get the milliseconds timestamp of the given date.\n *\n * @param {Date|Number} date - the given date\n * @returns {Number} the timestamp\n * @throws {TypeError} 1 argument required\n *\n * @example\n * // Get the timestamp of 29 February 2012 11:45:05.123:\n * const result = getTime(new Date(2012, 1, 29, 11, 45, 5, 123))\n * //=> 1330515905123\n */\nexport default function getTime(dirtyDate) {\n requiredArgs(1, arguments);\n var date = toDate(dirtyDate);\n var timestamp = date.getTime();\n return timestamp;\n}","import toDate from \"../toDate/index.js\";\nimport startOfISOWeek from \"../startOfISOWeek/index.js\";\nimport startOfISOWeekYear from \"../startOfISOWeekYear/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\nvar MILLISECONDS_IN_WEEK = 604800000;\n\n/**\n * @name getISOWeek\n * @category ISO Week Helpers\n * @summary Get the ISO week of the given date.\n *\n * @description\n * Get the ISO week of the given date.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param {Date|Number} date - the given date\n * @returns {Number} the ISO week\n * @throws {TypeError} 1 argument required\n *\n * @example\n * // Which week of the ISO-week numbering year is 2 January 2005?\n * const result = getISOWeek(new Date(2005, 0, 2))\n * //=> 53\n */\nexport default function getISOWeek(dirtyDate) {\n requiredArgs(1, arguments);\n var date = toDate(dirtyDate);\n var diff = startOfISOWeek(date).getTime() - startOfISOWeekYear(date).getTime();\n\n // Round the number of days to the nearest integer\n // because the number of milliseconds in a week is not constant\n // (e.g. it's different in the week of the daylight saving time clock shift)\n return Math.round(diff / MILLISECONDS_IN_WEEK) + 1;\n}","import getISOWeekYear from \"../getISOWeekYear/index.js\";\nimport startOfISOWeek from \"../startOfISOWeek/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\n/**\n * @name startOfISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Return the start of an ISO week-numbering year for the given date.\n *\n * @description\n * Return the start of an ISO week-numbering year,\n * which always starts 3 days before the year's first Thursday.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param {Date|Number} date - the original date\n * @returns {Date} the start of an ISO week-numbering year\n * @throws {TypeError} 1 argument required\n *\n * @example\n * // The start of an ISO week-numbering year for 2 July 2005:\n * const result = startOfISOWeekYear(new Date(2005, 6, 2))\n * //=> Mon Jan 03 2005 00:00:00\n */\nexport default function startOfISOWeekYear(dirtyDate) {\n requiredArgs(1, arguments);\n var year = getISOWeekYear(dirtyDate);\n var fourthOfJanuary = new Date(0);\n fourthOfJanuary.setFullYear(year, 0, 4);\n fourthOfJanuary.setHours(0, 0, 0, 0);\n var date = startOfISOWeek(fourthOfJanuary);\n return date;\n}","import toDate from \"../toDate/index.js\";\nimport startOfISOWeek from \"../startOfISOWeek/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\n/**\n * @name getISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Get the ISO week-numbering year of the given date.\n *\n * @description\n * Get the ISO week-numbering year of the given date,\n * which always starts 3 days before the year's first Thursday.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param {Date|Number} date - the given date\n * @returns {Number} the ISO week-numbering year\n * @throws {TypeError} 1 argument required\n *\n * @example\n * // Which ISO-week numbering year is 2 January 2005?\n * const result = getISOWeekYear(new Date(2005, 0, 2))\n * //=> 2004\n */\nexport default function getISOWeekYear(dirtyDate) {\n requiredArgs(1, arguments);\n var date = toDate(dirtyDate);\n var year = date.getFullYear();\n var fourthOfJanuaryOfNextYear = new Date(0);\n fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4);\n fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0);\n var startOfNextYear = startOfISOWeek(fourthOfJanuaryOfNextYear);\n var fourthOfJanuaryOfThisYear = new Date(0);\n fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4);\n fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0);\n var startOfThisYear = startOfISOWeek(fourthOfJanuaryOfThisYear);\n if (date.getTime() >= startOfNextYear.getTime()) {\n return year + 1;\n } else if (date.getTime() >= startOfThisYear.getTime()) {\n return year;\n } else {\n return year - 1;\n }\n}","import startOfWeek from \"../startOfWeek/index.js\";\nimport startOfWeekYear from \"../startOfWeekYear/index.js\";\nimport toDate from \"../toDate/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\nvar MILLISECONDS_IN_WEEK = 604800000;\n\n/**\n * @name getWeek\n * @category Week Helpers\n * @summary Get the local week index of the given date.\n *\n * @description\n * Get the local week index of the given date.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#Week_numbering\n *\n * @param {Date|Number} date - the given date\n * @param {Object} [options] - an object with options.\n * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}\n * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)\n * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year\n * @returns {Number} the week\n * @throws {TypeError} 1 argument required\n * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6\n * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7\n *\n * @example\n * // Which week of the local week numbering year is 2 January 2005 with default options?\n * const result = getWeek(new Date(2005, 0, 2))\n * //=> 2\n *\n * // Which week of the local week numbering year is 2 January 2005,\n * // if Monday is the first day of the week,\n * // and the first week of the year always contains 4 January?\n * const result = getWeek(new Date(2005, 0, 2), {\n * weekStartsOn: 1,\n * firstWeekContainsDate: 4\n * })\n * //=> 53\n */\n\nexport default function getWeek(dirtyDate, options) {\n requiredArgs(1, arguments);\n var date = toDate(dirtyDate);\n var diff = startOfWeek(date, options).getTime() - startOfWeekYear(date, options).getTime();\n\n // Round the number of days to the nearest integer\n // because the number of milliseconds in a week is not constant\n // (e.g. it's different in the week of the daylight saving time clock shift)\n return Math.round(diff / MILLISECONDS_IN_WEEK) + 1;\n}","import getWeekYear from \"../getWeekYear/index.js\";\nimport startOfWeek from \"../startOfWeek/index.js\";\nimport toInteger from \"../_lib/toInteger/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\nimport { getDefaultOptions } from \"../_lib/defaultOptions/index.js\";\n/**\n * @name startOfWeekYear\n * @category Week-Numbering Year Helpers\n * @summary Return the start of a local week-numbering year for the given date.\n *\n * @description\n * Return the start of a local week-numbering year.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#Week_numbering\n *\n * @param {Date|Number} date - the original date\n * @param {Object} [options] - an object with options.\n * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}\n * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)\n * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year\n * @returns {Date} the start of a week-numbering year\n * @throws {TypeError} 1 argument required\n * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6\n * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7\n *\n * @example\n * // The start of an a week-numbering year for 2 July 2005 with default settings:\n * const result = startOfWeekYear(new Date(2005, 6, 2))\n * //=> Sun Dec 26 2004 00:00:00\n *\n * @example\n * // The start of a week-numbering year for 2 July 2005\n * // if Monday is the first day of week\n * // and 4 January is always in the first week of the year:\n * const result = startOfWeekYear(new Date(2005, 6, 2), {\n * weekStartsOn: 1,\n * firstWeekContainsDate: 4\n * })\n * //=> Mon Jan 03 2005 00:00:00\n */\nexport default function startOfWeekYear(dirtyDate, options) {\n var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;\n requiredArgs(1, arguments);\n var defaultOptions = getDefaultOptions();\n var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1);\n var year = getWeekYear(dirtyDate, options);\n var firstWeek = new Date(0);\n firstWeek.setFullYear(year, 0, firstWeekContainsDate);\n firstWeek.setHours(0, 0, 0, 0);\n var date = startOfWeek(firstWeek, options);\n return date;\n}","import startOfWeek from \"../startOfWeek/index.js\";\nimport toDate from \"../toDate/index.js\";\nimport toInteger from \"../_lib/toInteger/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\nimport { getDefaultOptions } from \"../_lib/defaultOptions/index.js\";\n/**\n * @name getWeekYear\n * @category Week-Numbering Year Helpers\n * @summary Get the local week-numbering year of the given date.\n *\n * @description\n * Get the local week-numbering year of the given date.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#Week_numbering\n *\n * @param {Date|Number} date - the given date\n * @param {Object} [options] - an object with options.\n * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}\n * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)\n * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year\n * @returns {Number} the local week-numbering year\n * @throws {TypeError} 1 argument required\n * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6\n * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7\n *\n * @example\n * // Which week numbering year is 26 December 2004 with the default settings?\n * const result = getWeekYear(new Date(2004, 11, 26))\n * //=> 2005\n *\n * @example\n * // Which week numbering year is 26 December 2004 if week starts on Saturday?\n * const result = getWeekYear(new Date(2004, 11, 26), { weekStartsOn: 6 })\n * //=> 2004\n *\n * @example\n * // Which week numbering year is 26 December 2004 if the first week contains 4 January?\n * const result = getWeekYear(new Date(2004, 11, 26), { firstWeekContainsDate: 4 })\n * //=> 2004\n */\nexport default function getWeekYear(dirtyDate, options) {\n var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;\n requiredArgs(1, arguments);\n var date = toDate(dirtyDate);\n var year = date.getFullYear();\n var defaultOptions = getDefaultOptions();\n var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1);\n\n // Test if weekStartsOn is between 1 and 7 _and_ is not NaN\n if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {\n throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');\n }\n var firstWeekOfNextYear = new Date(0);\n firstWeekOfNextYear.setFullYear(year + 1, 0, firstWeekContainsDate);\n firstWeekOfNextYear.setHours(0, 0, 0, 0);\n var startOfNextYear = startOfWeek(firstWeekOfNextYear, options);\n var firstWeekOfThisYear = new Date(0);\n firstWeekOfThisYear.setFullYear(year, 0, firstWeekContainsDate);\n firstWeekOfThisYear.setHours(0, 0, 0, 0);\n var startOfThisYear = startOfWeek(firstWeekOfThisYear, options);\n if (date.getTime() >= startOfNextYear.getTime()) {\n return year + 1;\n } else if (date.getTime() >= startOfThisYear.getTime()) {\n return year;\n } else {\n return year - 1;\n }\n}","import differenceInCalendarWeeks from \"../differenceInCalendarWeeks/index.js\";\nimport lastDayOfMonth from \"../lastDayOfMonth/index.js\";\nimport startOfMonth from \"../startOfMonth/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\n/**\n * @name getWeeksInMonth\n * @category Week Helpers\n * @summary Get the number of calendar weeks a month spans.\n *\n * @description\n * Get the number of calendar weeks the month in the given date spans.\n *\n * @param {Date|Number} date - the given date\n * @param {Object} [options] - an object with options.\n * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}\n * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)\n * @returns {Number} the number of calendar weeks\n * @throws {TypeError} 2 arguments required\n * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6\n *\n * @example\n * // How many calendar weeks does February 2015 span?\n * const result = getWeeksInMonth(new Date(2015, 1, 8))\n * //=> 4\n *\n * @example\n * // If the week starts on Monday,\n * // how many calendar weeks does July 2017 span?\n * const result = getWeeksInMonth(new Date(2017, 6, 5), { weekStartsOn: 1 })\n * //=> 6\n */\nexport default function getWeeksInMonth(date, options) {\n requiredArgs(1, arguments);\n return differenceInCalendarWeeks(lastDayOfMonth(date), startOfMonth(date), options) + 1;\n}","import startOfWeek from \"../startOfWeek/index.js\";\nimport getTimezoneOffsetInMilliseconds from \"../_lib/getTimezoneOffsetInMilliseconds/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\nvar MILLISECONDS_IN_WEEK = 604800000;\n\n/**\n * @name differenceInCalendarWeeks\n * @category Week Helpers\n * @summary Get the number of calendar weeks between the given dates.\n *\n * @description\n * Get the number of calendar weeks between the given dates.\n *\n * @param {Date|Number} dateLeft - the later date\n * @param {Date|Number} dateRight - the earlier date\n * @param {Object} [options] - an object with options.\n * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}\n * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)\n * @returns {Number} the number of calendar weeks\n * @throws {TypeError} 2 arguments required\n * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6\n *\n * @example\n * // How many calendar weeks are between 5 July 2014 and 20 July 2014?\n * const result = differenceInCalendarWeeks(\n * new Date(2014, 6, 20),\n * new Date(2014, 6, 5)\n * )\n * //=> 3\n *\n * @example\n * // If the week starts on Monday,\n * // how many calendar weeks are between 5 July 2014 and 20 July 2014?\n * const result = differenceInCalendarWeeks(\n * new Date(2014, 6, 20),\n * new Date(2014, 6, 5),\n * { weekStartsOn: 1 }\n * )\n * //=> 2\n */\nexport default function differenceInCalendarWeeks(dirtyDateLeft, dirtyDateRight, options) {\n requiredArgs(2, arguments);\n var startOfWeekLeft = startOfWeek(dirtyDateLeft, options);\n var startOfWeekRight = startOfWeek(dirtyDateRight, options);\n var timestampLeft = startOfWeekLeft.getTime() - getTimezoneOffsetInMilliseconds(startOfWeekLeft);\n var timestampRight = startOfWeekRight.getTime() - getTimezoneOffsetInMilliseconds(startOfWeekRight);\n\n // Round the number of days to the nearest integer\n // because the number of milliseconds in a week is not constant\n // (e.g. it's different in the week of the daylight saving time clock shift)\n return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_WEEK);\n}","import toDate from \"../toDate/index.js\";\nimport requiredArgs from \"../_lib/requiredArgs/index.js\";\n/**\n * @name lastDayOfMonth\n * @category Month Helpers\n * @summary Return the last day of a month for the given date.\n *\n * @description\n * Return the last day of a month for the given date.\n * The result will be in the local timezone.\n *\n * @param {Date|Number} date - the original date\n * @returns {Date} the last day of a month\n * @throws {TypeError} 1 argument required\n *\n * @example\n * // The last day of a month for 2 September 2014 11:55:00:\n * const result = lastDayOfMonth(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 30 2014 00:00:00\n */\nexport default function lastDayOfMonth(dirtyDate) {\n requiredArgs(1, arguments);\n var date = toDate(dirtyDate);\n var month = date.getMonth();\n date.setFullYear(date.getFullYear(), month + 1, 0);\n date.setHours(0, 0, 0, 0);\n return date;\n}","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\nvar React = require('react');\nvar React__default = _interopDefault(React);\n\nvar UAParser = require('ua-parser-js/dist/ua-parser.min');\n\nvar ClientUAInstance = new UAParser();\nvar browser = ClientUAInstance.getBrowser();\nvar cpu = ClientUAInstance.getCPU();\nvar device = ClientUAInstance.getDevice();\nvar engine = ClientUAInstance.getEngine();\nvar os = ClientUAInstance.getOS();\nvar ua = ClientUAInstance.getUA();\nvar setUa = function setUa(userAgentString) {\n return ClientUAInstance.setUA(userAgentString);\n};\nvar parseUserAgent = function parseUserAgent(userAgent) {\n if (!userAgent) {\n console.error('No userAgent string was provided');\n return;\n }\n\n var UserAgentInstance = new UAParser(userAgent);\n return {\n UA: UserAgentInstance,\n browser: UserAgentInstance.getBrowser(),\n cpu: UserAgentInstance.getCPU(),\n device: UserAgentInstance.getDevice(),\n engine: UserAgentInstance.getEngine(),\n os: UserAgentInstance.getOS(),\n ua: UserAgentInstance.getUA(),\n setUserAgent: function setUserAgent(userAgentString) {\n return UserAgentInstance.setUA(userAgentString);\n }\n };\n};\n\nvar UAHelper = /*#__PURE__*/Object.freeze({\n ClientUAInstance: ClientUAInstance,\n browser: browser,\n cpu: cpu,\n device: device,\n engine: engine,\n os: os,\n ua: ua,\n setUa: setUa,\n parseUserAgent: parseUserAgent\n});\n\nfunction ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n\n if (enumerableOnly) {\n symbols = symbols.filter(function (sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n });\n }\n\n keys.push.apply(keys, symbols);\n }\n\n return keys;\n}\n\nfunction _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n\n if (i % 2) {\n ownKeys(Object(source), true).forEach(function (key) {\n _defineProperty(target, key, source[key]);\n });\n } else if (Object.getOwnPropertyDescriptors) {\n Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n } else {\n ownKeys(Object(source)).forEach(function (key) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n });\n }\n }\n\n return target;\n}\n\nfunction _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n _typeof = function (obj) {\n return typeof obj;\n };\n } else {\n _typeof = function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n };\n }\n\n return _typeof(obj);\n}\n\nfunction _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n}\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nfunction _extends() {\n _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n}\n\nfunction _inherits(subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n writable: true,\n configurable: true\n }\n });\n if (superClass) _setPrototypeOf(subClass, superClass);\n}\n\nfunction _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}\n\nfunction _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n}\n\nfunction _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n\n return target;\n}\n\nfunction _objectWithoutProperties(source, excluded) {\n if (source == null) return {};\n\n var target = _objectWithoutPropertiesLoose(source, excluded);\n\n var key, i;\n\n if (Object.getOwnPropertySymbols) {\n var sourceSymbolKeys = Object.getOwnPropertySymbols(source);\n\n for (i = 0; i < sourceSymbolKeys.length; i++) {\n key = sourceSymbolKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n target[key] = source[key];\n }\n }\n\n return target;\n}\n\nfunction _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}\n\nfunction _possibleConstructorReturn(self, call) {\n if (call && (typeof call === \"object\" || typeof call === \"function\")) {\n return call;\n } else if (call !== void 0) {\n throw new TypeError(\"Derived constructors may only return object or undefined\");\n }\n\n return _assertThisInitialized(self);\n}\n\nfunction _slicedToArray(arr, i) {\n return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();\n}\n\nfunction _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}\n\nfunction _iterableToArrayLimit(arr, i) {\n var _i = arr == null ? null : typeof Symbol !== \"undefined\" && arr[Symbol.iterator] || arr[\"@@iterator\"];\n\n if (_i == null) return;\n var _arr = [];\n var _n = true;\n var _d = false;\n\n var _s, _e;\n\n try {\n for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n}\n\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n}\n\nfunction _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n\n return arr2;\n}\n\nfunction _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nvar DeviceTypes = {\n Mobile: 'mobile',\n Tablet: 'tablet',\n SmartTv: 'smarttv',\n Console: 'console',\n Wearable: 'wearable',\n Embedded: 'embedded',\n Browser: undefined\n};\nvar BrowserTypes = {\n Chrome: 'Chrome',\n Firefox: 'Firefox',\n Opera: 'Opera',\n Yandex: 'Yandex',\n Safari: 'Safari',\n InternetExplorer: 'Internet Explorer',\n Edge: 'Edge',\n Chromium: 'Chromium',\n Ie: 'IE',\n MobileSafari: 'Mobile Safari',\n EdgeChromium: 'Edge Chromium',\n MIUI: 'MIUI Browser',\n SamsungBrowser: 'Samsung Browser'\n};\nvar OsTypes = {\n IOS: 'iOS',\n Android: 'Android',\n WindowsPhone: 'Windows Phone',\n Windows: 'Windows',\n MAC_OS: 'Mac OS'\n};\nvar InitialDeviceTypes = {\n isMobile: false,\n isTablet: false,\n isBrowser: false,\n isSmartTV: false,\n isConsole: false,\n isWearable: false\n};\n\nvar checkDeviceType = function checkDeviceType(type) {\n switch (type) {\n case DeviceTypes.Mobile:\n return {\n isMobile: true\n };\n\n case DeviceTypes.Tablet:\n return {\n isTablet: true\n };\n\n case DeviceTypes.SmartTv:\n return {\n isSmartTV: true\n };\n\n case DeviceTypes.Console:\n return {\n isConsole: true\n };\n\n case DeviceTypes.Wearable:\n return {\n isWearable: true\n };\n\n case DeviceTypes.Browser:\n return {\n isBrowser: true\n };\n\n case DeviceTypes.Embedded:\n return {\n isEmbedded: true\n };\n\n default:\n return InitialDeviceTypes;\n }\n};\nvar setUserAgent = function setUserAgent(userAgent) {\n return setUa(userAgent);\n};\nvar setDefaults = function setDefaults(p) {\n var d = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'none';\n return p ? p : d;\n};\nvar getNavigatorInstance = function getNavigatorInstance() {\n if (typeof window !== 'undefined') {\n if (window.navigator || navigator) {\n return window.navigator || navigator;\n }\n }\n\n return false;\n};\nvar isIOS13Check = function isIOS13Check(type) {\n var nav = getNavigatorInstance();\n return nav && nav.platform && (nav.platform.indexOf(type) !== -1 || nav.platform === 'MacIntel' && nav.maxTouchPoints > 1 && !window.MSStream);\n};\n\nvar browserPayload = function browserPayload(isBrowser, browser, engine, os, ua) {\n return {\n isBrowser: isBrowser,\n browserMajorVersion: setDefaults(browser.major),\n browserFullVersion: setDefaults(browser.version),\n browserName: setDefaults(browser.name),\n engineName: setDefaults(engine.name),\n engineVersion: setDefaults(engine.version),\n osName: setDefaults(os.name),\n osVersion: setDefaults(os.version),\n userAgent: setDefaults(ua)\n };\n};\nvar mobilePayload = function mobilePayload(type, device, os, ua) {\n return _objectSpread2({}, type, {\n vendor: setDefaults(device.vendor),\n model: setDefaults(device.model),\n os: setDefaults(os.name),\n osVersion: setDefaults(os.version),\n ua: setDefaults(ua)\n });\n};\nvar smartTvPayload = function smartTvPayload(isSmartTV, engine, os, ua) {\n return {\n isSmartTV: isSmartTV,\n engineName: setDefaults(engine.name),\n engineVersion: setDefaults(engine.version),\n osName: setDefaults(os.name),\n osVersion: setDefaults(os.version),\n userAgent: setDefaults(ua)\n };\n};\nvar consolePayload = function consolePayload(isConsole, engine, os, ua) {\n return {\n isConsole: isConsole,\n engineName: setDefaults(engine.name),\n engineVersion: setDefaults(engine.version),\n osName: setDefaults(os.name),\n osVersion: setDefaults(os.version),\n userAgent: setDefaults(ua)\n };\n};\nvar wearablePayload = function wearablePayload(isWearable, engine, os, ua) {\n return {\n isWearable: isWearable,\n engineName: setDefaults(engine.name),\n engineVersion: setDefaults(engine.version),\n osName: setDefaults(os.name),\n osVersion: setDefaults(os.version),\n userAgent: setDefaults(ua)\n };\n};\nvar embeddedPayload = function embeddedPayload(isEmbedded, device, engine, os, ua) {\n return {\n isEmbedded: isEmbedded,\n vendor: setDefaults(device.vendor),\n model: setDefaults(device.model),\n engineName: setDefaults(engine.name),\n engineVersion: setDefaults(engine.version),\n osName: setDefaults(os.name),\n osVersion: setDefaults(os.version),\n userAgent: setDefaults(ua)\n };\n};\n\nfunction deviceDetect(userAgent) {\n var _ref = userAgent ? parseUserAgent(userAgent) : UAHelper,\n device = _ref.device,\n browser = _ref.browser,\n engine = _ref.engine,\n os = _ref.os,\n ua = _ref.ua;\n\n var type = checkDeviceType(device.type);\n var isBrowser = type.isBrowser,\n isMobile = type.isMobile,\n isTablet = type.isTablet,\n isSmartTV = type.isSmartTV,\n isConsole = type.isConsole,\n isWearable = type.isWearable,\n isEmbedded = type.isEmbedded;\n\n if (isBrowser) {\n return browserPayload(isBrowser, browser, engine, os, ua);\n }\n\n if (isSmartTV) {\n return smartTvPayload(isSmartTV, engine, os, ua);\n }\n\n if (isConsole) {\n return consolePayload(isConsole, engine, os, ua);\n }\n\n if (isMobile) {\n return mobilePayload(type, device, os, ua);\n }\n\n if (isTablet) {\n return mobilePayload(type, device, os, ua);\n }\n\n if (isWearable) {\n return wearablePayload(isWearable, engine, os, ua);\n }\n\n if (isEmbedded) {\n return embeddedPayload(isEmbedded, device, engine, os, ua);\n }\n}\n\nvar isMobileType = function isMobileType(_ref) {\n var type = _ref.type;\n return type === DeviceTypes.Mobile;\n};\nvar isTabletType = function isTabletType(_ref2) {\n var type = _ref2.type;\n return type === DeviceTypes.Tablet;\n};\nvar isMobileAndTabletType = function isMobileAndTabletType(_ref3) {\n var type = _ref3.type;\n return type === DeviceTypes.Mobile || type === DeviceTypes.Tablet;\n};\nvar isSmartTVType = function isSmartTVType(_ref4) {\n var type = _ref4.type;\n return type === DeviceTypes.SmartTv;\n};\nvar isBrowserType = function isBrowserType(_ref5) {\n var type = _ref5.type;\n return type === DeviceTypes.Browser;\n};\nvar isWearableType = function isWearableType(_ref6) {\n var type = _ref6.type;\n return type === DeviceTypes.Wearable;\n};\nvar isConsoleType = function isConsoleType(_ref7) {\n var type = _ref7.type;\n return type === DeviceTypes.Console;\n};\nvar isEmbeddedType = function isEmbeddedType(_ref8) {\n var type = _ref8.type;\n return type === DeviceTypes.Embedded;\n};\nvar getMobileVendor = function getMobileVendor(_ref9) {\n var vendor = _ref9.vendor;\n return setDefaults(vendor);\n};\nvar getMobileModel = function getMobileModel(_ref10) {\n var model = _ref10.model;\n return setDefaults(model);\n};\nvar getDeviceType = function getDeviceType(_ref11) {\n var type = _ref11.type;\n return setDefaults(type, 'browser');\n}; // os types\n\nvar isAndroidType = function isAndroidType(_ref12) {\n var name = _ref12.name;\n return name === OsTypes.Android;\n};\nvar isWindowsType = function isWindowsType(_ref13) {\n var name = _ref13.name;\n return name === OsTypes.Windows;\n};\nvar isMacOsType = function isMacOsType(_ref14) {\n var name = _ref14.name;\n return name === OsTypes.MAC_OS;\n};\nvar isWinPhoneType = function isWinPhoneType(_ref15) {\n var name = _ref15.name;\n return name === OsTypes.WindowsPhone;\n};\nvar isIOSType = function isIOSType(_ref16) {\n var name = _ref16.name;\n return name === OsTypes.IOS;\n};\nvar getOsVersion = function getOsVersion(_ref17) {\n var version = _ref17.version;\n return setDefaults(version);\n};\nvar getOsName = function getOsName(_ref18) {\n var name = _ref18.name;\n return setDefaults(name);\n}; // browser types\n\nvar isChromeType = function isChromeType(_ref19) {\n var name = _ref19.name;\n return name === BrowserTypes.Chrome;\n};\nvar isFirefoxType = function isFirefoxType(_ref20) {\n var name = _ref20.name;\n return name === BrowserTypes.Firefox;\n};\nvar isChromiumType = function isChromiumType(_ref21) {\n var name = _ref21.name;\n return name === BrowserTypes.Chromium;\n};\nvar isEdgeType = function isEdgeType(_ref22) {\n var name = _ref22.name;\n return name === BrowserTypes.Edge;\n};\nvar isYandexType = function isYandexType(_ref23) {\n var name = _ref23.name;\n return name === BrowserTypes.Yandex;\n};\nvar isSafariType = function isSafariType(_ref24) {\n var name = _ref24.name;\n return name === BrowserTypes.Safari || name === BrowserTypes.MobileSafari;\n};\nvar isMobileSafariType = function isMobileSafariType(_ref25) {\n var name = _ref25.name;\n return name === BrowserTypes.MobileSafari;\n};\nvar isOperaType = function isOperaType(_ref26) {\n var name = _ref26.name;\n return name === BrowserTypes.Opera;\n};\nvar isIEType = function isIEType(_ref27) {\n var name = _ref27.name;\n return name === BrowserTypes.InternetExplorer || name === BrowserTypes.Ie;\n};\nvar isMIUIType = function isMIUIType(_ref28) {\n var name = _ref28.name;\n return name === BrowserTypes.MIUI;\n};\nvar isSamsungBrowserType = function isSamsungBrowserType(_ref29) {\n var name = _ref29.name;\n return name === BrowserTypes.SamsungBrowser;\n};\nvar getBrowserFullVersion = function getBrowserFullVersion(_ref30) {\n var version = _ref30.version;\n return setDefaults(version);\n};\nvar getBrowserVersion = function getBrowserVersion(_ref31) {\n var major = _ref31.major;\n return setDefaults(major);\n};\nvar getBrowserName = function getBrowserName(_ref32) {\n var name = _ref32.name;\n return setDefaults(name);\n}; // engine types\n\nvar getEngineName = function getEngineName(_ref33) {\n var name = _ref33.name;\n return setDefaults(name);\n};\nvar getEngineVersion = function getEngineVersion(_ref34) {\n var version = _ref34.version;\n return setDefaults(version);\n};\nvar isElectronType = function isElectronType() {\n var nav = getNavigatorInstance();\n var ua = nav && nav.userAgent && nav.userAgent.toLowerCase();\n return typeof ua === 'string' ? /electron/.test(ua) : false;\n};\nvar isEdgeChromiumType = function isEdgeChromiumType(ua) {\n return typeof ua === 'string' && ua.indexOf('Edg/') !== -1;\n};\nvar getIOS13 = function getIOS13() {\n var nav = getNavigatorInstance();\n return nav && (/iPad|iPhone|iPod/.test(nav.platform) || nav.platform === 'MacIntel' && nav.maxTouchPoints > 1) && !window.MSStream;\n};\nvar getIPad13 = function getIPad13() {\n return isIOS13Check('iPad');\n};\nvar getIphone13 = function getIphone13() {\n return isIOS13Check('iPhone');\n};\nvar getIPod13 = function getIPod13() {\n return isIOS13Check('iPod');\n};\nvar getUseragent = function getUseragent(userAg) {\n return setDefaults(userAg);\n};\n\nfunction buildSelectorsObject(options) {\n var _ref = options ? options : UAHelper,\n device = _ref.device,\n browser = _ref.browser,\n os = _ref.os,\n engine = _ref.engine,\n ua = _ref.ua;\n\n return {\n isSmartTV: isSmartTVType(device),\n isConsole: isConsoleType(device),\n isWearable: isWearableType(device),\n isEmbedded: isEmbeddedType(device),\n isMobileSafari: isMobileSafariType(browser) || getIPad13(),\n isChromium: isChromiumType(browser),\n isMobile: isMobileAndTabletType(device) || getIPad13(),\n isMobileOnly: isMobileType(device),\n isTablet: isTabletType(device) || getIPad13(),\n isBrowser: isBrowserType(device),\n isDesktop: isBrowserType(device),\n isAndroid: isAndroidType(os),\n isWinPhone: isWinPhoneType(os),\n isIOS: isIOSType(os) || getIPad13(),\n isChrome: isChromeType(browser),\n isFirefox: isFirefoxType(browser),\n isSafari: isSafariType(browser),\n isOpera: isOperaType(browser),\n isIE: isIEType(browser),\n osVersion: getOsVersion(os),\n osName: getOsName(os),\n fullBrowserVersion: getBrowserFullVersion(browser),\n browserVersion: getBrowserVersion(browser),\n browserName: getBrowserName(browser),\n mobileVendor: getMobileVendor(device),\n mobileModel: getMobileModel(device),\n engineName: getEngineName(engine),\n engineVersion: getEngineVersion(engine),\n getUA: getUseragent(ua),\n isEdge: isEdgeType(browser) || isEdgeChromiumType(ua),\n isYandex: isYandexType(browser),\n deviceType: getDeviceType(device),\n isIOS13: getIOS13(),\n isIPad13: getIPad13(),\n isIPhone13: getIphone13(),\n isIPod13: getIPod13(),\n isElectron: isElectronType(),\n isEdgeChromium: isEdgeChromiumType(ua),\n isLegacyEdge: isEdgeType(browser) && !isEdgeChromiumType(ua),\n isWindows: isWindowsType(os),\n isMacOs: isMacOsType(os),\n isMIUI: isMIUIType(browser),\n isSamsungBrowser: isSamsungBrowserType(browser)\n };\n}\n\nvar isSmartTV = isSmartTVType(device);\nvar isConsole = isConsoleType(device);\nvar isWearable = isWearableType(device);\nvar isEmbedded = isEmbeddedType(device);\nvar isMobileSafari = isMobileSafariType(browser) || getIPad13();\nvar isChromium = isChromiumType(browser);\nvar isMobile = isMobileAndTabletType(device) || getIPad13();\nvar isMobileOnly = isMobileType(device);\nvar isTablet = isTabletType(device) || getIPad13();\nvar isBrowser = isBrowserType(device);\nvar isDesktop = isBrowserType(device);\nvar isAndroid = isAndroidType(os);\nvar isWinPhone = isWinPhoneType(os);\nvar isIOS = isIOSType(os) || getIPad13();\nvar isChrome = isChromeType(browser);\nvar isFirefox = isFirefoxType(browser);\nvar isSafari = isSafariType(browser);\nvar isOpera = isOperaType(browser);\nvar isIE = isIEType(browser);\nvar osVersion = getOsVersion(os);\nvar osName = getOsName(os);\nvar fullBrowserVersion = getBrowserFullVersion(browser);\nvar browserVersion = getBrowserVersion(browser);\nvar browserName = getBrowserName(browser);\nvar mobileVendor = getMobileVendor(device);\nvar mobileModel = getMobileModel(device);\nvar engineName = getEngineName(engine);\nvar engineVersion = getEngineVersion(engine);\nvar getUA = getUseragent(ua);\nvar isEdge = isEdgeType(browser) || isEdgeChromiumType(ua);\nvar isYandex = isYandexType(browser);\nvar deviceType = getDeviceType(device);\nvar isIOS13 = getIOS13();\nvar isIPad13 = getIPad13();\nvar isIPhone13 = getIphone13();\nvar isIPod13 = getIPod13();\nvar isElectron = isElectronType();\nvar isEdgeChromium = isEdgeChromiumType(ua);\nvar isLegacyEdge = isEdgeType(browser) && !isEdgeChromiumType(ua);\nvar isWindows = isWindowsType(os);\nvar isMacOs = isMacOsType(os);\nvar isMIUI = isMIUIType(browser);\nvar isSamsungBrowser = isSamsungBrowserType(browser);\nvar getSelectorsByUserAgent = function getSelectorsByUserAgent(userAgent) {\n if (!userAgent || typeof userAgent !== 'string') {\n console.error('No valid user agent string was provided');\n return;\n }\n\n var _UAHelper$parseUserAg = parseUserAgent(userAgent),\n device = _UAHelper$parseUserAg.device,\n browser = _UAHelper$parseUserAg.browser,\n os = _UAHelper$parseUserAg.os,\n engine = _UAHelper$parseUserAg.engine,\n ua = _UAHelper$parseUserAg.ua;\n\n return buildSelectorsObject({\n device: device,\n browser: browser,\n os: os,\n engine: engine,\n ua: ua\n });\n};\n\nvar AndroidView = function AndroidView(_ref) {\n var renderWithFragment = _ref.renderWithFragment,\n children = _ref.children,\n props = _objectWithoutProperties(_ref, [\"renderWithFragment\", \"children\"]);\n\n return isAndroid ? renderWithFragment ? React__default.createElement(React.Fragment, null, children) : React__default.createElement(\"div\", props, children) : null;\n};\nvar BrowserView = function BrowserView(_ref2) {\n var renderWithFragment = _ref2.renderWithFragment,\n children = _ref2.children,\n props = _objectWithoutProperties(_ref2, [\"renderWithFragment\", \"children\"]);\n\n return isBrowser ? renderWithFragment ? React__default.createElement(React.Fragment, null, children) : React__default.createElement(\"div\", props, children) : null;\n};\nvar IEView = function IEView(_ref3) {\n var renderWithFragment = _ref3.renderWithFragment,\n children = _ref3.children,\n props = _objectWithoutProperties(_ref3, [\"renderWithFragment\", \"children\"]);\n\n return isIE ? renderWithFragment ? React__default.createElement(React.Fragment, null, children) : React__default.createElement(\"div\", props, children) : null;\n};\nvar IOSView = function IOSView(_ref4) {\n var renderWithFragment = _ref4.renderWithFragment,\n children = _ref4.children,\n props = _objectWithoutProperties(_ref4, [\"renderWithFragment\", \"children\"]);\n\n return isIOS ? renderWithFragment ? React__default.createElement(React.Fragment, null, children) : React__default.createElement(\"div\", props, children) : null;\n};\nvar MobileView = function MobileView(_ref5) {\n var renderWithFragment = _ref5.renderWithFragment,\n children = _ref5.children,\n props = _objectWithoutProperties(_ref5, [\"renderWithFragment\", \"children\"]);\n\n return isMobile ? renderWithFragment ? React__default.createElement(React.Fragment, null, children) : React__default.createElement(\"div\", props, children) : null;\n};\nvar TabletView = function TabletView(_ref6) {\n var renderWithFragment = _ref6.renderWithFragment,\n children = _ref6.children,\n props = _objectWithoutProperties(_ref6, [\"renderWithFragment\", \"children\"]);\n\n return isTablet ? renderWithFragment ? React__default.createElement(React.Fragment, null, children) : React__default.createElement(\"div\", props, children) : null;\n};\nvar WinPhoneView = function WinPhoneView(_ref7) {\n var renderWithFragment = _ref7.renderWithFragment,\n children = _ref7.children,\n props = _objectWithoutProperties(_ref7, [\"renderWithFragment\", \"children\"]);\n\n return isWinPhone ? renderWithFragment ? React__default.createElement(React.Fragment, null, children) : React__default.createElement(\"div\", props, children) : null;\n};\nvar MobileOnlyView = function MobileOnlyView(_ref8) {\n var renderWithFragment = _ref8.renderWithFragment,\n children = _ref8.children,\n viewClassName = _ref8.viewClassName,\n style = _ref8.style,\n props = _objectWithoutProperties(_ref8, [\"renderWithFragment\", \"children\", \"viewClassName\", \"style\"]);\n\n return isMobileOnly ? renderWithFragment ? React__default.createElement(React.Fragment, null, children) : React__default.createElement(\"div\", props, children) : null;\n};\nvar SmartTVView = function SmartTVView(_ref9) {\n var renderWithFragment = _ref9.renderWithFragment,\n children = _ref9.children,\n props = _objectWithoutProperties(_ref9, [\"renderWithFragment\", \"children\"]);\n\n return isSmartTV ? renderWithFragment ? React__default.createElement(React.Fragment, null, children) : React__default.createElement(\"div\", props, children) : null;\n};\nvar ConsoleView = function ConsoleView(_ref10) {\n var renderWithFragment = _ref10.renderWithFragment,\n children = _ref10.children,\n props = _objectWithoutProperties(_ref10, [\"renderWithFragment\", \"children\"]);\n\n return isConsole ? renderWithFragment ? React__default.createElement(React.Fragment, null, children) : React__default.createElement(\"div\", props, children) : null;\n};\nvar WearableView = function WearableView(_ref11) {\n var renderWithFragment = _ref11.renderWithFragment,\n children = _ref11.children,\n props = _objectWithoutProperties(_ref11, [\"renderWithFragment\", \"children\"]);\n\n return isWearable ? renderWithFragment ? React__default.createElement(React.Fragment, null, children) : React__default.createElement(\"div\", props, children) : null;\n};\nvar CustomView = function CustomView(_ref12) {\n var renderWithFragment = _ref12.renderWithFragment,\n children = _ref12.children,\n viewClassName = _ref12.viewClassName,\n style = _ref12.style,\n condition = _ref12.condition,\n props = _objectWithoutProperties(_ref12, [\"renderWithFragment\", \"children\", \"viewClassName\", \"style\", \"condition\"]);\n\n return condition ? renderWithFragment ? React__default.createElement(React.Fragment, null, children) : React__default.createElement(\"div\", props, children) : null;\n};\n\nfunction withOrientationChange(WrappedComponent) {\n return /*#__PURE__*/function (_React$Component) {\n _inherits(_class, _React$Component);\n\n function _class(props) {\n var _this;\n\n _classCallCheck(this, _class);\n\n _this = _possibleConstructorReturn(this, _getPrototypeOf(_class).call(this, props));\n _this.isEventListenerAdded = false;\n _this.handleOrientationChange = _this.handleOrientationChange.bind(_assertThisInitialized(_this));\n _this.onOrientationChange = _this.onOrientationChange.bind(_assertThisInitialized(_this));\n _this.onPageLoad = _this.onPageLoad.bind(_assertThisInitialized(_this));\n _this.state = {\n isLandscape: false,\n isPortrait: false\n };\n return _this;\n }\n\n _createClass(_class, [{\n key: \"handleOrientationChange\",\n value: function handleOrientationChange() {\n if (!this.isEventListenerAdded) {\n this.isEventListenerAdded = true;\n }\n\n var orientation = window.innerWidth > window.innerHeight ? 90 : 0;\n this.setState({\n isPortrait: orientation === 0,\n isLandscape: orientation === 90\n });\n }\n }, {\n key: \"onOrientationChange\",\n value: function onOrientationChange() {\n this.handleOrientationChange();\n }\n }, {\n key: \"onPageLoad\",\n value: function onPageLoad() {\n this.handleOrientationChange();\n }\n }, {\n key: \"componentDidMount\",\n value: function componentDidMount() {\n if ((typeof window === \"undefined\" ? \"undefined\" : _typeof(window)) !== undefined && isMobile) {\n if (!this.isEventListenerAdded) {\n this.handleOrientationChange();\n window.addEventListener(\"load\", this.onPageLoad, false);\n } else {\n window.removeEventListener(\"load\", this.onPageLoad, false);\n }\n\n window.addEventListener(\"resize\", this.onOrientationChange, false);\n }\n }\n }, {\n key: \"componentWillUnmount\",\n value: function componentWillUnmount() {\n window.removeEventListener(\"resize\", this.onOrientationChange, false);\n }\n }, {\n key: \"render\",\n value: function render() {\n return React__default.createElement(WrappedComponent, _extends({}, this.props, {\n isLandscape: this.state.isLandscape,\n isPortrait: this.state.isPortrait\n }));\n }\n }]);\n\n return _class;\n }(React__default.Component);\n}\n\nfunction useMobileOrientation() {\n var _useState = React.useState(function () {\n var orientation = window.innerWidth > window.innerHeight ? 90 : 0;\n return {\n isPortrait: orientation === 0,\n isLandscape: orientation === 90,\n orientation: orientation === 0 ? 'portrait' : 'landscape'\n };\n }),\n _useState2 = _slicedToArray(_useState, 2),\n state = _useState2[0],\n setState = _useState2[1];\n\n var handleOrientationChange = React.useCallback(function () {\n var orientation = window.innerWidth > window.innerHeight ? 90 : 0;\n var next = {\n isPortrait: orientation === 0,\n isLandscape: orientation === 90,\n orientation: orientation === 0 ? 'portrait' : 'landscape'\n };\n state.orientation !== next.orientation && setState(next);\n }, [state.orientation]);\n React.useEffect(function () {\n if ((typeof window === \"undefined\" ? \"undefined\" : _typeof(window)) !== undefined && isMobile) {\n handleOrientationChange();\n window.addEventListener(\"load\", handleOrientationChange, false);\n window.addEventListener(\"resize\", handleOrientationChange, false);\n }\n\n return function () {\n window.removeEventListener(\"resize\", handleOrientationChange, false);\n window.removeEventListener(\"load\", handleOrientationChange, false);\n };\n }, [handleOrientationChange]);\n return state;\n}\n\nfunction useDeviceData(userAgent) {\n var hookUserAgent = userAgent ? userAgent : window.navigator.userAgent;\n return parseUserAgent(hookUserAgent);\n}\n\nfunction useDeviceSelectors(userAgent) {\n var hookUserAgent = userAgent ? userAgent : window.navigator.userAgent;\n var deviceData = useDeviceData(hookUserAgent);\n var selectors = buildSelectorsObject(deviceData);\n return [selectors, deviceData];\n}\n\nexports.AndroidView = AndroidView;\nexports.BrowserTypes = BrowserTypes;\nexports.BrowserView = BrowserView;\nexports.ConsoleView = ConsoleView;\nexports.CustomView = CustomView;\nexports.IEView = IEView;\nexports.IOSView = IOSView;\nexports.MobileOnlyView = MobileOnlyView;\nexports.MobileView = MobileView;\nexports.OsTypes = OsTypes;\nexports.SmartTVView = SmartTVView;\nexports.TabletView = TabletView;\nexports.WearableView = WearableView;\nexports.WinPhoneView = WinPhoneView;\nexports.browserName = browserName;\nexports.browserVersion = browserVersion;\nexports.deviceDetect = deviceDetect;\nexports.deviceType = deviceType;\nexports.engineName = engineName;\nexports.engineVersion = engineVersion;\nexports.fullBrowserVersion = fullBrowserVersion;\nexports.getSelectorsByUserAgent = getSelectorsByUserAgent;\nexports.getUA = getUA;\nexports.isAndroid = isAndroid;\nexports.isBrowser = isBrowser;\nexports.isChrome = isChrome;\nexports.isChromium = isChromium;\nexports.isConsole = isConsole;\nexports.isDesktop = isDesktop;\nexports.isEdge = isEdge;\nexports.isEdgeChromium = isEdgeChromium;\nexports.isElectron = isElectron;\nexports.isEmbedded = isEmbedded;\nexports.isFirefox = isFirefox;\nexports.isIE = isIE;\nexports.isIOS = isIOS;\nexports.isIOS13 = isIOS13;\nexports.isIPad13 = isIPad13;\nexports.isIPhone13 = isIPhone13;\nexports.isIPod13 = isIPod13;\nexports.isLegacyEdge = isLegacyEdge;\nexports.isMIUI = isMIUI;\nexports.isMacOs = isMacOs;\nexports.isMobile = isMobile;\nexports.isMobileOnly = isMobileOnly;\nexports.isMobileSafari = isMobileSafari;\nexports.isOpera = isOpera;\nexports.isSafari = isSafari;\nexports.isSamsungBrowser = isSamsungBrowser;\nexports.isSmartTV = isSmartTV;\nexports.isTablet = isTablet;\nexports.isWearable = isWearable;\nexports.isWinPhone = isWinPhone;\nexports.isWindows = isWindows;\nexports.isYandex = isYandex;\nexports.mobileModel = mobileModel;\nexports.mobileVendor = mobileVendor;\nexports.osName = osName;\nexports.osVersion = osVersion;\nexports.parseUserAgent = parseUserAgent;\nexports.setUserAgent = setUserAgent;\nexports.useDeviceData = useDeviceData;\nexports.useDeviceSelectors = useDeviceSelectors;\nexports.useMobileOrientation = useMobileOrientation;\nexports.withOrientationChange = withOrientationChange;\n","/* global Map:readonly, Set:readonly, ArrayBuffer:readonly */\n\nvar hasElementType = typeof Element !== 'undefined';\nvar hasMap = typeof Map === 'function';\nvar hasSet = typeof Set === 'function';\nvar hasArrayBuffer = typeof ArrayBuffer === 'function' && !!ArrayBuffer.isView;\n\n// Note: We **don't** need `envHasBigInt64Array` in fde es6/index.js\n\nfunction equal(a, b) {\n // START: fast-deep-equal es6/index.js 3.1.3\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n // START: Modifications:\n // 1. Extra `has &&` helpers in initial condition allow es6 code\n // to co-exist with es5.\n // 2. Replace `for of` with es5 compliant iteration using `for`.\n // Basically, take:\n //\n // ```js\n // for (i of a.entries())\n // if (!b.has(i[0])) return false;\n // ```\n //\n // ... and convert to:\n //\n // ```js\n // it = a.entries();\n // while (!(i = it.next()).done)\n // if (!b.has(i.value[0])) return false;\n // ```\n //\n // **Note**: `i` access switches to `i.value`.\n var it;\n if (hasMap && (a instanceof Map) && (b instanceof Map)) {\n if (a.size !== b.size) return false;\n it = a.entries();\n while (!(i = it.next()).done)\n if (!b.has(i.value[0])) return false;\n it = a.entries();\n while (!(i = it.next()).done)\n if (!equal(i.value[1], b.get(i.value[0]))) return false;\n return true;\n }\n\n if (hasSet && (a instanceof Set) && (b instanceof Set)) {\n if (a.size !== b.size) return false;\n it = a.entries();\n while (!(i = it.next()).done)\n if (!b.has(i.value[0])) return false;\n return true;\n }\n // END: Modifications\n\n if (hasArrayBuffer && ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (a[i] !== b[i]) return false;\n return true;\n }\n\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n // START: Modifications:\n // Apply guards for `Object.create(null)` handling. See:\n // - https://github.com/FormidableLabs/react-fast-compare/issues/64\n // - https://github.com/epoberezkin/fast-deep-equal/issues/49\n if (a.valueOf !== Object.prototype.valueOf && typeof a.valueOf === 'function' && typeof b.valueOf === 'function') return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString && typeof a.toString === 'function' && typeof b.toString === 'function') return a.toString() === b.toString();\n // END: Modifications\n\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n // END: fast-deep-equal\n\n // START: react-fast-compare\n // custom handling for DOM elements\n if (hasElementType && a instanceof Element) return false;\n\n // custom handling for React/Preact\n for (i = length; i-- !== 0;) {\n if ((keys[i] === '_owner' || keys[i] === '__v' || keys[i] === '__o') && a.$$typeof) {\n // React-specific: avoid traversing React elements' _owner\n // Preact-specific: avoid traversing Preact elements' __v and __o\n // __v = $_original / $_vnode\n // __o = $_owner\n // These properties contain circular references and are not needed when\n // comparing the actual elements (and not their owners)\n // .$$typeof and ._store on just reasonable markers of elements\n\n continue;\n }\n\n // all other properties should be traversed as usual\n if (!equal(a[keys[i]], b[keys[i]])) return false;\n }\n // END: react-fast-compare\n\n // START: fast-deep-equal\n return true;\n }\n\n return a !== a && b !== b;\n}\n// end fast-deep-equal\n\nmodule.exports = function isEqual(a, b) {\n try {\n return equal(a, b);\n } catch (error) {\n if (((error.message || '').match(/stack|recursion/i))) {\n // warn on circular references, don't crash\n // browsers give this different errors name and messages:\n // chrome/safari: \"RangeError\", \"Maximum call stack size exceeded\"\n // firefox: \"InternalError\", too much recursion\"\n // edge: \"Error\", \"Out of stack space\"\n console.warn('react-fast-compare cannot handle circular refs');\n return false;\n }\n // some other error. we should definitely know about these\n throw error;\n }\n};\n","import PropTypes from 'prop-types';\nimport withSideEffect from 'react-side-effect';\nimport isEqual from 'react-fast-compare';\nimport React from 'react';\nimport objectAssign from 'object-assign';\n\nvar ATTRIBUTE_NAMES = {\n BODY: \"bodyAttributes\",\n HTML: \"htmlAttributes\",\n TITLE: \"titleAttributes\"\n};\n\nvar TAG_NAMES = {\n BASE: \"base\",\n BODY: \"body\",\n HEAD: \"head\",\n HTML: \"html\",\n LINK: \"link\",\n META: \"meta\",\n NOSCRIPT: \"noscript\",\n SCRIPT: \"script\",\n STYLE: \"style\",\n TITLE: \"title\"\n};\n\nvar VALID_TAG_NAMES = Object.keys(TAG_NAMES).map(function (name) {\n return TAG_NAMES[name];\n});\n\nvar TAG_PROPERTIES = {\n CHARSET: \"charset\",\n CSS_TEXT: \"cssText\",\n HREF: \"href\",\n HTTPEQUIV: \"http-equiv\",\n INNER_HTML: \"innerHTML\",\n ITEM_PROP: \"itemprop\",\n NAME: \"name\",\n PROPERTY: \"property\",\n REL: \"rel\",\n SRC: \"src\",\n TARGET: \"target\"\n};\n\nvar REACT_TAG_MAP = {\n accesskey: \"accessKey\",\n charset: \"charSet\",\n class: \"className\",\n contenteditable: \"contentEditable\",\n contextmenu: \"contextMenu\",\n \"http-equiv\": \"httpEquiv\",\n itemprop: \"itemProp\",\n tabindex: \"tabIndex\"\n};\n\nvar HELMET_PROPS = {\n DEFAULT_TITLE: \"defaultTitle\",\n DEFER: \"defer\",\n ENCODE_SPECIAL_CHARACTERS: \"encodeSpecialCharacters\",\n ON_CHANGE_CLIENT_STATE: \"onChangeClientState\",\n TITLE_TEMPLATE: \"titleTemplate\"\n};\n\nvar HTML_TAG_MAP = Object.keys(REACT_TAG_MAP).reduce(function (obj, key) {\n obj[REACT_TAG_MAP[key]] = key;\n return obj;\n}, {});\n\nvar SELF_CLOSING_TAGS = [TAG_NAMES.NOSCRIPT, TAG_NAMES.SCRIPT, TAG_NAMES.STYLE];\n\nvar HELMET_ATTRIBUTE = \"data-react-helmet\";\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) {\n return typeof obj;\n} : function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n};\n\nvar classCallCheck = function (instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n};\n\nvar createClass = function () {\n function defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n\n return function (Constructor, protoProps, staticProps) {\n if (protoProps) defineProperties(Constructor.prototype, protoProps);\n if (staticProps) defineProperties(Constructor, staticProps);\n return Constructor;\n };\n}();\n\nvar _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n};\n\nvar inherits = function (subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass);\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;\n};\n\nvar objectWithoutProperties = function (obj, keys) {\n var target = {};\n\n for (var i in obj) {\n if (keys.indexOf(i) >= 0) continue;\n if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;\n target[i] = obj[i];\n }\n\n return target;\n};\n\nvar possibleConstructorReturn = function (self, call) {\n if (!self) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self;\n};\n\nvar encodeSpecialCharacters = function encodeSpecialCharacters(str) {\n var encode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n\n if (encode === false) {\n return String(str);\n }\n\n return String(str).replace(/&/g, \"&\").replace(//g, \">\").replace(/\"/g, \""\").replace(/'/g, \"'\");\n};\n\nvar getTitleFromPropsList = function getTitleFromPropsList(propsList) {\n var innermostTitle = getInnermostProperty(propsList, TAG_NAMES.TITLE);\n var innermostTemplate = getInnermostProperty(propsList, HELMET_PROPS.TITLE_TEMPLATE);\n\n if (innermostTemplate && innermostTitle) {\n // use function arg to avoid need to escape $ characters\n return innermostTemplate.replace(/%s/g, function () {\n return Array.isArray(innermostTitle) ? innermostTitle.join(\"\") : innermostTitle;\n });\n }\n\n var innermostDefaultTitle = getInnermostProperty(propsList, HELMET_PROPS.DEFAULT_TITLE);\n\n return innermostTitle || innermostDefaultTitle || undefined;\n};\n\nvar getOnChangeClientState = function getOnChangeClientState(propsList) {\n return getInnermostProperty(propsList, HELMET_PROPS.ON_CHANGE_CLIENT_STATE) || function () {};\n};\n\nvar getAttributesFromPropsList = function getAttributesFromPropsList(tagType, propsList) {\n return propsList.filter(function (props) {\n return typeof props[tagType] !== \"undefined\";\n }).map(function (props) {\n return props[tagType];\n }).reduce(function (tagAttrs, current) {\n return _extends({}, tagAttrs, current);\n }, {});\n};\n\nvar getBaseTagFromPropsList = function getBaseTagFromPropsList(primaryAttributes, propsList) {\n return propsList.filter(function (props) {\n return typeof props[TAG_NAMES.BASE] !== \"undefined\";\n }).map(function (props) {\n return props[TAG_NAMES.BASE];\n }).reverse().reduce(function (innermostBaseTag, tag) {\n if (!innermostBaseTag.length) {\n var keys = Object.keys(tag);\n\n for (var i = 0; i < keys.length; i++) {\n var attributeKey = keys[i];\n var lowerCaseAttributeKey = attributeKey.toLowerCase();\n\n if (primaryAttributes.indexOf(lowerCaseAttributeKey) !== -1 && tag[lowerCaseAttributeKey]) {\n return innermostBaseTag.concat(tag);\n }\n }\n }\n\n return innermostBaseTag;\n }, []);\n};\n\nvar getTagsFromPropsList = function getTagsFromPropsList(tagName, primaryAttributes, propsList) {\n // Calculate list of tags, giving priority innermost component (end of the propslist)\n var approvedSeenTags = {};\n\n return propsList.filter(function (props) {\n if (Array.isArray(props[tagName])) {\n return true;\n }\n if (typeof props[tagName] !== \"undefined\") {\n warn(\"Helmet: \" + tagName + \" should be of type \\\"Array\\\". Instead found type \\\"\" + _typeof(props[tagName]) + \"\\\"\");\n }\n return false;\n }).map(function (props) {\n return props[tagName];\n }).reverse().reduce(function (approvedTags, instanceTags) {\n var instanceSeenTags = {};\n\n instanceTags.filter(function (tag) {\n var primaryAttributeKey = void 0;\n var keys = Object.keys(tag);\n for (var i = 0; i < keys.length; i++) {\n var attributeKey = keys[i];\n var lowerCaseAttributeKey = attributeKey.toLowerCase();\n\n // Special rule with link tags, since rel and href are both primary tags, rel takes priority\n if (primaryAttributes.indexOf(lowerCaseAttributeKey) !== -1 && !(primaryAttributeKey === TAG_PROPERTIES.REL && tag[primaryAttributeKey].toLowerCase() === \"canonical\") && !(lowerCaseAttributeKey === TAG_PROPERTIES.REL && tag[lowerCaseAttributeKey].toLowerCase() === \"stylesheet\")) {\n primaryAttributeKey = lowerCaseAttributeKey;\n }\n // Special case for innerHTML which doesn't work lowercased\n if (primaryAttributes.indexOf(attributeKey) !== -1 && (attributeKey === TAG_PROPERTIES.INNER_HTML || attributeKey === TAG_PROPERTIES.CSS_TEXT || attributeKey === TAG_PROPERTIES.ITEM_PROP)) {\n primaryAttributeKey = attributeKey;\n }\n }\n\n if (!primaryAttributeKey || !tag[primaryAttributeKey]) {\n return false;\n }\n\n var value = tag[primaryAttributeKey].toLowerCase();\n\n if (!approvedSeenTags[primaryAttributeKey]) {\n approvedSeenTags[primaryAttributeKey] = {};\n }\n\n if (!instanceSeenTags[primaryAttributeKey]) {\n instanceSeenTags[primaryAttributeKey] = {};\n }\n\n if (!approvedSeenTags[primaryAttributeKey][value]) {\n instanceSeenTags[primaryAttributeKey][value] = true;\n return true;\n }\n\n return false;\n }).reverse().forEach(function (tag) {\n return approvedTags.push(tag);\n });\n\n // Update seen tags with tags from this instance\n var keys = Object.keys(instanceSeenTags);\n for (var i = 0; i < keys.length; i++) {\n var attributeKey = keys[i];\n var tagUnion = objectAssign({}, approvedSeenTags[attributeKey], instanceSeenTags[attributeKey]);\n\n approvedSeenTags[attributeKey] = tagUnion;\n }\n\n return approvedTags;\n }, []).reverse();\n};\n\nvar getInnermostProperty = function getInnermostProperty(propsList, property) {\n for (var i = propsList.length - 1; i >= 0; i--) {\n var props = propsList[i];\n\n if (props.hasOwnProperty(property)) {\n return props[property];\n }\n }\n\n return null;\n};\n\nvar reducePropsToState = function reducePropsToState(propsList) {\n return {\n baseTag: getBaseTagFromPropsList([TAG_PROPERTIES.HREF, TAG_PROPERTIES.TARGET], propsList),\n bodyAttributes: getAttributesFromPropsList(ATTRIBUTE_NAMES.BODY, propsList),\n defer: getInnermostProperty(propsList, HELMET_PROPS.DEFER),\n encode: getInnermostProperty(propsList, HELMET_PROPS.ENCODE_SPECIAL_CHARACTERS),\n htmlAttributes: getAttributesFromPropsList(ATTRIBUTE_NAMES.HTML, propsList),\n linkTags: getTagsFromPropsList(TAG_NAMES.LINK, [TAG_PROPERTIES.REL, TAG_PROPERTIES.HREF], propsList),\n metaTags: getTagsFromPropsList(TAG_NAMES.META, [TAG_PROPERTIES.NAME, TAG_PROPERTIES.CHARSET, TAG_PROPERTIES.HTTPEQUIV, TAG_PROPERTIES.PROPERTY, TAG_PROPERTIES.ITEM_PROP], propsList),\n noscriptTags: getTagsFromPropsList(TAG_NAMES.NOSCRIPT, [TAG_PROPERTIES.INNER_HTML], propsList),\n onChangeClientState: getOnChangeClientState(propsList),\n scriptTags: getTagsFromPropsList(TAG_NAMES.SCRIPT, [TAG_PROPERTIES.SRC, TAG_PROPERTIES.INNER_HTML], propsList),\n styleTags: getTagsFromPropsList(TAG_NAMES.STYLE, [TAG_PROPERTIES.CSS_TEXT], propsList),\n title: getTitleFromPropsList(propsList),\n titleAttributes: getAttributesFromPropsList(ATTRIBUTE_NAMES.TITLE, propsList)\n };\n};\n\nvar rafPolyfill = function () {\n var clock = Date.now();\n\n return function (callback) {\n var currentTime = Date.now();\n\n if (currentTime - clock > 16) {\n clock = currentTime;\n callback(currentTime);\n } else {\n setTimeout(function () {\n rafPolyfill(callback);\n }, 0);\n }\n };\n}();\n\nvar cafPolyfill = function cafPolyfill(id) {\n return clearTimeout(id);\n};\n\nvar requestAnimationFrame = typeof window !== \"undefined\" ? window.requestAnimationFrame && window.requestAnimationFrame.bind(window) || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || rafPolyfill : global.requestAnimationFrame || rafPolyfill;\n\nvar cancelAnimationFrame = typeof window !== \"undefined\" ? window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || cafPolyfill : global.cancelAnimationFrame || cafPolyfill;\n\nvar warn = function warn(msg) {\n return console && typeof console.warn === \"function\" && console.warn(msg);\n};\n\nvar _helmetCallback = null;\n\nvar handleClientStateChange = function handleClientStateChange(newState) {\n if (_helmetCallback) {\n cancelAnimationFrame(_helmetCallback);\n }\n\n if (newState.defer) {\n _helmetCallback = requestAnimationFrame(function () {\n commitTagChanges(newState, function () {\n _helmetCallback = null;\n });\n });\n } else {\n commitTagChanges(newState);\n _helmetCallback = null;\n }\n};\n\nvar commitTagChanges = function commitTagChanges(newState, cb) {\n var baseTag = newState.baseTag,\n bodyAttributes = newState.bodyAttributes,\n htmlAttributes = newState.htmlAttributes,\n linkTags = newState.linkTags,\n metaTags = newState.metaTags,\n noscriptTags = newState.noscriptTags,\n onChangeClientState = newState.onChangeClientState,\n scriptTags = newState.scriptTags,\n styleTags = newState.styleTags,\n title = newState.title,\n titleAttributes = newState.titleAttributes;\n\n updateAttributes(TAG_NAMES.BODY, bodyAttributes);\n updateAttributes(TAG_NAMES.HTML, htmlAttributes);\n\n updateTitle(title, titleAttributes);\n\n var tagUpdates = {\n baseTag: updateTags(TAG_NAMES.BASE, baseTag),\n linkTags: updateTags(TAG_NAMES.LINK, linkTags),\n metaTags: updateTags(TAG_NAMES.META, metaTags),\n noscriptTags: updateTags(TAG_NAMES.NOSCRIPT, noscriptTags),\n scriptTags: updateTags(TAG_NAMES.SCRIPT, scriptTags),\n styleTags: updateTags(TAG_NAMES.STYLE, styleTags)\n };\n\n var addedTags = {};\n var removedTags = {};\n\n Object.keys(tagUpdates).forEach(function (tagType) {\n var _tagUpdates$tagType = tagUpdates[tagType],\n newTags = _tagUpdates$tagType.newTags,\n oldTags = _tagUpdates$tagType.oldTags;\n\n\n if (newTags.length) {\n addedTags[tagType] = newTags;\n }\n if (oldTags.length) {\n removedTags[tagType] = tagUpdates[tagType].oldTags;\n }\n });\n\n cb && cb();\n\n onChangeClientState(newState, addedTags, removedTags);\n};\n\nvar flattenArray = function flattenArray(possibleArray) {\n return Array.isArray(possibleArray) ? possibleArray.join(\"\") : possibleArray;\n};\n\nvar updateTitle = function updateTitle(title, attributes) {\n if (typeof title !== \"undefined\" && document.title !== title) {\n document.title = flattenArray(title);\n }\n\n updateAttributes(TAG_NAMES.TITLE, attributes);\n};\n\nvar updateAttributes = function updateAttributes(tagName, attributes) {\n var elementTag = document.getElementsByTagName(tagName)[0];\n\n if (!elementTag) {\n return;\n }\n\n var helmetAttributeString = elementTag.getAttribute(HELMET_ATTRIBUTE);\n var helmetAttributes = helmetAttributeString ? helmetAttributeString.split(\",\") : [];\n var attributesToRemove = [].concat(helmetAttributes);\n var attributeKeys = Object.keys(attributes);\n\n for (var i = 0; i < attributeKeys.length; i++) {\n var attribute = attributeKeys[i];\n var value = attributes[attribute] || \"\";\n\n if (elementTag.getAttribute(attribute) !== value) {\n elementTag.setAttribute(attribute, value);\n }\n\n if (helmetAttributes.indexOf(attribute) === -1) {\n helmetAttributes.push(attribute);\n }\n\n var indexToSave = attributesToRemove.indexOf(attribute);\n if (indexToSave !== -1) {\n attributesToRemove.splice(indexToSave, 1);\n }\n }\n\n for (var _i = attributesToRemove.length - 1; _i >= 0; _i--) {\n elementTag.removeAttribute(attributesToRemove[_i]);\n }\n\n if (helmetAttributes.length === attributesToRemove.length) {\n elementTag.removeAttribute(HELMET_ATTRIBUTE);\n } else if (elementTag.getAttribute(HELMET_ATTRIBUTE) !== attributeKeys.join(\",\")) {\n elementTag.setAttribute(HELMET_ATTRIBUTE, attributeKeys.join(\",\"));\n }\n};\n\nvar updateTags = function updateTags(type, tags) {\n var headElement = document.head || document.querySelector(TAG_NAMES.HEAD);\n var tagNodes = headElement.querySelectorAll(type + \"[\" + HELMET_ATTRIBUTE + \"]\");\n var oldTags = Array.prototype.slice.call(tagNodes);\n var newTags = [];\n var indexToDelete = void 0;\n\n if (tags && tags.length) {\n tags.forEach(function (tag) {\n var newElement = document.createElement(type);\n\n for (var attribute in tag) {\n if (tag.hasOwnProperty(attribute)) {\n if (attribute === TAG_PROPERTIES.INNER_HTML) {\n newElement.innerHTML = tag.innerHTML;\n } else if (attribute === TAG_PROPERTIES.CSS_TEXT) {\n if (newElement.styleSheet) {\n newElement.styleSheet.cssText = tag.cssText;\n } else {\n newElement.appendChild(document.createTextNode(tag.cssText));\n }\n } else {\n var value = typeof tag[attribute] === \"undefined\" ? \"\" : tag[attribute];\n newElement.setAttribute(attribute, value);\n }\n }\n }\n\n newElement.setAttribute(HELMET_ATTRIBUTE, \"true\");\n\n // Remove a duplicate tag from domTagstoRemove, so it isn't cleared.\n if (oldTags.some(function (existingTag, index) {\n indexToDelete = index;\n return newElement.isEqualNode(existingTag);\n })) {\n oldTags.splice(indexToDelete, 1);\n } else {\n newTags.push(newElement);\n }\n });\n }\n\n oldTags.forEach(function (tag) {\n return tag.parentNode.removeChild(tag);\n });\n newTags.forEach(function (tag) {\n return headElement.appendChild(tag);\n });\n\n return {\n oldTags: oldTags,\n newTags: newTags\n };\n};\n\nvar generateElementAttributesAsString = function generateElementAttributesAsString(attributes) {\n return Object.keys(attributes).reduce(function (str, key) {\n var attr = typeof attributes[key] !== \"undefined\" ? key + \"=\\\"\" + attributes[key] + \"\\\"\" : \"\" + key;\n return str ? str + \" \" + attr : attr;\n }, \"\");\n};\n\nvar generateTitleAsString = function generateTitleAsString(type, title, attributes, encode) {\n var attributeString = generateElementAttributesAsString(attributes);\n var flattenedTitle = flattenArray(title);\n return attributeString ? \"<\" + type + \" \" + HELMET_ATTRIBUTE + \"=\\\"true\\\" \" + attributeString + \">\" + encodeSpecialCharacters(flattenedTitle, encode) + \"\" + type + \">\" : \"<\" + type + \" \" + HELMET_ATTRIBUTE + \"=\\\"true\\\">\" + encodeSpecialCharacters(flattenedTitle, encode) + \"\" + type + \">\";\n};\n\nvar generateTagsAsString = function generateTagsAsString(type, tags, encode) {\n return tags.reduce(function (str, tag) {\n var attributeHtml = Object.keys(tag).filter(function (attribute) {\n return !(attribute === TAG_PROPERTIES.INNER_HTML || attribute === TAG_PROPERTIES.CSS_TEXT);\n }).reduce(function (string, attribute) {\n var attr = typeof tag[attribute] === \"undefined\" ? attribute : attribute + \"=\\\"\" + encodeSpecialCharacters(tag[attribute], encode) + \"\\\"\";\n return string ? string + \" \" + attr : attr;\n }, \"\");\n\n var tagContent = tag.innerHTML || tag.cssText || \"\";\n\n var isSelfClosing = SELF_CLOSING_TAGS.indexOf(type) === -1;\n\n return str + \"<\" + type + \" \" + HELMET_ATTRIBUTE + \"=\\\"true\\\" \" + attributeHtml + (isSelfClosing ? \"/>\" : \">\" + tagContent + \"\" + type + \">\");\n }, \"\");\n};\n\nvar convertElementAttributestoReactProps = function convertElementAttributestoReactProps(attributes) {\n var initProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n return Object.keys(attributes).reduce(function (obj, key) {\n obj[REACT_TAG_MAP[key] || key] = attributes[key];\n return obj;\n }, initProps);\n};\n\nvar convertReactPropstoHtmlAttributes = function convertReactPropstoHtmlAttributes(props) {\n var initAttributes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n return Object.keys(props).reduce(function (obj, key) {\n obj[HTML_TAG_MAP[key] || key] = props[key];\n return obj;\n }, initAttributes);\n};\n\nvar generateTitleAsReactComponent = function generateTitleAsReactComponent(type, title, attributes) {\n var _initProps;\n\n // assigning into an array to define toString function on it\n var initProps = (_initProps = {\n key: title\n }, _initProps[HELMET_ATTRIBUTE] = true, _initProps);\n var props = convertElementAttributestoReactProps(attributes, initProps);\n\n return [React.createElement(TAG_NAMES.TITLE, props, title)];\n};\n\nvar generateTagsAsReactComponent = function generateTagsAsReactComponent(type, tags) {\n return tags.map(function (tag, i) {\n var _mappedTag;\n\n var mappedTag = (_mappedTag = {\n key: i\n }, _mappedTag[HELMET_ATTRIBUTE] = true, _mappedTag);\n\n Object.keys(tag).forEach(function (attribute) {\n var mappedAttribute = REACT_TAG_MAP[attribute] || attribute;\n\n if (mappedAttribute === TAG_PROPERTIES.INNER_HTML || mappedAttribute === TAG_PROPERTIES.CSS_TEXT) {\n var content = tag.innerHTML || tag.cssText;\n mappedTag.dangerouslySetInnerHTML = { __html: content };\n } else {\n mappedTag[mappedAttribute] = tag[attribute];\n }\n });\n\n return React.createElement(type, mappedTag);\n });\n};\n\nvar getMethodsForTag = function getMethodsForTag(type, tags, encode) {\n switch (type) {\n case TAG_NAMES.TITLE:\n return {\n toComponent: function toComponent() {\n return generateTitleAsReactComponent(type, tags.title, tags.titleAttributes, encode);\n },\n toString: function toString() {\n return generateTitleAsString(type, tags.title, tags.titleAttributes, encode);\n }\n };\n case ATTRIBUTE_NAMES.BODY:\n case ATTRIBUTE_NAMES.HTML:\n return {\n toComponent: function toComponent() {\n return convertElementAttributestoReactProps(tags);\n },\n toString: function toString() {\n return generateElementAttributesAsString(tags);\n }\n };\n default:\n return {\n toComponent: function toComponent() {\n return generateTagsAsReactComponent(type, tags);\n },\n toString: function toString() {\n return generateTagsAsString(type, tags, encode);\n }\n };\n }\n};\n\nvar mapStateOnServer = function mapStateOnServer(_ref) {\n var baseTag = _ref.baseTag,\n bodyAttributes = _ref.bodyAttributes,\n encode = _ref.encode,\n htmlAttributes = _ref.htmlAttributes,\n linkTags = _ref.linkTags,\n metaTags = _ref.metaTags,\n noscriptTags = _ref.noscriptTags,\n scriptTags = _ref.scriptTags,\n styleTags = _ref.styleTags,\n _ref$title = _ref.title,\n title = _ref$title === undefined ? \"\" : _ref$title,\n titleAttributes = _ref.titleAttributes;\n return {\n base: getMethodsForTag(TAG_NAMES.BASE, baseTag, encode),\n bodyAttributes: getMethodsForTag(ATTRIBUTE_NAMES.BODY, bodyAttributes, encode),\n htmlAttributes: getMethodsForTag(ATTRIBUTE_NAMES.HTML, htmlAttributes, encode),\n link: getMethodsForTag(TAG_NAMES.LINK, linkTags, encode),\n meta: getMethodsForTag(TAG_NAMES.META, metaTags, encode),\n noscript: getMethodsForTag(TAG_NAMES.NOSCRIPT, noscriptTags, encode),\n script: getMethodsForTag(TAG_NAMES.SCRIPT, scriptTags, encode),\n style: getMethodsForTag(TAG_NAMES.STYLE, styleTags, encode),\n title: getMethodsForTag(TAG_NAMES.TITLE, { title: title, titleAttributes: titleAttributes }, encode)\n };\n};\n\nvar Helmet = function Helmet(Component) {\n var _class, _temp;\n\n return _temp = _class = function (_React$Component) {\n inherits(HelmetWrapper, _React$Component);\n\n function HelmetWrapper() {\n classCallCheck(this, HelmetWrapper);\n return possibleConstructorReturn(this, _React$Component.apply(this, arguments));\n }\n\n HelmetWrapper.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {\n return !isEqual(this.props, nextProps);\n };\n\n HelmetWrapper.prototype.mapNestedChildrenToProps = function mapNestedChildrenToProps(child, nestedChildren) {\n if (!nestedChildren) {\n return null;\n }\n\n switch (child.type) {\n case TAG_NAMES.SCRIPT:\n case TAG_NAMES.NOSCRIPT:\n return {\n innerHTML: nestedChildren\n };\n\n case TAG_NAMES.STYLE:\n return {\n cssText: nestedChildren\n };\n }\n\n throw new Error(\"<\" + child.type + \" /> elements are self-closing and can not contain children. Refer to our API for more information.\");\n };\n\n HelmetWrapper.prototype.flattenArrayTypeChildren = function flattenArrayTypeChildren(_ref) {\n var _babelHelpers$extends;\n\n var child = _ref.child,\n arrayTypeChildren = _ref.arrayTypeChildren,\n newChildProps = _ref.newChildProps,\n nestedChildren = _ref.nestedChildren;\n\n return _extends({}, arrayTypeChildren, (_babelHelpers$extends = {}, _babelHelpers$extends[child.type] = [].concat(arrayTypeChildren[child.type] || [], [_extends({}, newChildProps, this.mapNestedChildrenToProps(child, nestedChildren))]), _babelHelpers$extends));\n };\n\n HelmetWrapper.prototype.mapObjectTypeChildren = function mapObjectTypeChildren(_ref2) {\n var _babelHelpers$extends2, _babelHelpers$extends3;\n\n var child = _ref2.child,\n newProps = _ref2.newProps,\n newChildProps = _ref2.newChildProps,\n nestedChildren = _ref2.nestedChildren;\n\n switch (child.type) {\n case TAG_NAMES.TITLE:\n return _extends({}, newProps, (_babelHelpers$extends2 = {}, _babelHelpers$extends2[child.type] = nestedChildren, _babelHelpers$extends2.titleAttributes = _extends({}, newChildProps), _babelHelpers$extends2));\n\n case TAG_NAMES.BODY:\n return _extends({}, newProps, {\n bodyAttributes: _extends({}, newChildProps)\n });\n\n case TAG_NAMES.HTML:\n return _extends({}, newProps, {\n htmlAttributes: _extends({}, newChildProps)\n });\n }\n\n return _extends({}, newProps, (_babelHelpers$extends3 = {}, _babelHelpers$extends3[child.type] = _extends({}, newChildProps), _babelHelpers$extends3));\n };\n\n HelmetWrapper.prototype.mapArrayTypeChildrenToProps = function mapArrayTypeChildrenToProps(arrayTypeChildren, newProps) {\n var newFlattenedProps = _extends({}, newProps);\n\n Object.keys(arrayTypeChildren).forEach(function (arrayChildName) {\n var _babelHelpers$extends4;\n\n newFlattenedProps = _extends({}, newFlattenedProps, (_babelHelpers$extends4 = {}, _babelHelpers$extends4[arrayChildName] = arrayTypeChildren[arrayChildName], _babelHelpers$extends4));\n });\n\n return newFlattenedProps;\n };\n\n HelmetWrapper.prototype.warnOnInvalidChildren = function warnOnInvalidChildren(child, nestedChildren) {\n if (process.env.NODE_ENV !== \"production\") {\n if (!VALID_TAG_NAMES.some(function (name) {\n return child.type === name;\n })) {\n if (typeof child.type === \"function\") {\n return warn(\"You may be attempting to nest components within each other, which is not allowed. Refer to our API for more information.\");\n }\n\n return warn(\"Only elements types \" + VALID_TAG_NAMES.join(\", \") + \" are allowed. Helmet does not support rendering <\" + child.type + \"> elements. Refer to our API for more information.\");\n }\n\n if (nestedChildren && typeof nestedChildren !== \"string\" && (!Array.isArray(nestedChildren) || nestedChildren.some(function (nestedChild) {\n return typeof nestedChild !== \"string\";\n }))) {\n throw new Error(\"Helmet expects a string as a child of <\" + child.type + \">. Did you forget to wrap your children in braces? ( <\" + child.type + \">{``}\" + child.type + \"> ) Refer to our API for more information.\");\n }\n }\n\n return true;\n };\n\n HelmetWrapper.prototype.mapChildrenToProps = function mapChildrenToProps(children, newProps) {\n var _this2 = this;\n\n var arrayTypeChildren = {};\n\n React.Children.forEach(children, function (child) {\n if (!child || !child.props) {\n return;\n }\n\n var _child$props = child.props,\n nestedChildren = _child$props.children,\n childProps = objectWithoutProperties(_child$props, [\"children\"]);\n\n var newChildProps = convertReactPropstoHtmlAttributes(childProps);\n\n _this2.warnOnInvalidChildren(child, nestedChildren);\n\n switch (child.type) {\n case TAG_NAMES.LINK:\n case TAG_NAMES.META:\n case TAG_NAMES.NOSCRIPT:\n case TAG_NAMES.SCRIPT:\n case TAG_NAMES.STYLE:\n arrayTypeChildren = _this2.flattenArrayTypeChildren({\n child: child,\n arrayTypeChildren: arrayTypeChildren,\n newChildProps: newChildProps,\n nestedChildren: nestedChildren\n });\n break;\n\n default:\n newProps = _this2.mapObjectTypeChildren({\n child: child,\n newProps: newProps,\n newChildProps: newChildProps,\n nestedChildren: nestedChildren\n });\n break;\n }\n });\n\n newProps = this.mapArrayTypeChildrenToProps(arrayTypeChildren, newProps);\n return newProps;\n };\n\n HelmetWrapper.prototype.render = function render() {\n var _props = this.props,\n children = _props.children,\n props = objectWithoutProperties(_props, [\"children\"]);\n\n var newProps = _extends({}, props);\n\n if (children) {\n newProps = this.mapChildrenToProps(children, newProps);\n }\n\n return React.createElement(Component, newProps);\n };\n\n createClass(HelmetWrapper, null, [{\n key: \"canUseDOM\",\n\n\n // Component.peek comes from react-side-effect:\n // For testing, you may use a static peek() method available on the returned component.\n // It lets you get the current state without resetting the mounted instance stack.\n // Don’t use it for anything other than testing.\n\n /**\n * @param {Object} base: {\"target\": \"_blank\", \"href\": \"http://mysite.com/\"}\n * @param {Object} bodyAttributes: {\"className\": \"root\"}\n * @param {String} defaultTitle: \"Default Title\"\n * @param {Boolean} defer: true\n * @param {Boolean} encodeSpecialCharacters: true\n * @param {Object} htmlAttributes: {\"lang\": \"en\", \"amp\": undefined}\n * @param {Array} link: [{\"rel\": \"canonical\", \"href\": \"http://mysite.com/example\"}]\n * @param {Array} meta: [{\"name\": \"description\", \"content\": \"Test description\"}]\n * @param {Array} noscript: [{\"innerHTML\": \"
console.log(newState)\"\n * @param {Array} script: [{\"type\": \"text/javascript\", \"src\": \"http://mysite.com/js/test.js\"}]\n * @param {Array} style: [{\"type\": \"text/css\", \"cssText\": \"div { display: block; color: blue; }\"}]\n * @param {String} title: \"Title\"\n * @param {Object} titleAttributes: {\"itemprop\": \"name\"}\n * @param {String} titleTemplate: \"MySite.com - %s\"\n */\n set: function set$$1(canUseDOM) {\n Component.canUseDOM = canUseDOM;\n }\n }]);\n return HelmetWrapper;\n }(React.Component), _class.propTypes = {\n base: PropTypes.object,\n bodyAttributes: PropTypes.object,\n children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]),\n defaultTitle: PropTypes.string,\n defer: PropTypes.bool,\n encodeSpecialCharacters: PropTypes.bool,\n htmlAttributes: PropTypes.object,\n link: PropTypes.arrayOf(PropTypes.object),\n meta: PropTypes.arrayOf(PropTypes.object),\n noscript: PropTypes.arrayOf(PropTypes.object),\n onChangeClientState: PropTypes.func,\n script: PropTypes.arrayOf(PropTypes.object),\n style: PropTypes.arrayOf(PropTypes.object),\n title: PropTypes.string,\n titleAttributes: PropTypes.object,\n titleTemplate: PropTypes.string\n }, _class.defaultProps = {\n defer: true,\n encodeSpecialCharacters: true\n }, _class.peek = Component.peek, _class.rewind = function () {\n var mappedState = Component.rewind();\n if (!mappedState) {\n // provide fallback if mappedState is undefined\n mappedState = mapStateOnServer({\n baseTag: [],\n bodyAttributes: {},\n encodeSpecialCharacters: true,\n htmlAttributes: {},\n linkTags: [],\n metaTags: [],\n noscriptTags: [],\n scriptTags: [],\n styleTags: [],\n title: \"\",\n titleAttributes: {}\n });\n }\n\n return mappedState;\n }, _temp;\n};\n\nvar NullComponent = function NullComponent() {\n return null;\n};\n\nvar HelmetSideEffects = withSideEffect(reducePropsToState, handleClientStateChange, mapStateOnServer)(NullComponent);\n\nvar HelmetExport = Helmet(HelmetSideEffects);\nHelmetExport.renderStatic = HelmetExport.rewind;\n\nexport default HelmetExport;\nexport { HelmetExport as Helmet };\n","import { __rest } from \"tslib\";\nimport * as React from 'react';\nimport useIntl from './useIntl';\nvar DisplayName;\n(function (DisplayName) {\n DisplayName[\"formatDate\"] = \"FormattedDate\";\n DisplayName[\"formatTime\"] = \"FormattedTime\";\n DisplayName[\"formatNumber\"] = \"FormattedNumber\";\n DisplayName[\"formatList\"] = \"FormattedList\";\n // Note that this DisplayName is the locale display name, not to be confused with\n // the name of the enum, which is for React component display name in dev tools.\n DisplayName[\"formatDisplayName\"] = \"FormattedDisplayName\";\n})(DisplayName || (DisplayName = {}));\nvar DisplayNameParts;\n(function (DisplayNameParts) {\n DisplayNameParts[\"formatDate\"] = \"FormattedDateParts\";\n DisplayNameParts[\"formatTime\"] = \"FormattedTimeParts\";\n DisplayNameParts[\"formatNumber\"] = \"FormattedNumberParts\";\n DisplayNameParts[\"formatList\"] = \"FormattedListParts\";\n})(DisplayNameParts || (DisplayNameParts = {}));\nexport var FormattedNumberParts = function (props) {\n var intl = useIntl();\n var value = props.value, children = props.children, formatProps = __rest(props, [\"value\", \"children\"]);\n return children(intl.formatNumberToParts(value, formatProps));\n};\nFormattedNumberParts.displayName = 'FormattedNumberParts';\nexport var FormattedListParts = function (props) {\n var intl = useIntl();\n var value = props.value, children = props.children, formatProps = __rest(props, [\"value\", \"children\"]);\n return children(intl.formatListToParts(value, formatProps));\n};\nFormattedNumberParts.displayName = 'FormattedNumberParts';\nexport function createFormattedDateTimePartsComponent(name) {\n var ComponentParts = function (props) {\n var intl = useIntl();\n var value = props.value, children = props.children, formatProps = __rest(props, [\"value\", \"children\"]);\n var date = typeof value === 'string' ? new Date(value || 0) : value;\n var formattedParts = name === 'formatDate'\n ? intl.formatDateToParts(date, formatProps)\n : intl.formatTimeToParts(date, formatProps);\n return children(formattedParts);\n };\n ComponentParts.displayName = DisplayNameParts[name];\n return ComponentParts;\n}\nexport function createFormattedComponent(name) {\n var Component = function (props) {\n var intl = useIntl();\n var value = props.value, children = props.children, formatProps = __rest(props\n // TODO: fix TS type definition for localeMatcher upstream\n , [\"value\", \"children\"]);\n // TODO: fix TS type definition for localeMatcher upstream\n var formattedValue = intl[name](value, formatProps);\n if (typeof children === 'function') {\n return children(formattedValue);\n }\n var Text = intl.textComponent || React.Fragment;\n return React.createElement(Text, null, formattedValue);\n };\n Component.displayName = DisplayName[name];\n return Component;\n}\n//# sourceMappingURL=createFormattedComponent.js.map","import { createFormattedComponent, createFormattedDateTimePartsComponent, } from './src/components/createFormattedComponent';\nimport injectIntl, { Provider as RawIntlProvider, Context as IntlContext, } from './src/components/injectIntl';\nimport useIntl from './src/components/useIntl';\nimport IntlProvider from './src/components/provider';\nimport { createIntl } from './src/components/createIntl';\nimport FormattedRelativeTime from './src/components/relative';\nimport FormattedPlural from './src/components/plural';\nimport FormattedMessage from './src/components/message';\nimport FormattedDateTimeRange from './src/components/dateTimeRange';\nexport { FormattedDateTimeRange, FormattedMessage, FormattedPlural, FormattedRelativeTime, IntlContext, IntlProvider, RawIntlProvider, createIntl, injectIntl, useIntl, };\nexport { createIntlCache, UnsupportedFormatterError, InvalidConfigError, MissingDataError, MessageFormatError, MissingTranslationError, IntlErrorCode as ReactIntlErrorCode, IntlError as ReactIntlError, } from '@formatjs/intl';\nexport function defineMessages(msgs) {\n return msgs;\n}\nexport function defineMessage(msg) {\n return msg;\n}\n// IMPORTANT: Explicit here to prevent api-extractor from outputing `import('./src/types').CustomFormatConfig`\nexport var FormattedDate = createFormattedComponent('formatDate');\nexport var FormattedTime = createFormattedComponent('formatTime');\nexport var FormattedNumber = createFormattedComponent('formatNumber');\nexport var FormattedList = createFormattedComponent('formatList');\nexport var FormattedDisplayName = createFormattedComponent('formatDisplayName');\nexport var FormattedDateParts = createFormattedDateTimePartsComponent('formatDate');\nexport var FormattedTimeParts = createFormattedDateTimePartsComponent('formatTime');\nexport { FormattedNumberParts, FormattedListParts, } from './src/components/createFormattedComponent';\n//# sourceMappingURL=index.js.map","import { __assign } from \"tslib\";\nimport hoistNonReactStatics from 'hoist-non-react-statics';\nimport * as React from 'react';\nimport { invariantIntlContext } from '../utils';\nfunction getDisplayName(Component) {\n return Component.displayName || Component.name || 'Component';\n}\n// This is primarily dealing with packaging systems where multiple copies of react-intl\n// might exist\nvar IntlContext = typeof window !== 'undefined' && !window.__REACT_INTL_BYPASS_GLOBAL_CONTEXT__\n ? window.__REACT_INTL_CONTEXT__ ||\n (window.__REACT_INTL_CONTEXT__ = React.createContext(null))\n : React.createContext(null);\nvar IntlConsumer = IntlContext.Consumer, IntlProvider = IntlContext.Provider;\nexport var Provider = IntlProvider;\nexport var Context = IntlContext;\nexport default function injectIntl(WrappedComponent, options) {\n var _a = options || {}, _b = _a.intlPropName, intlPropName = _b === void 0 ? 'intl' : _b, _c = _a.forwardRef, forwardRef = _c === void 0 ? false : _c, _d = _a.enforceContext, enforceContext = _d === void 0 ? true : _d;\n var WithIntl = function (props) { return (React.createElement(IntlConsumer, null, function (intl) {\n var _a;\n if (enforceContext) {\n invariantIntlContext(intl);\n }\n var intlProp = (_a = {}, _a[intlPropName] = intl, _a);\n return (React.createElement(WrappedComponent, __assign({}, props, intlProp, { ref: forwardRef ? props.forwardedRef : null })));\n })); };\n WithIntl.displayName = \"injectIntl(\".concat(getDisplayName(WrappedComponent), \")\");\n WithIntl.WrappedComponent = WrappedComponent;\n if (forwardRef) {\n return hoistNonReactStatics(\n // @ts-expect-error\n React.forwardRef(function (props, ref) { return (React.createElement(WithIntl, __assign({}, props, { forwardedRef: ref }))); }), WrappedComponent);\n }\n return hoistNonReactStatics(WithIntl, WrappedComponent);\n}\n//# sourceMappingURL=injectIntl.js.map","/*\n * Copyright 2015, Yahoo Inc.\n * Copyrights licensed under the New BSD License.\n * See the accompanying LICENSE file for terms.\n */\nimport { __rest } from \"tslib\";\nimport * as React from 'react';\nimport { shallowEqual } from '../utils';\nimport useIntl from './useIntl';\nfunction areEqual(prevProps, nextProps) {\n var values = prevProps.values, otherProps = __rest(prevProps, [\"values\"]);\n var nextValues = nextProps.values, nextOtherProps = __rest(nextProps, [\"values\"]);\n return (shallowEqual(nextValues, values) &&\n shallowEqual(otherProps, nextOtherProps));\n}\nfunction FormattedMessage(props) {\n var intl = useIntl();\n var formatMessage = intl.formatMessage, _a = intl.textComponent, Text = _a === void 0 ? React.Fragment : _a;\n var id = props.id, description = props.description, defaultMessage = props.defaultMessage, values = props.values, children = props.children, _b = props.tagName, Component = _b === void 0 ? Text : _b, ignoreTag = props.ignoreTag;\n var descriptor = { id: id, description: description, defaultMessage: defaultMessage };\n var nodes = formatMessage(descriptor, values, {\n ignoreTag: ignoreTag,\n });\n if (typeof children === 'function') {\n return children(Array.isArray(nodes) ? nodes : [nodes]);\n }\n if (Component) {\n return React.createElement(Component, null, React.Children.toArray(nodes));\n }\n return React.createElement(React.Fragment, null, nodes);\n}\nFormattedMessage.displayName = 'FormattedMessage';\nvar MemoizedFormattedMessage = React.memo(FormattedMessage, areEqual);\nMemoizedFormattedMessage.displayName = 'MemoizedFormattedMessage';\nexport default MemoizedFormattedMessage;\n//# sourceMappingURL=message.js.map","import { __assign } from \"tslib\";\nimport { invariant } from '@formatjs/ecma402-abstract';\nimport { IntlMessageFormat, } from 'intl-messageformat';\nimport { MissingTranslationError, MessageFormatError } from './error';\nimport { TYPE } from '@formatjs/icu-messageformat-parser';\nfunction setTimeZoneInOptions(opts, timeZone) {\n return Object.keys(opts).reduce(function (all, k) {\n all[k] = __assign({ timeZone: timeZone }, opts[k]);\n return all;\n }, {});\n}\nfunction deepMergeOptions(opts1, opts2) {\n var keys = Object.keys(__assign(__assign({}, opts1), opts2));\n return keys.reduce(function (all, k) {\n all[k] = __assign(__assign({}, (opts1[k] || {})), (opts2[k] || {}));\n return all;\n }, {});\n}\nfunction deepMergeFormatsAndSetTimeZone(f1, timeZone) {\n if (!timeZone) {\n return f1;\n }\n var mfFormats = IntlMessageFormat.formats;\n return __assign(__assign(__assign({}, mfFormats), f1), { date: deepMergeOptions(setTimeZoneInOptions(mfFormats.date, timeZone), setTimeZoneInOptions(f1.date || {}, timeZone)), time: deepMergeOptions(setTimeZoneInOptions(mfFormats.time, timeZone), setTimeZoneInOptions(f1.time || {}, timeZone)) });\n}\nexport var formatMessage = function (_a, state, messageDescriptor, values, opts) {\n var locale = _a.locale, formats = _a.formats, messages = _a.messages, defaultLocale = _a.defaultLocale, defaultFormats = _a.defaultFormats, fallbackOnEmptyString = _a.fallbackOnEmptyString, onError = _a.onError, timeZone = _a.timeZone, defaultRichTextElements = _a.defaultRichTextElements;\n if (messageDescriptor === void 0) { messageDescriptor = { id: '' }; }\n var msgId = messageDescriptor.id, defaultMessage = messageDescriptor.defaultMessage;\n // `id` is a required field of a Message Descriptor.\n invariant(!!msgId, \"[@formatjs/intl] An `id` must be provided to format a message. You can either:\\n1. Configure your build toolchain with [babel-plugin-formatjs](https://formatjs.io/docs/tooling/babel-plugin)\\nor [@formatjs/ts-transformer](https://formatjs.io/docs/tooling/ts-transformer) OR\\n2. Configure your `eslint` config to include [eslint-plugin-formatjs](https://formatjs.io/docs/tooling/linter#enforce-id)\\nto autofix this issue\");\n var id = String(msgId);\n var message = \n // In case messages is Object.create(null)\n // e.g import('foo.json') from webpack)\n // See https://github.com/formatjs/formatjs/issues/1914\n messages &&\n Object.prototype.hasOwnProperty.call(messages, id) &&\n messages[id];\n // IMPORTANT: Hot path if `message` is AST with a single literal node\n if (Array.isArray(message) &&\n message.length === 1 &&\n message[0].type === TYPE.literal) {\n return message[0].value;\n }\n // IMPORTANT: Hot path straight lookup for performance\n if (!values &&\n message &&\n typeof message === 'string' &&\n !defaultRichTextElements) {\n return message.replace(/'\\{(.*?)\\}'/gi, \"{$1}\");\n }\n values = __assign(__assign({}, defaultRichTextElements), (values || {}));\n formats = deepMergeFormatsAndSetTimeZone(formats, timeZone);\n defaultFormats = deepMergeFormatsAndSetTimeZone(defaultFormats, timeZone);\n if (!message) {\n if (fallbackOnEmptyString === false && message === '') {\n return message;\n }\n if (!defaultMessage ||\n (locale && locale.toLowerCase() !== defaultLocale.toLowerCase())) {\n // This prevents warnings from littering the console in development\n // when no `messages` are passed into the for the\n // default locale.\n onError(new MissingTranslationError(messageDescriptor, locale));\n }\n if (defaultMessage) {\n try {\n var formatter = state.getMessageFormat(defaultMessage, defaultLocale, defaultFormats, opts);\n return formatter.format(values);\n }\n catch (e) {\n onError(new MessageFormatError(\"Error formatting default message for: \\\"\".concat(id, \"\\\", rendering default message verbatim\"), locale, messageDescriptor, e));\n return typeof defaultMessage === 'string' ? defaultMessage : id;\n }\n }\n return id;\n }\n // We have the translated message\n try {\n var formatter = state.getMessageFormat(message, locale, formats, __assign({ formatters: state }, (opts || {})));\n return formatter.format(values);\n }\n catch (e) {\n onError(new MessageFormatError(\"Error formatting message: \\\"\".concat(id, \"\\\", using \").concat(defaultMessage ? 'default message' : 'id', \" as fallback.\"), locale, messageDescriptor, e));\n }\n if (defaultMessage) {\n try {\n var formatter = state.getMessageFormat(defaultMessage, defaultLocale, defaultFormats, opts);\n return formatter.format(values);\n }\n catch (e) {\n onError(new MessageFormatError(\"Error formatting the default message for: \\\"\".concat(id, \"\\\", rendering message verbatim\"), locale, messageDescriptor, e));\n }\n }\n if (typeof message === 'string') {\n return message;\n }\n if (typeof defaultMessage === 'string') {\n return defaultMessage;\n }\n return id;\n};\n//# sourceMappingURL=message.js.map","import { IntlFormatError } from './error';\nimport { filterProps, getNamedFormat } from './utils';\nvar NUMBER_FORMAT_OPTIONS = [\n 'style',\n 'currency',\n 'unit',\n 'unitDisplay',\n 'useGrouping',\n 'minimumIntegerDigits',\n 'minimumFractionDigits',\n 'maximumFractionDigits',\n 'minimumSignificantDigits',\n 'maximumSignificantDigits',\n // ES2020 NumberFormat\n 'compactDisplay',\n 'currencyDisplay',\n 'currencySign',\n 'notation',\n 'signDisplay',\n 'unit',\n 'unitDisplay',\n 'numberingSystem',\n // ES2023 NumberFormat\n 'trailingZeroDisplay',\n 'roundingPriority',\n 'roundingIncrement',\n 'roundingMode',\n];\nexport function getFormatter(_a, getNumberFormat, options) {\n var locale = _a.locale, formats = _a.formats, onError = _a.onError;\n if (options === void 0) { options = {}; }\n var format = options.format;\n var defaults = ((format &&\n getNamedFormat(formats, 'number', format, onError)) ||\n {});\n var filteredOptions = filterProps(options, NUMBER_FORMAT_OPTIONS, defaults);\n return getNumberFormat(locale, filteredOptions);\n}\nexport function formatNumber(config, getNumberFormat, value, options) {\n if (options === void 0) { options = {}; }\n try {\n return getFormatter(config, getNumberFormat, options).format(value);\n }\n catch (e) {\n config.onError(new IntlFormatError('Error formatting number.', config.locale, e));\n }\n return String(value);\n}\nexport function formatNumberToParts(config, getNumberFormat, value, options) {\n if (options === void 0) { options = {}; }\n try {\n return getFormatter(config, getNumberFormat, options).formatToParts(value);\n }\n catch (e) {\n config.onError(new IntlFormatError('Error formatting number.', config.locale, e));\n }\n return [];\n}\n//# sourceMappingURL=number.js.map","import { getNamedFormat, filterProps } from './utils';\nimport { FormatError, ErrorCode } from 'intl-messageformat';\nimport { IntlFormatError } from './error';\nvar RELATIVE_TIME_FORMAT_OPTIONS = ['numeric', 'style'];\nfunction getFormatter(_a, getRelativeTimeFormat, options) {\n var locale = _a.locale, formats = _a.formats, onError = _a.onError;\n if (options === void 0) { options = {}; }\n var format = options.format;\n var defaults = (!!format && getNamedFormat(formats, 'relative', format, onError)) || {};\n var filteredOptions = filterProps(options, RELATIVE_TIME_FORMAT_OPTIONS, defaults);\n return getRelativeTimeFormat(locale, filteredOptions);\n}\nexport function formatRelativeTime(config, getRelativeTimeFormat, value, unit, options) {\n if (options === void 0) { options = {}; }\n if (!unit) {\n unit = 'second';\n }\n var RelativeTimeFormat = Intl.RelativeTimeFormat;\n if (!RelativeTimeFormat) {\n config.onError(new FormatError(\"Intl.RelativeTimeFormat is not available in this environment.\\nTry polyfilling it using \\\"@formatjs/intl-relativetimeformat\\\"\\n\", ErrorCode.MISSING_INTL_API));\n }\n try {\n return getFormatter(config, getRelativeTimeFormat, options).format(value, unit);\n }\n catch (e) {\n config.onError(new IntlFormatError('Error formatting relative time.', config.locale, e));\n }\n return String(value);\n}\n//# sourceMappingURL=relativeTime.js.map","import { __assign } from \"tslib\";\nimport { filterProps, getNamedFormat } from './utils';\nimport { IntlFormatError } from './error';\nvar DATE_TIME_FORMAT_OPTIONS = [\n 'formatMatcher',\n 'timeZone',\n 'hour12',\n 'weekday',\n 'era',\n 'year',\n 'month',\n 'day',\n 'hour',\n 'minute',\n 'second',\n 'timeZoneName',\n 'hourCycle',\n 'dateStyle',\n 'timeStyle',\n 'calendar',\n // 'dayPeriod',\n 'numberingSystem',\n 'fractionalSecondDigits',\n];\nexport function getFormatter(_a, type, getDateTimeFormat, options) {\n var locale = _a.locale, formats = _a.formats, onError = _a.onError, timeZone = _a.timeZone;\n if (options === void 0) { options = {}; }\n var format = options.format;\n var defaults = __assign(__assign({}, (timeZone && { timeZone: timeZone })), (format && getNamedFormat(formats, type, format, onError)));\n var filteredOptions = filterProps(options, DATE_TIME_FORMAT_OPTIONS, defaults);\n if (type === 'time' &&\n !filteredOptions.hour &&\n !filteredOptions.minute &&\n !filteredOptions.second &&\n !filteredOptions.timeStyle &&\n !filteredOptions.dateStyle) {\n // Add default formatting options if hour, minute, or second isn't defined.\n filteredOptions = __assign(__assign({}, filteredOptions), { hour: 'numeric', minute: 'numeric' });\n }\n return getDateTimeFormat(locale, filteredOptions);\n}\nexport function formatDate(config, getDateTimeFormat) {\n var _a = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n _a[_i - 2] = arguments[_i];\n }\n var value = _a[0], _b = _a[1], options = _b === void 0 ? {} : _b;\n var date = typeof value === 'string' ? new Date(value || 0) : value;\n try {\n return getFormatter(config, 'date', getDateTimeFormat, options).format(date);\n }\n catch (e) {\n config.onError(new IntlFormatError('Error formatting date.', config.locale, e));\n }\n return String(date);\n}\nexport function formatTime(config, getDateTimeFormat) {\n var _a = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n _a[_i - 2] = arguments[_i];\n }\n var value = _a[0], _b = _a[1], options = _b === void 0 ? {} : _b;\n var date = typeof value === 'string' ? new Date(value || 0) : value;\n try {\n return getFormatter(config, 'time', getDateTimeFormat, options).format(date);\n }\n catch (e) {\n config.onError(new IntlFormatError('Error formatting time.', config.locale, e));\n }\n return String(date);\n}\nexport function formatDateTimeRange(config, getDateTimeFormat) {\n var _a = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n _a[_i - 2] = arguments[_i];\n }\n var from = _a[0], to = _a[1], _b = _a[2], options = _b === void 0 ? {} : _b;\n var timeZone = config.timeZone, locale = config.locale, onError = config.onError;\n var filteredOptions = filterProps(options, DATE_TIME_FORMAT_OPTIONS, timeZone ? { timeZone: timeZone } : {});\n try {\n return getDateTimeFormat(locale, filteredOptions).formatRange(from, to);\n }\n catch (e) {\n onError(new IntlFormatError('Error formatting date time range.', config.locale, e));\n }\n return String(from);\n}\nexport function formatDateToParts(config, getDateTimeFormat) {\n var _a = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n _a[_i - 2] = arguments[_i];\n }\n var value = _a[0], _b = _a[1], options = _b === void 0 ? {} : _b;\n var date = typeof value === 'string' ? new Date(value || 0) : value;\n try {\n return getFormatter(config, 'date', getDateTimeFormat, options).formatToParts(date); // TODO: remove this when https://github.com/microsoft/TypeScript/pull/50402 is merged\n }\n catch (e) {\n config.onError(new IntlFormatError('Error formatting date.', config.locale, e));\n }\n return [];\n}\nexport function formatTimeToParts(config, getDateTimeFormat) {\n var _a = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n _a[_i - 2] = arguments[_i];\n }\n var value = _a[0], _b = _a[1], options = _b === void 0 ? {} : _b;\n var date = typeof value === 'string' ? new Date(value || 0) : value;\n try {\n return getFormatter(config, 'time', getDateTimeFormat, options).formatToParts(date); // TODO: remove this when https://github.com/microsoft/TypeScript/pull/50402 is merged\n }\n catch (e) {\n config.onError(new IntlFormatError('Error formatting time.', config.locale, e));\n }\n return [];\n}\n//# sourceMappingURL=dateTime.js.map","import { filterProps } from './utils';\nimport { IntlFormatError } from './error';\nimport { ErrorCode, FormatError } from 'intl-messageformat';\nvar PLURAL_FORMAT_OPTIONS = ['type'];\nexport function formatPlural(_a, getPluralRules, value, options) {\n var locale = _a.locale, onError = _a.onError;\n if (options === void 0) { options = {}; }\n if (!Intl.PluralRules) {\n onError(new FormatError(\"Intl.PluralRules is not available in this environment.\\nTry polyfilling it using \\\"@formatjs/intl-pluralrules\\\"\\n\", ErrorCode.MISSING_INTL_API));\n }\n var filteredOptions = filterProps(options, PLURAL_FORMAT_OPTIONS);\n try {\n return getPluralRules(locale, filteredOptions).select(value);\n }\n catch (e) {\n onError(new IntlFormatError('Error formatting plural.', locale, e));\n }\n return 'other';\n}\n//# sourceMappingURL=plural.js.map","import { __assign } from \"tslib\";\nimport { filterProps } from './utils';\nimport { FormatError, ErrorCode } from 'intl-messageformat';\nimport { IntlFormatError } from './error';\nvar LIST_FORMAT_OPTIONS = [\n 'type',\n 'style',\n];\nvar now = Date.now();\nfunction generateToken(i) {\n return \"\".concat(now, \"_\").concat(i, \"_\").concat(now);\n}\nexport function formatList(opts, getListFormat, values, options) {\n if (options === void 0) { options = {}; }\n var results = formatListToParts(opts, getListFormat, values, options).reduce(function (all, el) {\n var val = el.value;\n if (typeof val !== 'string') {\n all.push(val);\n }\n else if (typeof all[all.length - 1] === 'string') {\n all[all.length - 1] += val;\n }\n else {\n all.push(val);\n }\n return all;\n }, []);\n return results.length === 1 ? results[0] : results.length === 0 ? '' : results;\n}\nexport function formatListToParts(_a, getListFormat, values, options) {\n var locale = _a.locale, onError = _a.onError;\n if (options === void 0) { options = {}; }\n var ListFormat = Intl.ListFormat;\n if (!ListFormat) {\n onError(new FormatError(\"Intl.ListFormat is not available in this environment.\\nTry polyfilling it using \\\"@formatjs/intl-listformat\\\"\\n\", ErrorCode.MISSING_INTL_API));\n }\n var filteredOptions = filterProps(options, LIST_FORMAT_OPTIONS);\n try {\n var richValues_1 = {};\n var serializedValues = values.map(function (v, i) {\n if (typeof v === 'object') {\n var id = generateToken(i);\n richValues_1[id] = v;\n return id;\n }\n return String(v);\n });\n return getListFormat(locale, filteredOptions)\n .formatToParts(serializedValues)\n .map(function (part) {\n return part.type === 'literal'\n ? part\n : __assign(__assign({}, part), { value: richValues_1[part.value] || part.value });\n });\n }\n catch (e) {\n onError(new IntlFormatError('Error formatting list.', locale, e));\n }\n // @ts-ignore\n return values;\n}\n//# sourceMappingURL=list.js.map","import { filterProps } from './utils';\nimport { FormatError, ErrorCode } from 'intl-messageformat';\nimport { IntlFormatError } from './error';\nvar DISPLAY_NAMES_OPTONS = [\n 'style',\n 'type',\n 'fallback',\n 'languageDisplay',\n];\nexport function formatDisplayName(_a, getDisplayNames, value, options) {\n var locale = _a.locale, onError = _a.onError;\n var DisplayNames = Intl.DisplayNames;\n if (!DisplayNames) {\n onError(new FormatError(\"Intl.DisplayNames is not available in this environment.\\nTry polyfilling it using \\\"@formatjs/intl-displaynames\\\"\\n\", ErrorCode.MISSING_INTL_API));\n }\n var filteredOptions = filterProps(options, DISPLAY_NAMES_OPTONS);\n try {\n return getDisplayNames(locale, filteredOptions).of(value);\n }\n catch (e) {\n onError(new IntlFormatError('Error formatting display name.', locale, e));\n }\n}\n//# sourceMappingURL=displayName.js.map","/*\n * Copyright 2015, Yahoo Inc.\n * Copyrights licensed under the New BSD License.\n * See the accompanying LICENSE file for terms.\n */\nimport { __assign, __rest, __spreadArray } from \"tslib\";\nimport { createIntl as coreCreateIntl, formatMessage as coreFormatMessage, } from '@formatjs/intl';\nimport * as React from 'react';\nimport { DEFAULT_INTL_CONFIG, assignUniqueKeysToParts } from '../utils';\nimport { isFormatXMLElementFn, } from 'intl-messageformat';\nfunction assignUniqueKeysToFormatXMLElementFnArgument(values) {\n if (!values) {\n return values;\n }\n return Object.keys(values).reduce(function (acc, k) {\n var v = values[k];\n acc[k] = isFormatXMLElementFn(v)\n ? assignUniqueKeysToParts(v)\n : v;\n return acc;\n }, {});\n}\nvar formatMessage = function (config, formatters, descriptor, rawValues) {\n var rest = [];\n for (var _i = 4; _i < arguments.length; _i++) {\n rest[_i - 4] = arguments[_i];\n }\n var values = assignUniqueKeysToFormatXMLElementFnArgument(rawValues);\n var chunks = coreFormatMessage.apply(void 0, __spreadArray([config,\n formatters,\n descriptor,\n values], rest, false));\n if (Array.isArray(chunks)) {\n return React.Children.toArray(chunks);\n }\n return chunks;\n};\n/**\n * Create intl object\n * @param config intl config\n * @param cache cache for formatter instances to prevent memory leak\n */\nexport var createIntl = function (_a, cache) {\n var rawDefaultRichTextElements = _a.defaultRichTextElements, config = __rest(_a, [\"defaultRichTextElements\"]);\n var defaultRichTextElements = assignUniqueKeysToFormatXMLElementFnArgument(rawDefaultRichTextElements);\n var coreIntl = coreCreateIntl(__assign(__assign(__assign({}, DEFAULT_INTL_CONFIG), config), { defaultRichTextElements: defaultRichTextElements }), cache);\n var resolvedConfig = {\n locale: coreIntl.locale,\n timeZone: coreIntl.timeZone,\n fallbackOnEmptyString: coreIntl.fallbackOnEmptyString,\n formats: coreIntl.formats,\n defaultLocale: coreIntl.defaultLocale,\n defaultFormats: coreIntl.defaultFormats,\n messages: coreIntl.messages,\n onError: coreIntl.onError,\n defaultRichTextElements: defaultRichTextElements,\n };\n return __assign(__assign({}, coreIntl), { formatMessage: formatMessage.bind(null, resolvedConfig, \n // @ts-expect-error fix this\n coreIntl.formatters), \n // @ts-expect-error fix this\n $t: formatMessage.bind(null, resolvedConfig, coreIntl.formatters) });\n};\n//# sourceMappingURL=createIntl.js.map","import { __assign } from \"tslib\";\nimport { createFormatters, DEFAULT_INTL_CONFIG } from './utils';\nimport { InvalidConfigError, MissingDataError } from './error';\nimport { formatNumber, formatNumberToParts } from './number';\nimport { formatRelativeTime } from './relativeTime';\nimport { formatDate, formatDateToParts, formatTime, formatTimeToParts, formatDateTimeRange, } from './dateTime';\nimport { formatPlural } from './plural';\nimport { formatMessage } from './message';\nimport { formatList, formatListToParts } from './list';\nimport { formatDisplayName } from './displayName';\nfunction messagesContainString(messages) {\n var firstMessage = messages ? messages[Object.keys(messages)[0]] : undefined;\n return typeof firstMessage === 'string';\n}\nfunction verifyConfigMessages(config) {\n if (config.onWarn &&\n config.defaultRichTextElements &&\n messagesContainString(config.messages || {})) {\n config.onWarn(\"[@formatjs/intl] \\\"defaultRichTextElements\\\" was specified but \\\"message\\\" was not pre-compiled. \\nPlease consider using \\\"@formatjs/cli\\\" to pre-compile your messages for performance.\\nFor more details see https://formatjs.io/docs/getting-started/message-distribution\");\n }\n}\n/**\n * Create intl object\n * @param config intl config\n * @param cache cache for formatter instances to prevent memory leak\n */\nexport function createIntl(config, cache) {\n var formatters = createFormatters(cache);\n var resolvedConfig = __assign(__assign({}, DEFAULT_INTL_CONFIG), config);\n var locale = resolvedConfig.locale, defaultLocale = resolvedConfig.defaultLocale, onError = resolvedConfig.onError;\n if (!locale) {\n if (onError) {\n onError(new InvalidConfigError(\"\\\"locale\\\" was not configured, using \\\"\".concat(defaultLocale, \"\\\" as fallback. See https://formatjs.io/docs/react-intl/api#intlshape for more details\")));\n }\n // Since there's no registered locale data for `locale`, this will\n // fallback to the `defaultLocale` to make sure things can render.\n // The `messages` are overridden to the `defaultProps` empty object\n // to maintain referential equality across re-renders. It's assumed\n // each contains a `defaultMessage` prop.\n resolvedConfig.locale = resolvedConfig.defaultLocale || 'en';\n }\n else if (!Intl.NumberFormat.supportedLocalesOf(locale).length && onError) {\n onError(new MissingDataError(\"Missing locale data for locale: \\\"\".concat(locale, \"\\\" in Intl.NumberFormat. Using default locale: \\\"\").concat(defaultLocale, \"\\\" as fallback. See https://formatjs.io/docs/react-intl#runtime-requirements for more details\")));\n }\n else if (!Intl.DateTimeFormat.supportedLocalesOf(locale).length &&\n onError) {\n onError(new MissingDataError(\"Missing locale data for locale: \\\"\".concat(locale, \"\\\" in Intl.DateTimeFormat. Using default locale: \\\"\").concat(defaultLocale, \"\\\" as fallback. See https://formatjs.io/docs/react-intl#runtime-requirements for more details\")));\n }\n verifyConfigMessages(resolvedConfig);\n return __assign(__assign({}, resolvedConfig), { formatters: formatters, formatNumber: formatNumber.bind(null, resolvedConfig, formatters.getNumberFormat), formatNumberToParts: formatNumberToParts.bind(null, resolvedConfig, formatters.getNumberFormat), formatRelativeTime: formatRelativeTime.bind(null, resolvedConfig, formatters.getRelativeTimeFormat), formatDate: formatDate.bind(null, resolvedConfig, formatters.getDateTimeFormat), formatDateToParts: formatDateToParts.bind(null, resolvedConfig, formatters.getDateTimeFormat), formatTime: formatTime.bind(null, resolvedConfig, formatters.getDateTimeFormat), formatDateTimeRange: formatDateTimeRange.bind(null, resolvedConfig, formatters.getDateTimeFormat), formatTimeToParts: formatTimeToParts.bind(null, resolvedConfig, formatters.getDateTimeFormat), formatPlural: formatPlural.bind(null, resolvedConfig, formatters.getPluralRules), \n // @ts-expect-error TODO: will get to this later\n formatMessage: formatMessage.bind(null, resolvedConfig, formatters), \n // @ts-expect-error TODO: will get to this later\n $t: formatMessage.bind(null, resolvedConfig, formatters), formatList: formatList.bind(null, resolvedConfig, formatters.getListFormat), formatListToParts: formatListToParts.bind(null, resolvedConfig, formatters.getListFormat), formatDisplayName: formatDisplayName.bind(null, resolvedConfig, formatters.getDisplayNames) });\n}\n//# sourceMappingURL=create-intl.js.map","/*\n * Copyright 2015, Yahoo Inc.\n * Copyrights licensed under the New BSD License.\n * See the accompanying LICENSE file for terms.\n */\nimport { __extends } from \"tslib\";\nimport { createIntlCache } from '@formatjs/intl';\nimport * as React from 'react';\nimport { DEFAULT_INTL_CONFIG, invariantIntlContext, shallowEqual } from '../utils';\nimport { Provider } from './injectIntl';\nimport { createIntl } from './createIntl';\nfunction processIntlConfig(config) {\n return {\n locale: config.locale,\n timeZone: config.timeZone,\n fallbackOnEmptyString: config.fallbackOnEmptyString,\n formats: config.formats,\n textComponent: config.textComponent,\n messages: config.messages,\n defaultLocale: config.defaultLocale,\n defaultFormats: config.defaultFormats,\n onError: config.onError,\n onWarn: config.onWarn,\n wrapRichTextChunksInFragment: config.wrapRichTextChunksInFragment,\n defaultRichTextElements: config.defaultRichTextElements,\n };\n}\nvar IntlProvider = /** @class */ (function (_super) {\n __extends(IntlProvider, _super);\n function IntlProvider() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.cache = createIntlCache();\n _this.state = {\n cache: _this.cache,\n intl: createIntl(processIntlConfig(_this.props), _this.cache),\n prevConfig: processIntlConfig(_this.props),\n };\n return _this;\n }\n IntlProvider.getDerivedStateFromProps = function (props, _a) {\n var prevConfig = _a.prevConfig, cache = _a.cache;\n var config = processIntlConfig(props);\n if (!shallowEqual(prevConfig, config)) {\n return {\n intl: createIntl(config, cache),\n prevConfig: config,\n };\n }\n return null;\n };\n IntlProvider.prototype.render = function () {\n invariantIntlContext(this.state.intl);\n return React.createElement(Provider, { value: this.state.intl }, this.props.children);\n };\n IntlProvider.displayName = 'IntlProvider';\n IntlProvider.defaultProps = DEFAULT_INTL_CONFIG;\n return IntlProvider;\n}(React.PureComponent));\nexport default IntlProvider;\n//# sourceMappingURL=provider.js.map","import * as React from 'react';\nimport { invariantIntlContext } from '../utils';\nimport { Context } from './injectIntl';\nexport default function useIntl() {\n var intl = React.useContext(Context);\n invariantIntlContext(intl);\n return intl;\n}\n//# sourceMappingURL=useIntl.js.map","import { __assign } from \"tslib\";\nimport * as React from 'react';\nimport { invariant } from '@formatjs/ecma402-abstract';\nimport { DEFAULT_INTL_CONFIG as CORE_DEFAULT_INTL_CONFIG } from '@formatjs/intl';\nexport function invariantIntlContext(intl) {\n invariant(intl, '[React Intl] Could not find required `intl` object. ' +\n ' needs to exist in the component ancestry.');\n}\nexport var DEFAULT_INTL_CONFIG = __assign(__assign({}, CORE_DEFAULT_INTL_CONFIG), { textComponent: React.Fragment });\n/**\n * Takes a `formatXMLElementFn`, and composes it in function, which passes\n * argument `parts` through, assigning unique key to each part, to prevent\n * \"Each child in a list should have a unique \"key\"\" React error.\n * @param formatXMLElementFn\n */\nexport function assignUniqueKeysToParts(formatXMLElementFn) {\n return function (parts) {\n // eslint-disable-next-line prefer-rest-params\n return formatXMLElementFn(React.Children.toArray(parts));\n };\n}\nexport function shallowEqual(objA, objB) {\n if (objA === objB) {\n return true;\n }\n if (!objA || !objB) {\n return false;\n }\n var aKeys = Object.keys(objA);\n var bKeys = Object.keys(objB);\n var len = aKeys.length;\n if (bKeys.length !== len) {\n return false;\n }\n for (var i = 0; i < len; i++) {\n var key = aKeys[i];\n if (objA[key] !== objB[key] ||\n !Object.prototype.hasOwnProperty.call(objB, key)) {\n return false;\n }\n }\n return true;\n}\n//# sourceMappingURL=utils.js.map","/** @license React v16.13.1\n * react-is.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';var b=\"function\"===typeof Symbol&&Symbol.for,c=b?Symbol.for(\"react.element\"):60103,d=b?Symbol.for(\"react.portal\"):60106,e=b?Symbol.for(\"react.fragment\"):60107,f=b?Symbol.for(\"react.strict_mode\"):60108,g=b?Symbol.for(\"react.profiler\"):60114,h=b?Symbol.for(\"react.provider\"):60109,k=b?Symbol.for(\"react.context\"):60110,l=b?Symbol.for(\"react.async_mode\"):60111,m=b?Symbol.for(\"react.concurrent_mode\"):60111,n=b?Symbol.for(\"react.forward_ref\"):60112,p=b?Symbol.for(\"react.suspense\"):60113,q=b?\nSymbol.for(\"react.suspense_list\"):60120,r=b?Symbol.for(\"react.memo\"):60115,t=b?Symbol.for(\"react.lazy\"):60116,v=b?Symbol.for(\"react.block\"):60121,w=b?Symbol.for(\"react.fundamental\"):60117,x=b?Symbol.for(\"react.responder\"):60118,y=b?Symbol.for(\"react.scope\"):60119;\nfunction z(a){if(\"object\"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;exports.Fragment=e;exports.Lazy=t;exports.Memo=r;exports.Portal=d;\nexports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isAsyncMode=function(a){return A(a)||z(a)===l};exports.isConcurrentMode=A;exports.isContextConsumer=function(a){return z(a)===k};exports.isContextProvider=function(a){return z(a)===h};exports.isElement=function(a){return\"object\"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return z(a)===n};exports.isFragment=function(a){return z(a)===e};exports.isLazy=function(a){return z(a)===t};\nexports.isMemo=function(a){return z(a)===r};exports.isPortal=function(a){return z(a)===d};exports.isProfiler=function(a){return z(a)===g};exports.isStrictMode=function(a){return z(a)===f};exports.isSuspense=function(a){return z(a)===p};\nexports.isValidElementType=function(a){return\"string\"===typeof a||\"function\"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||\"object\"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)};exports.typeOf=z;\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-is.production.min.js');\n} else {\n module.exports = require('./cjs/react-is.development.js');\n}\n","/**\n * react-number-format - 5.4.2\n * Author : Sudhanshu Yadav\n * Copyright (c) 2016, 2024 to Sudhanshu Yadav, released under the MIT license.\n * https://github.com/s-yadav/react-number-format\n */\n\nimport React, { useState, useMemo, useRef, useEffect, useLayoutEffect } from 'react';\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nfunction __rest(s, e) {\r\n var t = {};\r\n for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n { t[p] = s[p]; } }\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n { for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n { t[p[i]] = s[p[i]]; }\r\n } }\r\n return t;\r\n}\n\nvar SourceType;\n(function (SourceType) {\n SourceType[\"event\"] = \"event\";\n SourceType[\"props\"] = \"prop\";\n})(SourceType || (SourceType = {}));\n\n// basic noop function\nfunction noop() { }\nfunction memoizeOnce(cb) {\n var lastArgs;\n var lastValue = undefined;\n return function () {\n var args = [], len = arguments.length;\n while ( len-- ) args[ len ] = arguments[ len ];\n\n if (lastArgs &&\n args.length === lastArgs.length &&\n args.every(function (value, index) { return value === lastArgs[index]; })) {\n return lastValue;\n }\n lastArgs = args;\n lastValue = cb.apply(void 0, args);\n return lastValue;\n };\n}\nfunction charIsNumber(char) {\n return !!(char || '').match(/\\d/);\n}\nfunction isNil(val) {\n return val === null || val === undefined;\n}\nfunction isNanValue(val) {\n return typeof val === 'number' && isNaN(val);\n}\nfunction isNotValidValue(val) {\n return isNil(val) || isNanValue(val) || (typeof val === 'number' && !isFinite(val));\n}\nfunction escapeRegExp(str) {\n return str.replace(/[-[\\]/{}()*+?.\\\\^$|]/g, '\\\\$&');\n}\nfunction getThousandsGroupRegex(thousandsGroupStyle) {\n switch (thousandsGroupStyle) {\n case 'lakh':\n return /(\\d+?)(?=(\\d\\d)+(\\d)(?!\\d))(\\.\\d+)?/g;\n case 'wan':\n return /(\\d)(?=(\\d{4})+(?!\\d))/g;\n case 'thousand':\n default:\n return /(\\d)(?=(\\d{3})+(?!\\d))/g;\n }\n}\nfunction applyThousandSeparator(str, thousandSeparator, thousandsGroupStyle) {\n var thousandsGroupRegex = getThousandsGroupRegex(thousandsGroupStyle);\n var index = str.search(/[1-9]/);\n index = index === -1 ? str.length : index;\n return (str.substring(0, index) +\n str.substring(index, str.length).replace(thousandsGroupRegex, '$1' + thousandSeparator));\n}\nfunction usePersistentCallback(cb) {\n var callbackRef = useRef(cb);\n // keep the callback ref upto date\n callbackRef.current = cb;\n /**\n * initialize a persistent callback which never changes\n * through out the component lifecycle\n */\n var persistentCbRef = useRef(function () {\n var args = [], len = arguments.length;\n while ( len-- ) args[ len ] = arguments[ len ];\n\n return callbackRef.current.apply(callbackRef, args);\n });\n return persistentCbRef.current;\n}\n//spilt a float number into different parts beforeDecimal, afterDecimal, and negation\nfunction splitDecimal(numStr, allowNegative) {\n if ( allowNegative === void 0 ) allowNegative = true;\n\n var hasNegation = numStr[0] === '-';\n var addNegation = hasNegation && allowNegative;\n numStr = numStr.replace('-', '');\n var parts = numStr.split('.');\n var beforeDecimal = parts[0];\n var afterDecimal = parts[1] || '';\n return {\n beforeDecimal: beforeDecimal,\n afterDecimal: afterDecimal,\n hasNegation: hasNegation,\n addNegation: addNegation,\n };\n}\nfunction fixLeadingZero(numStr) {\n if (!numStr)\n { return numStr; }\n var isNegative = numStr[0] === '-';\n if (isNegative)\n { numStr = numStr.substring(1, numStr.length); }\n var parts = numStr.split('.');\n var beforeDecimal = parts[0].replace(/^0+/, '') || '0';\n var afterDecimal = parts[1] || '';\n return (\"\" + (isNegative ? '-' : '') + beforeDecimal + (afterDecimal ? (\".\" + afterDecimal) : ''));\n}\n/**\n * limit decimal numbers to given scale\n * Not used .fixedTo because that will break with big numbers\n */\nfunction limitToScale(numStr, scale, fixedDecimalScale) {\n var str = '';\n var filler = fixedDecimalScale ? '0' : '';\n for (var i = 0; i <= scale - 1; i++) {\n str += numStr[i] || filler;\n }\n return str;\n}\nfunction repeat(str, count) {\n return Array(count + 1).join(str);\n}\nfunction toNumericString(num) {\n var _num = num + ''; // typecast number to string\n // store the sign and remove it from the number.\n var sign = _num[0] === '-' ? '-' : '';\n if (sign)\n { _num = _num.substring(1); }\n // split the number into cofficient and exponent\n var ref = _num.split(/[eE]/g);\n var coefficient = ref[0];\n var exponent = ref[1];\n // covert exponent to number;\n exponent = Number(exponent);\n // if there is no exponent part or its 0, return the coffiecient with sign\n if (!exponent)\n { return sign + coefficient; }\n coefficient = coefficient.replace('.', '');\n /**\n * for scientific notation the current decimal index will be after first number (index 0)\n * So effective decimal index will always be 1 + exponent value\n */\n var decimalIndex = 1 + exponent;\n var coffiecientLn = coefficient.length;\n if (decimalIndex < 0) {\n // if decimal index is less then 0 add preceding 0s\n // add 1 as join will have\n coefficient = '0.' + repeat('0', Math.abs(decimalIndex)) + coefficient;\n }\n else if (decimalIndex >= coffiecientLn) {\n // if decimal index is less then 0 add leading 0s\n coefficient = coefficient + repeat('0', decimalIndex - coffiecientLn);\n }\n else {\n // else add decimal point at proper index\n coefficient =\n (coefficient.substring(0, decimalIndex) || '0') + '.' + coefficient.substring(decimalIndex);\n }\n return sign + coefficient;\n}\n/**\n * This method is required to round prop value to given scale.\n * Not used .round or .fixedTo because that will break with big numbers\n */\nfunction roundToPrecision(numStr, scale, fixedDecimalScale) {\n //if number is empty don't do anything return empty string\n if (['', '-'].indexOf(numStr) !== -1)\n { return numStr; }\n var shouldHaveDecimalSeparator = (numStr.indexOf('.') !== -1 || fixedDecimalScale) && scale;\n var ref = splitDecimal(numStr);\n var beforeDecimal = ref.beforeDecimal;\n var afterDecimal = ref.afterDecimal;\n var hasNegation = ref.hasNegation;\n var floatValue = parseFloat((\"0.\" + (afterDecimal || '0')));\n var floatValueStr = afterDecimal.length <= scale ? (\"0.\" + afterDecimal) : floatValue.toFixed(scale);\n var roundedDecimalParts = floatValueStr.split('.');\n var intPart = beforeDecimal;\n // if we have cary over from rounding decimal part, add that on before decimal\n if (beforeDecimal && Number(roundedDecimalParts[0])) {\n intPart = beforeDecimal\n .split('')\n .reverse()\n .reduce(function (roundedStr, current, idx) {\n if (roundedStr.length > idx) {\n return ((Number(roundedStr[0]) + Number(current)).toString() +\n roundedStr.substring(1, roundedStr.length));\n }\n return current + roundedStr;\n }, roundedDecimalParts[0]);\n }\n var decimalPart = limitToScale(roundedDecimalParts[1] || '', scale, fixedDecimalScale);\n var negation = hasNegation ? '-' : '';\n var decimalSeparator = shouldHaveDecimalSeparator ? '.' : '';\n return (\"\" + negation + intPart + decimalSeparator + decimalPart);\n}\n/** set the caret positon in an input field **/\nfunction setCaretPosition(el, caretPos) {\n el.value = el.value;\n // ^ this is used to not only get 'focus', but\n // to make sure we don't have it everything -selected-\n // (it causes an issue in chrome, and having it doesn't hurt any other browser)\n if (el !== null) {\n /* @ts-ignore */\n if (el.createTextRange) {\n /* @ts-ignore */\n var range = el.createTextRange();\n range.move('character', caretPos);\n range.select();\n return true;\n }\n // (el.selectionStart === 0 added for Firefox bug)\n if (el.selectionStart || el.selectionStart === 0) {\n el.focus();\n el.setSelectionRange(caretPos, caretPos);\n return true;\n }\n // fail city, fortunately this never happens (as far as I've tested) :)\n el.focus();\n return false;\n }\n}\n/**\n * TODO: remove dependency of findChangeRange, findChangedRangeFromCaretPositions is better way to find what is changed\n * currently this is mostly required by test and isCharacterSame util\n * Given previous value and newValue it returns the index\n * start - end to which values have changed.\n * This function makes assumption about only consecutive\n * characters are changed which is correct assumption for caret input.\n */\nvar findChangeRange = memoizeOnce(function (prevValue, newValue) {\n var i = 0, j = 0;\n var prevLength = prevValue.length;\n var newLength = newValue.length;\n while (prevValue[i] === newValue[i] && i < prevLength)\n { i++; }\n //check what has been changed from last\n while (prevValue[prevLength - 1 - j] === newValue[newLength - 1 - j] &&\n newLength - j > i &&\n prevLength - j > i) {\n j++;\n }\n return {\n from: { start: i, end: prevLength - j },\n to: { start: i, end: newLength - j },\n };\n});\nvar findChangedRangeFromCaretPositions = function (lastCaretPositions, currentCaretPosition) {\n var startPosition = Math.min(lastCaretPositions.selectionStart, currentCaretPosition);\n return {\n from: { start: startPosition, end: lastCaretPositions.selectionEnd },\n to: { start: startPosition, end: currentCaretPosition },\n };\n};\n/*\n Returns a number whose value is limited to the given range\n*/\nfunction clamp(num, min, max) {\n return Math.min(Math.max(num, min), max);\n}\nfunction geInputCaretPosition(el) {\n /*Max of selectionStart and selectionEnd is taken for the patch of pixel and other mobile device caret bug*/\n return Math.max(el.selectionStart, el.selectionEnd);\n}\nfunction addInputMode() {\n return (typeof navigator !== 'undefined' &&\n !(navigator.platform && /iPhone|iPod/.test(navigator.platform)));\n}\nfunction getDefaultChangeMeta(value) {\n return {\n from: {\n start: 0,\n end: 0,\n },\n to: {\n start: 0,\n end: value.length,\n },\n lastValue: '',\n };\n}\nfunction getMaskAtIndex(mask, index) {\n if ( mask === void 0 ) mask = ' ';\n\n if (typeof mask === 'string') {\n return mask;\n }\n return mask[index] || ' ';\n}\nfunction defaultIsCharacterSame(ref) {\n var currentValue = ref.currentValue;\n var formattedValue = ref.formattedValue;\n var currentValueIndex = ref.currentValueIndex;\n var formattedValueIndex = ref.formattedValueIndex;\n\n return currentValue[currentValueIndex] === formattedValue[formattedValueIndex];\n}\nfunction getCaretPosition(newFormattedValue, lastFormattedValue, curValue, curCaretPos, boundary, isValidInputCharacter, \n/**\n * format function can change the character, the caret engine relies on mapping old value and new value\n * In such case if character is changed, parent can tell which chars are equivalent\n * Some example, all allowedDecimalCharacters are updated to decimalCharacters, 2nd case if user is coverting\n * number to different numeric system.\n */\nisCharacterSame) {\n if ( isCharacterSame === void 0 ) isCharacterSame = defaultIsCharacterSame;\n\n /**\n * if something got inserted on empty value, add the formatted character before the current value,\n * This is to avoid the case where typed character is present on format characters\n */\n var firstAllowedPosition = boundary.findIndex(function (b) { return b; });\n var prefixFormat = newFormattedValue.slice(0, firstAllowedPosition);\n if (!lastFormattedValue && !curValue.startsWith(prefixFormat)) {\n lastFormattedValue = prefixFormat;\n curValue = prefixFormat + curValue;\n curCaretPos = curCaretPos + prefixFormat.length;\n }\n var curValLn = curValue.length;\n var formattedValueLn = newFormattedValue.length;\n // create index map\n var addedIndexMap = {};\n var indexMap = new Array(curValLn);\n for (var i = 0; i < curValLn; i++) {\n indexMap[i] = -1;\n for (var j = 0, jLn = formattedValueLn; j < jLn; j++) {\n var isCharSame = isCharacterSame({\n currentValue: curValue,\n lastValue: lastFormattedValue,\n formattedValue: newFormattedValue,\n currentValueIndex: i,\n formattedValueIndex: j,\n });\n if (isCharSame && addedIndexMap[j] !== true) {\n indexMap[i] = j;\n addedIndexMap[j] = true;\n break;\n }\n }\n }\n /**\n * For current caret position find closest characters (left and right side)\n * which are properly mapped to formatted value.\n * The idea is that the new caret position will exist always in the boundary of\n * that mapped index\n */\n var pos = curCaretPos;\n while (pos < curValLn && (indexMap[pos] === -1 || !isValidInputCharacter(curValue[pos]))) {\n pos++;\n }\n // if the caret position is on last keep the endIndex as last for formatted value\n var endIndex = pos === curValLn || indexMap[pos] === -1 ? formattedValueLn : indexMap[pos];\n pos = curCaretPos - 1;\n while (pos > 0 && indexMap[pos] === -1)\n { pos--; }\n var startIndex = pos === -1 || indexMap[pos] === -1 ? 0 : indexMap[pos] + 1;\n /**\n * case where a char is added on suffix and removed from middle, example 2sq345 becoming $2,345 sq\n * there is still a mapping but the order of start index and end index is changed\n */\n if (startIndex > endIndex)\n { return endIndex; }\n /**\n * given the current caret position if it closer to startIndex\n * keep the new caret position on start index or keep it closer to endIndex\n */\n return curCaretPos - startIndex < endIndex - curCaretPos ? startIndex : endIndex;\n}\n/* This keeps the caret within typing area so people can't type in between prefix or suffix or format characters */\nfunction getCaretPosInBoundary(value, caretPos, boundary, direction) {\n var valLn = value.length;\n // clamp caret position to [0, value.length]\n caretPos = clamp(caretPos, 0, valLn);\n if (direction === 'left') {\n while (caretPos >= 0 && !boundary[caretPos])\n { caretPos--; }\n // if we don't find any suitable caret position on left, set it on first allowed position\n if (caretPos === -1)\n { caretPos = boundary.indexOf(true); }\n }\n else {\n while (caretPos <= valLn && !boundary[caretPos])\n { caretPos++; }\n // if we don't find any suitable caret position on right, set it on last allowed position\n if (caretPos > valLn)\n { caretPos = boundary.lastIndexOf(true); }\n }\n // if we still don't find caret position, set it at the end of value\n if (caretPos === -1)\n { caretPos = valLn; }\n return caretPos;\n}\nfunction caretUnknownFormatBoundary(formattedValue) {\n var boundaryAry = Array.from({ length: formattedValue.length + 1 }).map(function () { return true; });\n for (var i = 0, ln = boundaryAry.length; i < ln; i++) {\n // consider caret to be in boundary if it is before or after numeric value\n boundaryAry[i] = Boolean(charIsNumber(formattedValue[i]) || charIsNumber(formattedValue[i - 1]));\n }\n return boundaryAry;\n}\nfunction useInternalValues(value, defaultValue, valueIsNumericString, format, removeFormatting, onValueChange) {\n if ( onValueChange === void 0 ) onValueChange = noop;\n\n var getValues = usePersistentCallback(function (value, valueIsNumericString) {\n var formattedValue, numAsString;\n if (isNotValidValue(value)) {\n numAsString = '';\n formattedValue = '';\n }\n else if (typeof value === 'number' || valueIsNumericString) {\n numAsString = typeof value === 'number' ? toNumericString(value) : value;\n formattedValue = format(numAsString);\n }\n else {\n numAsString = removeFormatting(value, undefined);\n formattedValue = format(numAsString);\n }\n return { formattedValue: formattedValue, numAsString: numAsString };\n });\n var ref = useState(function () {\n return getValues(isNil(value) ? defaultValue : value, valueIsNumericString);\n });\n var values = ref[0];\n var setValues = ref[1];\n var _onValueChange = function (newValues, sourceInfo) {\n if (newValues.formattedValue !== values.formattedValue) {\n setValues({\n formattedValue: newValues.formattedValue,\n numAsString: newValues.value,\n });\n }\n // call parent on value change if only if formatted value is changed\n onValueChange(newValues, sourceInfo);\n };\n // if value is switch from controlled to uncontrolled, use the internal state's value to format with new props\n var _value = value;\n var _valueIsNumericString = valueIsNumericString;\n if (isNil(value)) {\n _value = values.numAsString;\n _valueIsNumericString = true;\n }\n var newValues = getValues(_value, _valueIsNumericString);\n useMemo(function () {\n setValues(newValues);\n }, [newValues.formattedValue]);\n return [values, _onValueChange];\n}\n\nfunction defaultRemoveFormatting(value) {\n return value.replace(/[^0-9]/g, '');\n}\nfunction defaultFormat(value) {\n return value;\n}\nfunction NumberFormatBase(props) {\n var type = props.type; if ( type === void 0 ) type = 'text';\n var displayType = props.displayType; if ( displayType === void 0 ) displayType = 'input';\n var customInput = props.customInput;\n var renderText = props.renderText;\n var getInputRef = props.getInputRef;\n var format = props.format; if ( format === void 0 ) format = defaultFormat;\n var removeFormatting = props.removeFormatting; if ( removeFormatting === void 0 ) removeFormatting = defaultRemoveFormatting;\n var defaultValue = props.defaultValue;\n var valueIsNumericString = props.valueIsNumericString;\n var onValueChange = props.onValueChange;\n var isAllowed = props.isAllowed;\n var onChange = props.onChange; if ( onChange === void 0 ) onChange = noop;\n var onKeyDown = props.onKeyDown; if ( onKeyDown === void 0 ) onKeyDown = noop;\n var onMouseUp = props.onMouseUp; if ( onMouseUp === void 0 ) onMouseUp = noop;\n var onFocus = props.onFocus; if ( onFocus === void 0 ) onFocus = noop;\n var onBlur = props.onBlur; if ( onBlur === void 0 ) onBlur = noop;\n var propValue = props.value;\n var getCaretBoundary = props.getCaretBoundary; if ( getCaretBoundary === void 0 ) getCaretBoundary = caretUnknownFormatBoundary;\n var isValidInputCharacter = props.isValidInputCharacter; if ( isValidInputCharacter === void 0 ) isValidInputCharacter = charIsNumber;\n var isCharacterSame = props.isCharacterSame;\n var otherProps = __rest(props, [\"type\", \"displayType\", \"customInput\", \"renderText\", \"getInputRef\", \"format\", \"removeFormatting\", \"defaultValue\", \"valueIsNumericString\", \"onValueChange\", \"isAllowed\", \"onChange\", \"onKeyDown\", \"onMouseUp\", \"onFocus\", \"onBlur\", \"value\", \"getCaretBoundary\", \"isValidInputCharacter\", \"isCharacterSame\"]);\n var ref = useInternalValues(propValue, defaultValue, Boolean(valueIsNumericString), format, removeFormatting, onValueChange);\n var ref_0 = ref[0];\n var formattedValue = ref_0.formattedValue;\n var numAsString = ref_0.numAsString;\n var onFormattedValueChange = ref[1];\n var caretPositionBeforeChange = useRef();\n var lastUpdatedValue = useRef({ formattedValue: formattedValue, numAsString: numAsString });\n var _onValueChange = function (values, source) {\n lastUpdatedValue.current = { formattedValue: values.formattedValue, numAsString: values.value };\n onFormattedValueChange(values, source);\n };\n var ref$1 = useState(false);\n var mounted = ref$1[0];\n var setMounted = ref$1[1];\n var focusedElm = useRef(null);\n var timeout = useRef({\n setCaretTimeout: null,\n focusTimeout: null,\n });\n useEffect(function () {\n setMounted(true);\n return function () {\n clearTimeout(timeout.current.setCaretTimeout);\n clearTimeout(timeout.current.focusTimeout);\n };\n }, []);\n var _format = format;\n var getValueObject = function (formattedValue, numAsString) {\n var floatValue = parseFloat(numAsString);\n return {\n formattedValue: formattedValue,\n value: numAsString,\n floatValue: isNaN(floatValue) ? undefined : floatValue,\n };\n };\n var setPatchedCaretPosition = function (el, caretPos, currentValue) {\n // don't reset the caret position when the whole input content is selected\n if (el.selectionStart === 0 && el.selectionEnd === el.value.length)\n { return; }\n /* setting caret position within timeout of 0ms is required for mobile chrome,\n otherwise browser resets the caret position after we set it\n We are also setting it without timeout so that in normal browser we don't see the flickering */\n setCaretPosition(el, caretPos);\n timeout.current.setCaretTimeout = setTimeout(function () {\n if (el.value === currentValue && el.selectionStart !== caretPos) {\n setCaretPosition(el, caretPos);\n }\n }, 0);\n };\n /* This keeps the caret within typing area so people can't type in between prefix or suffix */\n var correctCaretPosition = function (value, caretPos, direction) {\n return getCaretPosInBoundary(value, caretPos, getCaretBoundary(value), direction);\n };\n var getNewCaretPosition = function (inputValue, newFormattedValue, caretPos) {\n var caretBoundary = getCaretBoundary(newFormattedValue);\n var updatedCaretPos = getCaretPosition(newFormattedValue, formattedValue, inputValue, caretPos, caretBoundary, isValidInputCharacter, isCharacterSame);\n //correct caret position if its outside of editable area\n updatedCaretPos = getCaretPosInBoundary(newFormattedValue, updatedCaretPos, caretBoundary);\n return updatedCaretPos;\n };\n var updateValueAndCaretPosition = function (params) {\n var newFormattedValue = params.formattedValue; if ( newFormattedValue === void 0 ) newFormattedValue = '';\n var input = params.input;\n var source = params.source;\n var event = params.event;\n var numAsString = params.numAsString;\n var caretPos;\n if (input) {\n var inputValue = params.inputValue || input.value;\n var currentCaretPosition = geInputCaretPosition(input);\n /**\n * set the value imperatively, this is required for IE fix\n * This is also required as if new caret position is beyond the previous value.\n * Caret position will not be set correctly\n */\n input.value = newFormattedValue;\n //get the caret position\n caretPos = getNewCaretPosition(inputValue, newFormattedValue, currentCaretPosition);\n //set caret position imperatively\n if (caretPos !== undefined) {\n setPatchedCaretPosition(input, caretPos, newFormattedValue);\n }\n }\n if (newFormattedValue !== formattedValue) {\n // trigger onValueChange synchronously, so parent is updated along with the number format. Fix for #277, #287\n _onValueChange(getValueObject(newFormattedValue, numAsString), { event: event, source: source });\n }\n };\n /**\n * if the formatted value is not synced to parent, or if the formatted value is different from last synced value sync it\n * if the formatting props is removed, in which case last formatted value will be different from the numeric string value\n * in such case we need to inform the parent.\n */\n useEffect(function () {\n var ref = lastUpdatedValue.current;\n var lastFormattedValue = ref.formattedValue;\n var lastNumAsString = ref.numAsString;\n if (formattedValue !== lastFormattedValue || numAsString !== lastNumAsString) {\n _onValueChange(getValueObject(formattedValue, numAsString), {\n event: undefined,\n source: SourceType.props,\n });\n }\n }, [formattedValue, numAsString]);\n // also if formatted value is changed from the props, we need to update the caret position\n // keep the last caret position if element is focused\n var currentCaretPosition = focusedElm.current\n ? geInputCaretPosition(focusedElm.current)\n : undefined;\n // needed to prevent warning with useLayoutEffect on server\n var useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;\n useIsomorphicLayoutEffect(function () {\n var input = focusedElm.current;\n if (formattedValue !== lastUpdatedValue.current.formattedValue && input) {\n var caretPos = getNewCaretPosition(lastUpdatedValue.current.formattedValue, formattedValue, currentCaretPosition);\n /**\n * set the value imperatively, as we set the caret position as well imperatively.\n * This is to keep value and caret position in sync\n */\n input.value = formattedValue;\n setPatchedCaretPosition(input, caretPos, formattedValue);\n }\n }, [formattedValue]);\n var formatInputValue = function (inputValue, event, source) {\n var input = event.target;\n var changeRange = caretPositionBeforeChange.current\n ? findChangedRangeFromCaretPositions(caretPositionBeforeChange.current, input.selectionEnd)\n : findChangeRange(formattedValue, inputValue);\n var changeMeta = Object.assign(Object.assign({}, changeRange), { lastValue: formattedValue });\n var _numAsString = removeFormatting(inputValue, changeMeta);\n var _formattedValue = _format(_numAsString);\n // formatting can remove some of the number chars, so we need to fine number string again\n _numAsString = removeFormatting(_formattedValue, undefined);\n if (isAllowed && !isAllowed(getValueObject(_formattedValue, _numAsString))) {\n //reset the caret position\n var input$1 = event.target;\n var currentCaretPosition = geInputCaretPosition(input$1);\n var caretPos = getNewCaretPosition(inputValue, formattedValue, currentCaretPosition);\n input$1.value = formattedValue;\n setPatchedCaretPosition(input$1, caretPos, formattedValue);\n return false;\n }\n updateValueAndCaretPosition({\n formattedValue: _formattedValue,\n numAsString: _numAsString,\n inputValue: inputValue,\n event: event,\n source: source,\n input: event.target,\n });\n return true;\n };\n var setCaretPositionInfoBeforeChange = function (el, endOffset) {\n if ( endOffset === void 0 ) endOffset = 0;\n\n var selectionStart = el.selectionStart;\n var selectionEnd = el.selectionEnd;\n caretPositionBeforeChange.current = { selectionStart: selectionStart, selectionEnd: selectionEnd + endOffset };\n };\n var _onChange = function (e) {\n var el = e.target;\n var inputValue = el.value;\n var changed = formatInputValue(inputValue, e, SourceType.event);\n if (changed)\n { onChange(e); }\n // reset the position, as we have already handled the caret position\n caretPositionBeforeChange.current = undefined;\n };\n var _onKeyDown = function (e) {\n var el = e.target;\n var key = e.key;\n var selectionStart = el.selectionStart;\n var selectionEnd = el.selectionEnd;\n var value = el.value; if ( value === void 0 ) value = '';\n var expectedCaretPosition;\n //Handle backspace and delete against non numerical/decimal characters or arrow keys\n if (key === 'ArrowLeft' || key === 'Backspace') {\n expectedCaretPosition = Math.max(selectionStart - 1, 0);\n }\n else if (key === 'ArrowRight') {\n expectedCaretPosition = Math.min(selectionStart + 1, value.length);\n }\n else if (key === 'Delete') {\n expectedCaretPosition = selectionStart;\n }\n // if key is delete and text is not selected keep the end offset to 1, as it deletes one character\n // this is required as selection is not changed on delete case, which changes the change range calculation\n var endOffset = 0;\n if (key === 'Delete' && selectionStart === selectionEnd) {\n endOffset = 1;\n }\n var isArrowKey = key === 'ArrowLeft' || key === 'ArrowRight';\n //if expectedCaretPosition is not set it means we don't want to Handle keyDown\n // also if multiple characters are selected don't handle\n if (expectedCaretPosition === undefined || (selectionStart !== selectionEnd && !isArrowKey)) {\n onKeyDown(e);\n // keep information of what was the caret position before keyDown\n // set it after onKeyDown, in case parent updates the position manually\n setCaretPositionInfoBeforeChange(el, endOffset);\n return;\n }\n var newCaretPosition = expectedCaretPosition;\n if (isArrowKey) {\n var direction = key === 'ArrowLeft' ? 'left' : 'right';\n newCaretPosition = correctCaretPosition(value, expectedCaretPosition, direction);\n // arrow left or right only moves the caret, so no need to handle the event, if we are handling it manually\n if (newCaretPosition !== expectedCaretPosition) {\n e.preventDefault();\n }\n }\n else if (key === 'Delete' && !isValidInputCharacter(value[expectedCaretPosition])) {\n // in case of delete go to closest caret boundary on the right side\n newCaretPosition = correctCaretPosition(value, expectedCaretPosition, 'right');\n }\n else if (key === 'Backspace' && !isValidInputCharacter(value[expectedCaretPosition])) {\n // in case of backspace go to closest caret boundary on the left side\n newCaretPosition = correctCaretPosition(value, expectedCaretPosition, 'left');\n }\n if (newCaretPosition !== expectedCaretPosition) {\n setPatchedCaretPosition(el, newCaretPosition, value);\n }\n onKeyDown(e);\n setCaretPositionInfoBeforeChange(el, endOffset);\n };\n /** required to handle the caret position when click anywhere within the input **/\n var _onMouseUp = function (e) {\n var el = e.target;\n /**\n * NOTE: we have to give default value for value as in case when custom input is provided\n * value can come as undefined when nothing is provided on value prop.\n */\n var correctCaretPositionIfRequired = function () {\n var selectionStart = el.selectionStart;\n var selectionEnd = el.selectionEnd;\n var value = el.value; if ( value === void 0 ) value = '';\n if (selectionStart === selectionEnd) {\n var caretPosition = correctCaretPosition(value, selectionStart);\n if (caretPosition !== selectionStart) {\n setPatchedCaretPosition(el, caretPosition, value);\n }\n }\n };\n correctCaretPositionIfRequired();\n // try to correct after selection has updated by browser\n // this case is required when user clicks on some position while a text is selected on input\n requestAnimationFrame(function () {\n correctCaretPositionIfRequired();\n });\n onMouseUp(e);\n setCaretPositionInfoBeforeChange(el);\n };\n var _onFocus = function (e) {\n // Workaround Chrome and Safari bug https://bugs.chromium.org/p/chromium/issues/detail?id=779328\n // (onFocus event target selectionStart is always 0 before setTimeout)\n if (e.persist)\n { e.persist(); }\n var el = e.target;\n var currentTarget = e.currentTarget;\n focusedElm.current = el;\n timeout.current.focusTimeout = setTimeout(function () {\n var selectionStart = el.selectionStart;\n var selectionEnd = el.selectionEnd;\n var value = el.value; if ( value === void 0 ) value = '';\n var caretPosition = correctCaretPosition(value, selectionStart);\n //setPatchedCaretPosition only when everything is not selected on focus (while tabbing into the field)\n if (caretPosition !== selectionStart &&\n !(selectionStart === 0 && selectionEnd === value.length)) {\n setPatchedCaretPosition(el, caretPosition, value);\n }\n onFocus(Object.assign(Object.assign({}, e), { currentTarget: currentTarget }));\n }, 0);\n };\n var _onBlur = function (e) {\n focusedElm.current = null;\n clearTimeout(timeout.current.focusTimeout);\n clearTimeout(timeout.current.setCaretTimeout);\n onBlur(e);\n };\n // add input mode on element based on format prop and device once the component is mounted\n var inputMode = mounted && addInputMode() ? 'numeric' : undefined;\n var inputProps = Object.assign({ inputMode: inputMode }, otherProps, {\n type: type,\n value: formattedValue,\n onChange: _onChange,\n onKeyDown: _onKeyDown,\n onMouseUp: _onMouseUp,\n onFocus: _onFocus,\n onBlur: _onBlur,\n });\n if (displayType === 'text') {\n return renderText ? (React.createElement(React.Fragment, null, renderText(formattedValue, otherProps) || null)) : (React.createElement(\"span\", Object.assign({}, otherProps, { ref: getInputRef }), formattedValue));\n }\n else if (customInput) {\n var CustomInput = customInput;\n /* @ts-ignore */\n return React.createElement(CustomInput, Object.assign({}, inputProps, { ref: getInputRef }));\n }\n return React.createElement(\"input\", Object.assign({}, inputProps, { ref: getInputRef }));\n}\n\nfunction format(numStr, props) {\n var decimalScale = props.decimalScale;\n var fixedDecimalScale = props.fixedDecimalScale;\n var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';\n var suffix = props.suffix; if ( suffix === void 0 ) suffix = '';\n var allowNegative = props.allowNegative;\n var thousandsGroupStyle = props.thousandsGroupStyle; if ( thousandsGroupStyle === void 0 ) thousandsGroupStyle = 'thousand';\n // don't apply formatting on empty string or '-'\n if (numStr === '' || numStr === '-') {\n return numStr;\n }\n var ref = getSeparators(props);\n var thousandSeparator = ref.thousandSeparator;\n var decimalSeparator = ref.decimalSeparator;\n /**\n * Keep the decimal separator\n * when decimalScale is not defined or non zero and the numStr has decimal in it\n * Or if decimalScale is > 0 and fixeDecimalScale is true (even if numStr has no decimal)\n */\n var hasDecimalSeparator = (decimalScale !== 0 && numStr.indexOf('.') !== -1) || (decimalScale && fixedDecimalScale);\n var ref$1 = splitDecimal(numStr, allowNegative);\n var beforeDecimal = ref$1.beforeDecimal;\n var afterDecimal = ref$1.afterDecimal;\n var addNegation = ref$1.addNegation; // eslint-disable-line prefer-const\n //apply decimal precision if its defined\n if (decimalScale !== undefined) {\n afterDecimal = limitToScale(afterDecimal, decimalScale, !!fixedDecimalScale);\n }\n if (thousandSeparator) {\n beforeDecimal = applyThousandSeparator(beforeDecimal, thousandSeparator, thousandsGroupStyle);\n }\n //add prefix and suffix when there is a number present\n if (prefix)\n { beforeDecimal = prefix + beforeDecimal; }\n if (suffix)\n { afterDecimal = afterDecimal + suffix; }\n //restore negation sign\n if (addNegation)\n { beforeDecimal = '-' + beforeDecimal; }\n numStr = beforeDecimal + ((hasDecimalSeparator && decimalSeparator) || '') + afterDecimal;\n return numStr;\n}\nfunction getSeparators(props) {\n var decimalSeparator = props.decimalSeparator; if ( decimalSeparator === void 0 ) decimalSeparator = '.';\n var thousandSeparator = props.thousandSeparator;\n var allowedDecimalSeparators = props.allowedDecimalSeparators;\n if (thousandSeparator === true) {\n thousandSeparator = ',';\n }\n if (!allowedDecimalSeparators) {\n allowedDecimalSeparators = [decimalSeparator, '.'];\n }\n return {\n decimalSeparator: decimalSeparator,\n thousandSeparator: thousandSeparator,\n allowedDecimalSeparators: allowedDecimalSeparators,\n };\n}\nfunction handleNegation(value, allowNegative) {\n if ( value === void 0 ) value = '';\n\n var negationRegex = new RegExp('(-)');\n var doubleNegationRegex = new RegExp('(-)(.)*(-)');\n // Check number has '-' value\n var hasNegation = negationRegex.test(value);\n // Check number has 2 or more '-' values\n var removeNegation = doubleNegationRegex.test(value);\n //remove negation\n value = value.replace(/-/g, '');\n if (hasNegation && !removeNegation && allowNegative) {\n value = '-' + value;\n }\n return value;\n}\nfunction getNumberRegex(decimalSeparator, global) {\n return new RegExp((\"(^-)|[0-9]|\" + (escapeRegExp(decimalSeparator))), global ? 'g' : undefined);\n}\nfunction isNumericString(val, prefix, suffix) {\n // for empty value we can always treat it as numeric string\n if (val === '')\n { return true; }\n return (!(prefix === null || prefix === void 0 ? void 0 : prefix.match(/\\d/)) && !(suffix === null || suffix === void 0 ? void 0 : suffix.match(/\\d/)) && typeof val === 'string' && !isNaN(Number(val)));\n}\nfunction removeFormatting(value, changeMeta, props) {\n var assign;\n\n if ( changeMeta === void 0 ) changeMeta = getDefaultChangeMeta(value);\n var allowNegative = props.allowNegative;\n var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';\n var suffix = props.suffix; if ( suffix === void 0 ) suffix = '';\n var decimalScale = props.decimalScale;\n var from = changeMeta.from;\n var to = changeMeta.to;\n var start = to.start;\n var end = to.end;\n var ref = getSeparators(props);\n var allowedDecimalSeparators = ref.allowedDecimalSeparators;\n var decimalSeparator = ref.decimalSeparator;\n var isBeforeDecimalSeparator = value[end] === decimalSeparator;\n /**\n * If only a number is added on empty input which matches with the prefix or suffix,\n * then don't remove it, just return the same\n */\n if (charIsNumber(value) &&\n (value === prefix || value === suffix) &&\n changeMeta.lastValue === '') {\n return value;\n }\n /** Check for any allowed decimal separator is added in the numeric format and replace it with decimal separator */\n if (end - start === 1 && allowedDecimalSeparators.indexOf(value[start]) !== -1) {\n var separator = decimalScale === 0 ? '' : decimalSeparator;\n value = value.substring(0, start) + separator + value.substring(start + 1, value.length);\n }\n var stripNegation = function (value, start, end) {\n /**\n * if prefix starts with - we don't allow negative number to avoid confusion\n * if suffix starts with - and the value length is same as suffix length, then the - sign is from the suffix\n * In other cases, if the value starts with - then it is a negation\n */\n var hasNegation = false;\n var hasDoubleNegation = false;\n if (prefix.startsWith('-')) {\n hasNegation = false;\n }\n else if (value.startsWith('--')) {\n hasNegation = false;\n hasDoubleNegation = true;\n }\n else if (suffix.startsWith('-') && value.length === suffix.length) {\n hasNegation = false;\n }\n else if (value[0] === '-') {\n hasNegation = true;\n }\n var charsToRemove = hasNegation ? 1 : 0;\n if (hasDoubleNegation)\n { charsToRemove = 2; }\n // remove negation/double negation from start to simplify prefix logic as negation comes before prefix\n if (charsToRemove) {\n value = value.substring(charsToRemove);\n // account for the removal of the negation for start and end index\n start -= charsToRemove;\n end -= charsToRemove;\n }\n return { value: value, start: start, end: end, hasNegation: hasNegation };\n };\n var toMetadata = stripNegation(value, start, end);\n var hasNegation = toMetadata.hasNegation;\n ((assign = toMetadata, value = assign.value, start = assign.start, end = assign.end));\n var ref$1 = stripNegation(changeMeta.lastValue, from.start, from.end);\n var fromStart = ref$1.start;\n var fromEnd = ref$1.end;\n var lastValue = ref$1.value;\n // if only prefix and suffix part is updated reset the value to last value\n // if the changed range is from suffix in the updated value, and the the suffix starts with the same characters, allow the change\n var updatedSuffixPart = value.substring(start, end);\n if (value.length &&\n lastValue.length &&\n (fromStart > lastValue.length - suffix.length || fromEnd < prefix.length) &&\n !(updatedSuffixPart && suffix.startsWith(updatedSuffixPart))) {\n value = lastValue;\n }\n /**\n * remove prefix\n * Remove whole prefix part if its present on the value\n * If the prefix is partially deleted (in which case change start index will be less the prefix length)\n * Remove only partial part of prefix.\n */\n var startIndex = 0;\n if (value.startsWith(prefix))\n { startIndex += prefix.length; }\n else if (start < prefix.length)\n { startIndex = start; }\n value = value.substring(startIndex);\n // account for deleted prefix for end\n end -= startIndex;\n /**\n * Remove suffix\n * Remove whole suffix part if its present on the value\n * If the suffix is partially deleted (in which case change end index will be greater than the suffixStartIndex)\n * remove the partial part of suffix\n */\n var endIndex = value.length;\n var suffixStartIndex = value.length - suffix.length;\n if (value.endsWith(suffix))\n { endIndex = suffixStartIndex; }\n // if the suffix is removed from the end\n else if (end > suffixStartIndex)\n { endIndex = end; }\n // if the suffix is removed from start\n else if (end > value.length - suffix.length)\n { endIndex = end; }\n value = value.substring(0, endIndex);\n // add the negation back and handle for double negation\n value = handleNegation(hasNegation ? (\"-\" + value) : value, allowNegative);\n // remove non numeric characters\n value = (value.match(getNumberRegex(decimalSeparator, true)) || []).join('');\n // replace the decimalSeparator with ., and only keep the first separator, ignore following ones\n var firstIndex = value.indexOf(decimalSeparator);\n value = value.replace(new RegExp(escapeRegExp(decimalSeparator), 'g'), function (match, index) {\n return index === firstIndex ? '.' : '';\n });\n //check if beforeDecimal got deleted and there is nothing after decimal,\n //clear all numbers in such case while keeping the - sign\n var ref$2 = splitDecimal(value, allowNegative);\n var beforeDecimal = ref$2.beforeDecimal;\n var afterDecimal = ref$2.afterDecimal;\n var addNegation = ref$2.addNegation; // eslint-disable-line prefer-const\n //clear only if something got deleted before decimal (cursor is before decimal)\n if (to.end - to.start < from.end - from.start &&\n beforeDecimal === '' &&\n isBeforeDecimalSeparator &&\n !parseFloat(afterDecimal)) {\n value = addNegation ? '-' : '';\n }\n return value;\n}\nfunction getCaretBoundary(formattedValue, props) {\n var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';\n var suffix = props.suffix; if ( suffix === void 0 ) suffix = '';\n var boundaryAry = Array.from({ length: formattedValue.length + 1 }).map(function () { return true; });\n var hasNegation = formattedValue[0] === '-';\n // fill for prefix and negation\n boundaryAry.fill(false, 0, prefix.length + (hasNegation ? 1 : 0));\n // fill for suffix\n var valLn = formattedValue.length;\n boundaryAry.fill(false, valLn - suffix.length + 1, valLn + 1);\n return boundaryAry;\n}\nfunction validateAndUpdateProps(props) {\n var ref = getSeparators(props);\n var thousandSeparator = ref.thousandSeparator;\n var decimalSeparator = ref.decimalSeparator;\n // eslint-disable-next-line prefer-const\n var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';\n var allowNegative = props.allowNegative; if ( allowNegative === void 0 ) allowNegative = true;\n if (thousandSeparator === decimalSeparator) {\n throw new Error((\"\\n Decimal separator can't be same as thousand separator.\\n thousandSeparator: \" + thousandSeparator + \" (thousandSeparator = {true} is same as thousandSeparator = \\\",\\\")\\n decimalSeparator: \" + decimalSeparator + \" (default value for decimalSeparator is .)\\n \"));\n }\n if (prefix.startsWith('-') && allowNegative) {\n // TODO: throw error in next major version\n console.error((\"\\n Prefix can't start with '-' when allowNegative is true.\\n prefix: \" + prefix + \"\\n allowNegative: \" + allowNegative + \"\\n \"));\n allowNegative = false;\n }\n return Object.assign(Object.assign({}, props), { allowNegative: allowNegative });\n}\nfunction useNumericFormat(props) {\n // validate props\n props = validateAndUpdateProps(props);\n var _decimalSeparator = props.decimalSeparator;\n var _allowedDecimalSeparators = props.allowedDecimalSeparators;\n var thousandsGroupStyle = props.thousandsGroupStyle;\n var suffix = props.suffix;\n var allowNegative = props.allowNegative;\n var allowLeadingZeros = props.allowLeadingZeros;\n var onKeyDown = props.onKeyDown; if ( onKeyDown === void 0 ) onKeyDown = noop;\n var onBlur = props.onBlur; if ( onBlur === void 0 ) onBlur = noop;\n var thousandSeparator = props.thousandSeparator;\n var decimalScale = props.decimalScale;\n var fixedDecimalScale = props.fixedDecimalScale;\n var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';\n var defaultValue = props.defaultValue;\n var value = props.value;\n var valueIsNumericString = props.valueIsNumericString;\n var onValueChange = props.onValueChange;\n var restProps = __rest(props, [\"decimalSeparator\", \"allowedDecimalSeparators\", \"thousandsGroupStyle\", \"suffix\", \"allowNegative\", \"allowLeadingZeros\", \"onKeyDown\", \"onBlur\", \"thousandSeparator\", \"decimalScale\", \"fixedDecimalScale\", \"prefix\", \"defaultValue\", \"value\", \"valueIsNumericString\", \"onValueChange\"]);\n // get derived decimalSeparator and allowedDecimalSeparators\n var ref = getSeparators(props);\n var decimalSeparator = ref.decimalSeparator;\n var allowedDecimalSeparators = ref.allowedDecimalSeparators;\n var _format = function (numStr) { return format(numStr, props); };\n var _removeFormatting = function (inputValue, changeMeta) { return removeFormatting(inputValue, changeMeta, props); };\n var _value = isNil(value) ? defaultValue : value;\n // try to figure out isValueNumericString based on format prop and value\n var _valueIsNumericString = valueIsNumericString !== null && valueIsNumericString !== void 0 ? valueIsNumericString : isNumericString(_value, prefix, suffix);\n if (!isNil(value)) {\n _valueIsNumericString = _valueIsNumericString || typeof value === 'number';\n }\n else if (!isNil(defaultValue)) {\n _valueIsNumericString = _valueIsNumericString || typeof defaultValue === 'number';\n }\n var roundIncomingValueToPrecision = function (value) {\n if (isNotValidValue(value))\n { return value; }\n if (typeof value === 'number') {\n value = toNumericString(value);\n }\n /**\n * only round numeric or float string values coming through props,\n * we don't need to do it for onChange events, as we want to prevent typing there\n */\n if (_valueIsNumericString && typeof decimalScale === 'number') {\n return roundToPrecision(value, decimalScale, Boolean(fixedDecimalScale));\n }\n return value;\n };\n var ref$1 = useInternalValues(roundIncomingValueToPrecision(value), roundIncomingValueToPrecision(defaultValue), Boolean(_valueIsNumericString), _format, _removeFormatting, onValueChange);\n var ref$1_0 = ref$1[0];\n var numAsString = ref$1_0.numAsString;\n var formattedValue = ref$1_0.formattedValue;\n var _onValueChange = ref$1[1];\n var _onKeyDown = function (e) {\n var el = e.target;\n var key = e.key;\n var selectionStart = el.selectionStart;\n var selectionEnd = el.selectionEnd;\n var value = el.value; if ( value === void 0 ) value = '';\n // if user tries to delete partial prefix then ignore it\n if ((key === 'Backspace' || key === 'Delete') && selectionEnd < prefix.length) {\n e.preventDefault();\n return;\n }\n // if multiple characters are selected and user hits backspace, no need to handle anything manually\n if (selectionStart !== selectionEnd) {\n onKeyDown(e);\n return;\n }\n // if user hits backspace, while the cursor is before prefix, and the input has negation, remove the negation\n if (key === 'Backspace' &&\n value[0] === '-' &&\n selectionStart === prefix.length + 1 &&\n allowNegative) {\n // bring the cursor to after negation\n setCaretPosition(el, 1);\n }\n // don't allow user to delete decimal separator when decimalScale and fixedDecimalScale is set\n if (decimalScale && fixedDecimalScale) {\n if (key === 'Backspace' && value[selectionStart - 1] === decimalSeparator) {\n setCaretPosition(el, selectionStart - 1);\n e.preventDefault();\n }\n else if (key === 'Delete' && value[selectionStart] === decimalSeparator) {\n e.preventDefault();\n }\n }\n // if user presses the allowed decimal separator before the separator, move the cursor after the separator\n if ((allowedDecimalSeparators === null || allowedDecimalSeparators === void 0 ? void 0 : allowedDecimalSeparators.includes(key)) && value[selectionStart] === decimalSeparator) {\n setCaretPosition(el, selectionStart + 1);\n }\n var _thousandSeparator = thousandSeparator === true ? ',' : thousandSeparator;\n // move cursor when delete or backspace is pressed before/after thousand separator\n if (key === 'Backspace' && value[selectionStart - 1] === _thousandSeparator) {\n setCaretPosition(el, selectionStart - 1);\n }\n if (key === 'Delete' && value[selectionStart] === _thousandSeparator) {\n setCaretPosition(el, selectionStart + 1);\n }\n onKeyDown(e);\n };\n var _onBlur = function (e) {\n var _value = numAsString;\n // if there no no numeric value, clear the input\n if (!_value.match(/\\d/g)) {\n _value = '';\n }\n // clear leading 0s\n if (!allowLeadingZeros) {\n _value = fixLeadingZero(_value);\n }\n // apply fixedDecimalScale on blur event\n if (fixedDecimalScale && decimalScale) {\n _value = roundToPrecision(_value, decimalScale, fixedDecimalScale);\n }\n if (_value !== numAsString) {\n var formattedValue = format(_value, props);\n _onValueChange({\n formattedValue: formattedValue,\n value: _value,\n floatValue: parseFloat(_value),\n }, {\n event: e,\n source: SourceType.event,\n });\n }\n onBlur(e);\n };\n var isValidInputCharacter = function (inputChar) {\n if (inputChar === decimalSeparator)\n { return true; }\n return charIsNumber(inputChar);\n };\n var isCharacterSame = function (ref) {\n var currentValue = ref.currentValue;\n var lastValue = ref.lastValue;\n var formattedValue = ref.formattedValue;\n var currentValueIndex = ref.currentValueIndex;\n var formattedValueIndex = ref.formattedValueIndex;\n\n var curChar = currentValue[currentValueIndex];\n var newChar = formattedValue[formattedValueIndex];\n /**\n * NOTE: as thousand separator and allowedDecimalSeparators can be same, we need to check on\n * typed range if we have typed any character from allowedDecimalSeparators, in that case we\n * consider different characters like , and . same within the range of updated value.\n */\n var typedRange = findChangeRange(lastValue, currentValue);\n var to = typedRange.to;\n // handle corner case where if we user types a decimal separator with fixedDecimalScale\n // and pass back float value the cursor jumps. #851\n var getDecimalSeparatorIndex = function (value) {\n return _removeFormatting(value).indexOf('.') + prefix.length;\n };\n if (value === 0 &&\n fixedDecimalScale &&\n decimalScale &&\n currentValue[to.start] === decimalSeparator &&\n getDecimalSeparatorIndex(currentValue) < currentValueIndex &&\n getDecimalSeparatorIndex(formattedValue) > formattedValueIndex) {\n return false;\n }\n if (currentValueIndex >= to.start &&\n currentValueIndex < to.end &&\n allowedDecimalSeparators &&\n allowedDecimalSeparators.includes(curChar) &&\n newChar === decimalSeparator) {\n return true;\n }\n return curChar === newChar;\n };\n return Object.assign(Object.assign({}, restProps), { value: formattedValue, valueIsNumericString: false, isValidInputCharacter: isValidInputCharacter,\n isCharacterSame: isCharacterSame, onValueChange: _onValueChange, format: _format, removeFormatting: _removeFormatting, getCaretBoundary: function (formattedValue) { return getCaretBoundary(formattedValue, props); }, onKeyDown: _onKeyDown, onBlur: _onBlur });\n}\nfunction NumericFormat(props) {\n var numericFormatProps = useNumericFormat(props);\n return React.createElement(NumberFormatBase, Object.assign({}, numericFormatProps));\n}\n\nfunction format$1(numStr, props) {\n var format = props.format;\n var allowEmptyFormatting = props.allowEmptyFormatting;\n var mask = props.mask;\n var patternChar = props.patternChar; if ( patternChar === void 0 ) patternChar = '#';\n if (numStr === '' && !allowEmptyFormatting)\n { return ''; }\n var hashCount = 0;\n var formattedNumberAry = format.split('');\n for (var i = 0, ln = format.length; i < ln; i++) {\n if (format[i] === patternChar) {\n formattedNumberAry[i] = numStr[hashCount] || getMaskAtIndex(mask, hashCount);\n hashCount += 1;\n }\n }\n return formattedNumberAry.join('');\n}\nfunction removeFormatting$1(value, changeMeta, props) {\n if ( changeMeta === void 0 ) changeMeta = getDefaultChangeMeta(value);\n\n var format = props.format;\n var patternChar = props.patternChar; if ( patternChar === void 0 ) patternChar = '#';\n var from = changeMeta.from;\n var to = changeMeta.to;\n var lastValue = changeMeta.lastValue; if ( lastValue === void 0 ) lastValue = '';\n var isNumericSlot = function (caretPos) { return format[caretPos] === patternChar; };\n var removeFormatChar = function (string, startIndex) {\n var str = '';\n for (var i = 0; i < string.length; i++) {\n if (isNumericSlot(startIndex + i) && charIsNumber(string[i])) {\n str += string[i];\n }\n }\n return str;\n };\n var extractNumbers = function (str) { return str.replace(/[^0-9]/g, ''); };\n // if format doesn't have any number, remove all the non numeric characters\n if (!format.match(/\\d/)) {\n return extractNumbers(value);\n }\n /**\n * if user paste the whole formatted text in an empty input or doing select all and paste, check if matches to the pattern\n * and remove the format characters, if there is a mismatch on the pattern, do plane number extract\n */\n if ((lastValue === '' || from.end - from.start === lastValue.length) &&\n value.length === format.length) {\n var str = '';\n for (var i = 0; i < value.length; i++) {\n if (isNumericSlot(i)) {\n if (charIsNumber(value[i])) {\n str += value[i];\n }\n }\n else if (value[i] !== format[i]) {\n // if there is a mismatch on the pattern, do plane number extract\n return extractNumbers(value);\n }\n }\n return str;\n }\n /**\n * For partial change,\n * where ever there is a change on the input, we can break the number in three parts\n * 1st: left part which is unchanged\n * 2nd: middle part which is changed\n * 3rd: right part which is unchanged\n *\n * The first and third section will be same as last value, only the middle part will change\n * We can consider on the change part all the new characters are non format characters.\n * And on the first and last section it can have partial format characters.\n *\n * We pick first and last section from the lastValue (as that has 1-1 mapping with format)\n * and middle one from the update value.\n */\n var firstSection = lastValue.substring(0, from.start);\n var middleSection = value.substring(to.start, to.end);\n var lastSection = lastValue.substring(from.end);\n return (\"\" + (removeFormatChar(firstSection, 0)) + (extractNumbers(middleSection)) + (removeFormatChar(lastSection, from.end)));\n}\nfunction getCaretBoundary$1(formattedValue, props) {\n var format = props.format;\n var mask = props.mask;\n var patternChar = props.patternChar; if ( patternChar === void 0 ) patternChar = '#';\n var boundaryAry = Array.from({ length: formattedValue.length + 1 }).map(function () { return true; });\n var hashCount = 0;\n var firstEmptySlot = -1;\n var maskAndIndexMap = {};\n format.split('').forEach(function (char, index) {\n var maskAtIndex = undefined;\n if (char === patternChar) {\n hashCount++;\n maskAtIndex = getMaskAtIndex(mask, hashCount - 1);\n if (firstEmptySlot === -1 && formattedValue[index] === maskAtIndex) {\n firstEmptySlot = index;\n }\n }\n maskAndIndexMap[index] = maskAtIndex;\n });\n var isPosAllowed = function (pos) {\n // the position is allowed if the position is not masked and valid number area\n return format[pos] === patternChar && formattedValue[pos] !== maskAndIndexMap[pos];\n };\n for (var i = 0, ln = boundaryAry.length; i < ln; i++) {\n // consider caret to be in boundary if it is before or after numeric value\n // Note: on pattern based format its denoted by patternCharacter\n // we should also allow user to put cursor on first empty slot\n boundaryAry[i] = i === firstEmptySlot || isPosAllowed(i) || isPosAllowed(i - 1);\n }\n // the first patternChar position is always allowed\n boundaryAry[format.indexOf(patternChar)] = true;\n return boundaryAry;\n}\nfunction validateProps(props) {\n var mask = props.mask;\n if (mask) {\n var maskAsStr = mask === 'string' ? mask : mask.toString();\n if (maskAsStr.match(/\\d/g)) {\n throw new Error((\"Mask \" + mask + \" should not contain numeric character;\"));\n }\n }\n}\nfunction isNumericString$1(val, format) {\n //we can treat empty string as numeric string\n if (val === '')\n { return true; }\n return !(format === null || format === void 0 ? void 0 : format.match(/\\d/)) && typeof val === 'string' && (!!val.match(/^\\d+$/) || val === '');\n}\nfunction usePatternFormat(props) {\n var mask = props.mask;\n var allowEmptyFormatting = props.allowEmptyFormatting;\n var formatProp = props.format;\n var inputMode = props.inputMode; if ( inputMode === void 0 ) inputMode = 'numeric';\n var onKeyDown = props.onKeyDown; if ( onKeyDown === void 0 ) onKeyDown = noop;\n var patternChar = props.patternChar; if ( patternChar === void 0 ) patternChar = '#';\n var value = props.value;\n var defaultValue = props.defaultValue;\n var valueIsNumericString = props.valueIsNumericString;\n var restProps = __rest(props, [\"mask\", \"allowEmptyFormatting\", \"format\", \"inputMode\", \"onKeyDown\", \"patternChar\", \"value\", \"defaultValue\", \"valueIsNumericString\"]);\n // validate props\n validateProps(props);\n var _getCaretBoundary = function (formattedValue) {\n return getCaretBoundary$1(formattedValue, props);\n };\n var _onKeyDown = function (e) {\n var key = e.key;\n var el = e.target;\n var selectionStart = el.selectionStart;\n var selectionEnd = el.selectionEnd;\n var value = el.value;\n // if multiple characters are selected and user hits backspace, no need to handle anything manually\n if (selectionStart !== selectionEnd) {\n onKeyDown(e);\n return;\n }\n // bring the cursor to closest numeric section\n var caretPos = selectionStart;\n // if backspace is pressed after the format characters, bring it to numeric section\n // if delete is pressed before the format characters, bring it to numeric section\n if (key === 'Backspace' || key === 'Delete') {\n var direction = 'right';\n if (key === 'Backspace') {\n while (caretPos > 0 && formatProp[caretPos - 1] !== patternChar) {\n caretPos--;\n }\n direction = 'left';\n }\n else {\n var formatLn = formatProp.length;\n while (caretPos < formatLn && formatProp[caretPos] !== patternChar) {\n caretPos++;\n }\n direction = 'right';\n }\n caretPos = getCaretPosInBoundary(value, caretPos, _getCaretBoundary(value), direction);\n }\n else if (formatProp[caretPos] !== patternChar &&\n key !== 'ArrowLeft' &&\n key !== 'ArrowRight') {\n // if user is typing on format character position, bring user to next allowed caret position\n caretPos = getCaretPosInBoundary(value, caretPos + 1, _getCaretBoundary(value), 'right');\n }\n // if we changing caret position, set the caret position\n if (caretPos !== selectionStart) {\n setCaretPosition(el, caretPos);\n }\n onKeyDown(e);\n };\n // try to figure out isValueNumericString based on format prop and value\n var _value = isNil(value) ? defaultValue : value;\n var isValueNumericString = valueIsNumericString !== null && valueIsNumericString !== void 0 ? valueIsNumericString : isNumericString$1(_value, formatProp);\n var _props = Object.assign(Object.assign({}, props), { valueIsNumericString: isValueNumericString });\n return Object.assign(Object.assign({}, restProps), { value: value,\n defaultValue: defaultValue, valueIsNumericString: isValueNumericString, inputMode: inputMode, format: function (numStr) { return format$1(numStr, _props); }, removeFormatting: function (inputValue, changeMeta) { return removeFormatting$1(inputValue, changeMeta, _props); }, getCaretBoundary: _getCaretBoundary, onKeyDown: _onKeyDown });\n}\nfunction PatternFormat(props) {\n var patternFormatProps = usePatternFormat(props);\n return React.createElement(NumberFormatBase, Object.assign({}, patternFormatProps));\n}\n\nexport { NumberFormatBase, NumericFormat, PatternFormat, getCaretBoundary as getNumericCaretBoundary, getCaretBoundary$1 as getPatternCaretBoundary, format as numericFormatter, format$1 as patternFormatter, removeFormatting as removeNumericFormat, removeFormatting$1 as removePatternFormat, useNumericFormat, usePatternFormat };\n","/**\n * Relay v16.2.0\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nmodule.exports = require('./lib/hooks.js');\n","/**\n * Relay v16.2.0\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nmodule.exports = require('./lib/index.js');\n","'use strict';\n\nfunction getComponentName(component) {\n return component.displayName || component.name || 'Component';\n}\nfunction getContainerName(Component) {\n return 'Relay(' + getComponentName(Component) + ')';\n}\nmodule.exports = {\n getComponentName: getComponentName,\n getContainerName: getContainerName\n};","'use strict';\n\nvar React = require('react');\nvar _require = require('relay-runtime'),\n createRelayContext = _require.__internal.createRelayContext;\nmodule.exports = createRelayContext(React);","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _objectSpread2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar _objectWithoutPropertiesLoose2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectWithoutPropertiesLoose\"));\nvar _assertThisInitialized2 = _interopRequireDefault(require(\"@babel/runtime/helpers/assertThisInitialized\"));\nvar _inheritsLoose2 = _interopRequireDefault(require(\"@babel/runtime/helpers/inheritsLoose\"));\nvar _defineProperty2 = _interopRequireDefault(require(\"@babel/runtime/helpers/defineProperty\"));\nvar _excluded = [\"componentRef\", \"__relayContext\", \"__rootIsQueryRenderer\"];\nvar buildReactRelayContainer = require('./buildReactRelayContainer');\nvar _require = require('./ReactRelayContainerUtils'),\n getContainerName = _require.getContainerName;\nvar _require2 = require('./RelayContext'),\n assertRelayContext = _require2.assertRelayContext;\nvar areEqual = require(\"fbjs/lib/areEqual\");\nvar React = require('react');\nvar _require3 = require('relay-runtime'),\n createFragmentSpecResolver = _require3.createFragmentSpecResolver,\n getDataIDsFromObject = _require3.getDataIDsFromObject,\n isScalarAndEqual = _require3.isScalarAndEqual;\nfunction createContainerWithFragments(Component, fragments) {\n var _class;\n var containerName = getContainerName(Component);\n return _class = /*#__PURE__*/function (_React$Component) {\n (0, _inheritsLoose2[\"default\"])(_class, _React$Component);\n function _class(props) {\n var _props$__rootIsQueryR, _this;\n _this = _React$Component.call(this, props) || this;\n (0, _defineProperty2[\"default\"])((0, _assertThisInitialized2[\"default\"])(_this), \"_handleFragmentDataUpdate\", function () {\n var resolverFromThisUpdate = _this.state.resolver;\n _this.setState(function (updatedState) {\n return resolverFromThisUpdate === updatedState.resolver ? {\n data: updatedState.resolver.resolve(),\n relayProp: getRelayProp(updatedState.relayProp.environment)\n } : null;\n });\n });\n var relayContext = assertRelayContext(props.__relayContext);\n var rootIsQueryRenderer = (_props$__rootIsQueryR = props.__rootIsQueryRenderer) !== null && _props$__rootIsQueryR !== void 0 ? _props$__rootIsQueryR : false;\n var resolver = createFragmentSpecResolver(relayContext, containerName, fragments, props, rootIsQueryRenderer);\n _this.state = {\n data: resolver.resolve(),\n prevProps: props,\n prevPropsContext: relayContext,\n relayProp: getRelayProp(relayContext.environment),\n resolver: resolver\n };\n return _this;\n }\n _class.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, prevState) {\n var _nextProps$__rootIsQu;\n var prevProps = prevState.prevProps;\n var relayContext = assertRelayContext(nextProps.__relayContext);\n var rootIsQueryRenderer = (_nextProps$__rootIsQu = nextProps.__rootIsQueryRenderer) !== null && _nextProps$__rootIsQu !== void 0 ? _nextProps$__rootIsQu : false;\n var prevIDs = getDataIDsFromObject(fragments, prevProps);\n var nextIDs = getDataIDsFromObject(fragments, nextProps);\n var resolver = prevState.resolver;\n if (prevState.prevPropsContext.environment !== relayContext.environment || !areEqual(prevIDs, nextIDs)) {\n resolver = createFragmentSpecResolver(relayContext, containerName, fragments, nextProps, rootIsQueryRenderer);\n return {\n data: resolver.resolve(),\n prevPropsContext: relayContext,\n prevProps: nextProps,\n relayProp: getRelayProp(relayContext.environment),\n resolver: resolver\n };\n } else {\n resolver.setProps(nextProps);\n var data = resolver.resolve();\n if (data !== prevState.data) {\n return {\n data: data,\n prevProps: nextProps,\n prevPropsContext: relayContext,\n relayProp: getRelayProp(relayContext.environment)\n };\n }\n }\n return null;\n };\n var _proto = _class.prototype;\n _proto.componentDidMount = function componentDidMount() {\n this._subscribeToNewResolverAndRerenderIfStoreHasChanged();\n };\n _proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {\n if (this.state.resolver !== prevState.resolver) {\n prevState.resolver.dispose();\n this._subscribeToNewResolverAndRerenderIfStoreHasChanged();\n } else {\n this._rerenderIfStoreHasChanged();\n }\n };\n _proto.componentWillUnmount = function componentWillUnmount() {\n this.state.resolver.dispose();\n };\n _proto.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) {\n if (nextState.data !== this.state.data) {\n return true;\n }\n var keys = Object.keys(nextProps);\n for (var ii = 0; ii < keys.length; ii++) {\n var key = keys[ii];\n if (key === '__relayContext') {\n if (nextState.prevPropsContext.environment !== this.state.prevPropsContext.environment) {\n return true;\n }\n } else {\n if (!fragments.hasOwnProperty(key) && !isScalarAndEqual(nextProps[key], this.props[key])) {\n return true;\n }\n }\n }\n return false;\n };\n _proto._rerenderIfStoreHasChanged = function _rerenderIfStoreHasChanged() {\n var _this$state = this.state,\n data = _this$state.data,\n resolver = _this$state.resolver;\n var maybeNewData = resolver.resolve();\n if (data !== maybeNewData) {\n this.setState({\n data: maybeNewData\n });\n }\n };\n _proto._subscribeToNewResolverAndRerenderIfStoreHasChanged = function _subscribeToNewResolverAndRerenderIfStoreHasChanged() {\n var _this$state2 = this.state,\n data = _this$state2.data,\n resolver = _this$state2.resolver;\n var maybeNewData = resolver.resolve();\n resolver.setCallback(this.props, this._handleFragmentDataUpdate);\n if (data !== maybeNewData) {\n this.setState({\n data: maybeNewData\n });\n }\n };\n _proto.render = function render() {\n var _this$props = this.props,\n componentRef = _this$props.componentRef,\n __relayContext = _this$props.__relayContext,\n __rootIsQueryRenderer = _this$props.__rootIsQueryRenderer,\n props = (0, _objectWithoutPropertiesLoose2[\"default\"])(_this$props, _excluded);\n return React.createElement(Component, (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, props), this.state.data), {}, {\n ref: componentRef,\n relay: this.state.relayProp\n }));\n };\n return _class;\n }(React.Component), (0, _defineProperty2[\"default\"])(_class, \"displayName\", containerName), _class;\n}\nfunction getRelayProp(environment) {\n return {\n environment: environment\n };\n}\nfunction createContainer(Component, fragmentSpec) {\n return buildReactRelayContainer(Component, fragmentSpec, createContainerWithFragments);\n}\nmodule.exports = {\n createContainer: createContainer\n};","'use strict';\n\nvar ReactRelayContext = require('./ReactRelayContext');\nvar ReactRelayQueryRendererContext = require('./ReactRelayQueryRendererContext');\nvar areEqual = require(\"fbjs/lib/areEqual\");\nvar React = require('react');\nvar _require = require('relay-runtime'),\n createOperationDescriptor = _require.createOperationDescriptor,\n deepFreeze = _require.deepFreeze,\n getRequest = _require.getRequest;\nvar useLayoutEffect = React.useLayoutEffect,\n useState = React.useState,\n useRef = React.useRef,\n useMemo = React.useMemo;\nvar queryRendererContext = {\n rootIsQueryRenderer: true\n};\nfunction useDeepCompare(value) {\n var latestValue = React.useRef(value);\n if (!areEqual(latestValue.current, value)) {\n if (process.env.NODE_ENV !== \"production\") {\n deepFreeze(value);\n }\n latestValue.current = value;\n }\n return latestValue.current;\n}\nfunction ReactRelayLocalQueryRenderer(props) {\n var environment = props.environment,\n query = props.query,\n variables = props.variables,\n render = props.render;\n var latestVariables = useDeepCompare(variables);\n var operation = useMemo(function () {\n var request = getRequest(query);\n return createOperationDescriptor(request, latestVariables);\n }, [query, latestVariables]);\n var relayContext = useMemo(function () {\n return {\n environment: environment\n };\n }, [environment]);\n var dataRef = useRef(null);\n var _useState = useState(null),\n forceUpdate = _useState[1];\n var cleanupFnRef = useRef(null);\n var snapshot = useMemo(function () {\n environment.check(operation);\n var res = environment.lookup(operation.fragment);\n dataRef.current = res.data;\n var retainDisposable = environment.retain(operation);\n var subscribeDisposable = environment.subscribe(res, function (newSnapshot) {\n dataRef.current = newSnapshot.data;\n forceUpdate(dataRef.current);\n });\n var disposed = false;\n function nextCleanupFn() {\n if (!disposed) {\n disposed = true;\n cleanupFnRef.current = null;\n retainDisposable.dispose();\n subscribeDisposable.dispose();\n }\n }\n if (cleanupFnRef.current) {\n cleanupFnRef.current();\n }\n cleanupFnRef.current = nextCleanupFn;\n return res;\n }, [environment, operation]);\n useLayoutEffect(function () {\n var cleanupFn = cleanupFnRef.current;\n return function () {\n cleanupFn && cleanupFn();\n };\n }, [snapshot]);\n return /*#__PURE__*/React.createElement(ReactRelayContext.Provider, {\n value: relayContext\n }, /*#__PURE__*/React.createElement(ReactRelayQueryRendererContext.Provider, {\n value: queryRendererContext\n }, render({\n props: dataRef.current\n })));\n}\nmodule.exports = ReactRelayLocalQueryRenderer;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\nvar _objectWithoutPropertiesLoose2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectWithoutPropertiesLoose\"));\nvar _assertThisInitialized2 = _interopRequireDefault(require(\"@babel/runtime/helpers/assertThisInitialized\"));\nvar _inheritsLoose2 = _interopRequireDefault(require(\"@babel/runtime/helpers/inheritsLoose\"));\nvar _defineProperty2 = _interopRequireDefault(require(\"@babel/runtime/helpers/defineProperty\"));\nvar _objectSpread3 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar _excluded = [\"componentRef\"],\n _excluded2 = [\"componentRef\", \"__relayContext\", \"__rootIsQueryRenderer\"],\n _excluded3 = [\"componentRef\", \"__relayContext\", \"__rootIsQueryRenderer\"];\nvar buildReactRelayContainer = require('./buildReactRelayContainer');\nvar getRootVariablesForFragments = require('./getRootVariablesForFragments');\nvar _require = require('./ReactRelayContainerUtils'),\n getComponentName = _require.getComponentName,\n getContainerName = _require.getContainerName;\nvar ReactRelayContext = require('./ReactRelayContext');\nvar ReactRelayQueryFetcher = require('./ReactRelayQueryFetcher');\nvar _require2 = require('./RelayContext'),\n assertRelayContext = _require2.assertRelayContext;\nvar areEqual = require(\"fbjs/lib/areEqual\");\nvar invariant = require('invariant');\nvar React = require('react');\nvar _require3 = require('relay-runtime'),\n ConnectionInterface = _require3.ConnectionInterface,\n Observable = _require3.Observable,\n RelayFeatureFlags = _require3.RelayFeatureFlags,\n createFragmentSpecResolver = _require3.createFragmentSpecResolver,\n createOperationDescriptor = _require3.createOperationDescriptor,\n getDataIDsFromObject = _require3.getDataIDsFromObject,\n getRequest = _require3.getRequest,\n getVariablesFromObject = _require3.getVariablesFromObject,\n isScalarAndEqual = _require3.isScalarAndEqual;\nvar warning = require(\"fbjs/lib/warning\");\nvar FORWARD = 'forward';\nfunction createGetConnectionFromProps(metadata) {\n var path = metadata.path;\n !path ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'ReactRelayPaginationContainer: Unable to synthesize a ' + 'getConnectionFromProps function.') : invariant(false) : void 0;\n return function (props) {\n var data = props[metadata.fragmentName];\n for (var i = 0; i < path.length; i++) {\n if (!data || typeof data !== 'object') {\n return null;\n }\n data = data[path[i]];\n }\n return data;\n };\n}\nfunction createGetFragmentVariables(metadata) {\n var countVariable = metadata.count;\n !countVariable ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'ReactRelayPaginationContainer: Unable to synthesize a ' + 'getFragmentVariables function.') : invariant(false) : void 0;\n return function (prevVars, totalCount) {\n return (0, _objectSpread3[\"default\"])((0, _objectSpread3[\"default\"])({}, prevVars), {}, (0, _defineProperty2[\"default\"])({}, countVariable, totalCount));\n };\n}\nfunction findConnectionMetadata(fragments) {\n var foundConnectionMetadata = null;\n var isRelayModern = false;\n for (var fragmentName in fragments) {\n var fragment = fragments[fragmentName];\n var connectionMetadata = fragment.metadata && fragment.metadata.connection;\n if (fragment.metadata !== undefined) {\n isRelayModern = true;\n }\n if (connectionMetadata) {\n !(connectionMetadata.length === 1) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'ReactRelayPaginationContainer: Only a single @connection is ' + 'supported, `%s` has %s.', fragmentName, connectionMetadata.length) : invariant(false) : void 0;\n !!foundConnectionMetadata ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'ReactRelayPaginationContainer: Only a single fragment with ' + '@connection is supported.') : invariant(false) : void 0;\n foundConnectionMetadata = (0, _objectSpread3[\"default\"])((0, _objectSpread3[\"default\"])({}, connectionMetadata[0]), {}, {\n fragmentName: fragmentName\n });\n }\n }\n !(!isRelayModern || foundConnectionMetadata !== null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'ReactRelayPaginationContainer: A @connection directive must be present.') : invariant(false) : void 0;\n return foundConnectionMetadata || {};\n}\nfunction toObserver(observerOrCallback) {\n return typeof observerOrCallback === 'function' ? {\n error: observerOrCallback,\n complete: observerOrCallback,\n unsubscribe: function unsubscribe(subscription) {\n typeof observerOrCallback === 'function' && observerOrCallback();\n }\n } : observerOrCallback || {};\n}\nfunction createContainerWithFragments(Component, fragments, connectionConfig) {\n var _class;\n var componentName = getComponentName(Component);\n var containerName = getContainerName(Component);\n var metadata = findConnectionMetadata(fragments);\n var getConnectionFromProps = connectionConfig.getConnectionFromProps || createGetConnectionFromProps(metadata);\n var direction = connectionConfig.direction || metadata.direction;\n !direction ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'ReactRelayPaginationContainer: Unable to infer direction of the ' + 'connection, possibly because both first and last are provided.') : invariant(false) : void 0;\n var getFragmentVariables = connectionConfig.getFragmentVariables || createGetFragmentVariables(metadata);\n return _class = /*#__PURE__*/function (_React$Component) {\n (0, _inheritsLoose2[\"default\"])(_class, _React$Component);\n function _class(props) {\n var _props$__rootIsQueryR, _this;\n _this = _React$Component.call(this, props) || this;\n (0, _defineProperty2[\"default\"])((0, _assertThisInitialized2[\"default\"])(_this), \"_handleFragmentDataUpdate\", function () {\n _this.setState({\n data: _this._resolver.resolve()\n });\n });\n (0, _defineProperty2[\"default\"])((0, _assertThisInitialized2[\"default\"])(_this), \"_hasMore\", function () {\n var connectionData = _this._getConnectionData();\n return !!(connectionData && connectionData.hasMore && connectionData.cursor);\n });\n (0, _defineProperty2[\"default\"])((0, _assertThisInitialized2[\"default\"])(_this), \"_isLoading\", function () {\n return !!_this._refetchSubscription;\n });\n (0, _defineProperty2[\"default\"])((0, _assertThisInitialized2[\"default\"])(_this), \"_refetchConnection\", function (totalCount, observerOrCallback, refetchVariables) {\n if (!_this._canFetchPage('refetchConnection')) {\n return {\n dispose: function dispose() {}\n };\n }\n _this._refetchVariables = refetchVariables;\n var paginatingVariables = {\n count: totalCount,\n cursor: null,\n totalCount: totalCount\n };\n var fetch = _this._fetchPage(paginatingVariables, toObserver(observerOrCallback), {\n force: true\n });\n return {\n dispose: fetch.unsubscribe\n };\n });\n (0, _defineProperty2[\"default\"])((0, _assertThisInitialized2[\"default\"])(_this), \"_loadMore\", function (pageSize, observerOrCallback, options) {\n if (!_this._canFetchPage('loadMore')) {\n return {\n dispose: function dispose() {}\n };\n }\n var observer = toObserver(observerOrCallback);\n var connectionData = _this._getConnectionData();\n if (!connectionData) {\n Observable.create(function (sink) {\n return sink.complete();\n }).subscribe(observer);\n return null;\n }\n var totalCount = connectionData.edgeCount + pageSize;\n if (options && options.force) {\n return _this._refetchConnection(totalCount, observerOrCallback);\n }\n var _ConnectionInterface$ = ConnectionInterface.get(),\n END_CURSOR = _ConnectionInterface$.END_CURSOR,\n START_CURSOR = _ConnectionInterface$.START_CURSOR;\n var cursor = connectionData.cursor;\n process.env.NODE_ENV !== \"production\" ? warning(cursor != null && cursor !== '', 'ReactRelayPaginationContainer: Cannot `loadMore` without valid `%s` (got `%s`)', direction === FORWARD ? END_CURSOR : START_CURSOR, cursor) : void 0;\n var paginatingVariables = {\n count: pageSize,\n cursor: cursor,\n totalCount: totalCount\n };\n var fetch = _this._fetchPage(paginatingVariables, observer, options);\n return {\n dispose: fetch.unsubscribe\n };\n });\n var relayContext = assertRelayContext(props.__relayContext);\n var rootIsQueryRenderer = (_props$__rootIsQueryR = props.__rootIsQueryRenderer) !== null && _props$__rootIsQueryR !== void 0 ? _props$__rootIsQueryR : false;\n _this._isARequestInFlight = false;\n _this._refetchSubscription = null;\n _this._refetchVariables = null;\n if (RelayFeatureFlags.ENABLE_CONTAINERS_SUBSCRIBE_ON_COMMIT === true) {\n _this._resolver = createFragmentSpecResolver(relayContext, containerName, fragments, props, rootIsQueryRenderer);\n } else {\n _this._resolver = createFragmentSpecResolver(relayContext, containerName, fragments, props, rootIsQueryRenderer, _this._handleFragmentDataUpdate);\n }\n _this.state = {\n data: _this._resolver.resolve(),\n prevContext: relayContext,\n contextForChildren: relayContext,\n relayProp: _this._buildRelayProp(relayContext),\n resolverGeneration: 0\n };\n _this._isUnmounted = false;\n _this._hasFetched = false;\n return _this;\n }\n var _proto = _class.prototype;\n _proto.componentDidMount = function componentDidMount() {\n this._isUnmounted = false;\n if (RelayFeatureFlags.ENABLE_CONTAINERS_SUBSCRIBE_ON_COMMIT === true) {\n this._subscribeToNewResolverAndRerenderIfStoreHasChanged();\n }\n };\n _proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {\n if (RelayFeatureFlags.ENABLE_CONTAINERS_SUBSCRIBE_ON_COMMIT === true) {\n if (prevState.resolverGeneration !== this.state.resolverGeneration) {\n this._subscribeToNewResolverAndRerenderIfStoreHasChanged();\n } else {\n this._rerenderIfStoreHasChanged();\n }\n }\n };\n _proto.UNSAFE_componentWillReceiveProps = function UNSAFE_componentWillReceiveProps(nextProps) {\n var _this2 = this;\n var _nextProps$__rootIsQu;\n var relayContext = assertRelayContext(nextProps.__relayContext);\n var rootIsQueryRenderer = (_nextProps$__rootIsQu = nextProps.__rootIsQueryRenderer) !== null && _nextProps$__rootIsQu !== void 0 ? _nextProps$__rootIsQu : false;\n var prevIDs = getDataIDsFromObject(fragments, this.props);\n var nextIDs = getDataIDsFromObject(fragments, nextProps);\n var prevRootVariables = getRootVariablesForFragments(fragments, this.props);\n var nextRootVariables = getRootVariablesForFragments(fragments, nextProps);\n if (relayContext.environment !== this.state.prevContext.environment || !areEqual(prevRootVariables, nextRootVariables) || !areEqual(prevIDs, nextIDs)) {\n this._cleanup();\n if (RelayFeatureFlags.ENABLE_CONTAINERS_SUBSCRIBE_ON_COMMIT === true) {\n this._resolver = createFragmentSpecResolver(relayContext, containerName, fragments, nextProps, rootIsQueryRenderer);\n } else {\n this._resolver = createFragmentSpecResolver(relayContext, containerName, fragments, nextProps, rootIsQueryRenderer, this._handleFragmentDataUpdate);\n }\n this.setState(function (prevState) {\n return {\n prevContext: relayContext,\n contextForChildren: relayContext,\n relayProp: _this2._buildRelayProp(relayContext),\n resolverGeneration: prevState.resolverGeneration + 1\n };\n });\n } else if (!this._hasFetched) {\n this._resolver.setProps(nextProps);\n }\n var data = this._resolver.resolve();\n if (data !== this.state.data) {\n this.setState({\n data: data\n });\n }\n };\n _proto.componentWillUnmount = function componentWillUnmount() {\n this._isUnmounted = true;\n this._cleanup();\n };\n _proto.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) {\n if (nextState.data !== this.state.data || nextState.relayProp !== this.state.relayProp || nextState.resolverGeneration !== this.state.resolverGeneration) {\n return true;\n }\n var keys = Object.keys(nextProps);\n for (var ii = 0; ii < keys.length; ii++) {\n var key = keys[ii];\n if (key === '__relayContext') {\n if (nextState.prevContext.environment !== this.state.prevContext.environment) {\n return true;\n }\n } else {\n if (!fragments.hasOwnProperty(key) && !isScalarAndEqual(nextProps[key], this.props[key])) {\n return true;\n }\n }\n }\n return false;\n };\n _proto._buildRelayProp = function _buildRelayProp(relayContext) {\n return {\n hasMore: this._hasMore,\n isLoading: this._isLoading,\n loadMore: this._loadMore,\n refetchConnection: this._refetchConnection,\n environment: relayContext.environment\n };\n };\n _proto._rerenderIfStoreHasChanged = function _rerenderIfStoreHasChanged() {\n var data = this.state.data;\n var maybeNewData = this._resolver.resolve();\n if (data !== maybeNewData) {\n this.setState({\n data: maybeNewData\n });\n }\n };\n _proto._subscribeToNewResolverAndRerenderIfStoreHasChanged = function _subscribeToNewResolverAndRerenderIfStoreHasChanged() {\n var data = this.state.data;\n var maybeNewData = this._resolver.resolve();\n this._resolver.setCallback(this.props, this._handleFragmentDataUpdate);\n if (data !== maybeNewData) {\n this.setState({\n data: maybeNewData\n });\n }\n };\n _proto._getConnectionData = function _getConnectionData() {\n var _this$props = this.props,\n _ = _this$props.componentRef,\n restProps = (0, _objectWithoutPropertiesLoose2[\"default\"])(_this$props, _excluded);\n var props = (0, _objectSpread3[\"default\"])((0, _objectSpread3[\"default\"])({}, restProps), this.state.data);\n var connectionData = getConnectionFromProps(props);\n if (connectionData == null) {\n return null;\n }\n var _ConnectionInterface$2 = ConnectionInterface.get(),\n EDGES = _ConnectionInterface$2.EDGES,\n PAGE_INFO = _ConnectionInterface$2.PAGE_INFO,\n HAS_NEXT_PAGE = _ConnectionInterface$2.HAS_NEXT_PAGE,\n HAS_PREV_PAGE = _ConnectionInterface$2.HAS_PREV_PAGE,\n END_CURSOR = _ConnectionInterface$2.END_CURSOR,\n START_CURSOR = _ConnectionInterface$2.START_CURSOR;\n !(typeof connectionData === 'object') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'ReactRelayPaginationContainer: Expected `getConnectionFromProps()` in `%s`' + 'to return `null` or a plain object with %s and %s properties, got `%s`.', componentName, EDGES, PAGE_INFO, connectionData) : invariant(false) : void 0;\n var edges = connectionData[EDGES];\n var pageInfo = connectionData[PAGE_INFO];\n if (edges == null || pageInfo == null) {\n return null;\n }\n !Array.isArray(edges) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'ReactRelayPaginationContainer: Expected `getConnectionFromProps()` in `%s`' + 'to return an object with %s: Array, got `%s`.', componentName, EDGES, edges) : invariant(false) : void 0;\n !(typeof pageInfo === 'object') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'ReactRelayPaginationContainer: Expected `getConnectionFromProps()` in `%s`' + 'to return an object with %s: Object, got `%s`.', componentName, PAGE_INFO, pageInfo) : invariant(false) : void 0;\n var hasMore = direction === FORWARD ? pageInfo[HAS_NEXT_PAGE] : pageInfo[HAS_PREV_PAGE];\n var cursor = direction === FORWARD ? pageInfo[END_CURSOR] : pageInfo[START_CURSOR];\n if (typeof hasMore !== 'boolean' || edges.length !== 0 && typeof cursor === 'undefined') {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'ReactRelayPaginationContainer: Cannot paginate without %s fields in `%s`. ' + 'Be sure to fetch %s (got `%s`) and %s (got `%s`).', PAGE_INFO, componentName, direction === FORWARD ? HAS_NEXT_PAGE : HAS_PREV_PAGE, hasMore, direction === FORWARD ? END_CURSOR : START_CURSOR, cursor) : void 0;\n return null;\n }\n return {\n cursor: cursor,\n edgeCount: edges.length,\n hasMore: hasMore\n };\n };\n _proto._getQueryFetcher = function _getQueryFetcher() {\n if (!this._queryFetcher) {\n this._queryFetcher = new ReactRelayQueryFetcher();\n }\n return this._queryFetcher;\n };\n _proto._canFetchPage = function _canFetchPage(method) {\n if (this._isUnmounted) {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'ReactRelayPaginationContainer: Unexpected call of `%s` ' + 'on unmounted container `%s`. It looks like some instances ' + 'of your container still trying to fetch data but they already ' + 'unmounted. Please make sure you clear all timers, intervals, async ' + 'calls, etc that may trigger `%s` call.', method, containerName, method) : void 0;\n return false;\n }\n return true;\n };\n _proto._fetchPage = function _fetchPage(paginatingVariables, observer, options) {\n var _this3 = this;\n var _assertRelayContext = assertRelayContext(this.props.__relayContext),\n environment = _assertRelayContext.environment;\n var _this$props2 = this.props,\n _ = _this$props2.componentRef,\n __relayContext = _this$props2.__relayContext,\n __rootIsQueryRenderer = _this$props2.__rootIsQueryRenderer,\n restProps = (0, _objectWithoutPropertiesLoose2[\"default\"])(_this$props2, _excluded2);\n var props = (0, _objectSpread3[\"default\"])((0, _objectSpread3[\"default\"])({}, restProps), this.state.data);\n var fragmentVariables;\n var rootVariables = getRootVariablesForFragments(fragments, restProps);\n fragmentVariables = getVariablesFromObject(fragments, restProps);\n fragmentVariables = (0, _objectSpread3[\"default\"])((0, _objectSpread3[\"default\"])((0, _objectSpread3[\"default\"])({}, rootVariables), fragmentVariables), this._refetchVariables);\n var fetchVariables = connectionConfig.getVariables(props, {\n count: paginatingVariables.count,\n cursor: paginatingVariables.cursor\n }, fragmentVariables);\n !(typeof fetchVariables === 'object' && fetchVariables !== null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'ReactRelayPaginationContainer: Expected `getVariables()` to ' + 'return an object, got `%s` in `%s`.', fetchVariables, componentName) : invariant(false) : void 0;\n fetchVariables = (0, _objectSpread3[\"default\"])((0, _objectSpread3[\"default\"])({}, fetchVariables), this._refetchVariables);\n fragmentVariables = (0, _objectSpread3[\"default\"])((0, _objectSpread3[\"default\"])({}, fetchVariables), fragmentVariables);\n var cacheConfig = options ? {\n force: !!options.force\n } : undefined;\n if (cacheConfig != null && (options === null || options === void 0 ? void 0 : options.metadata) != null) {\n cacheConfig.metadata = options === null || options === void 0 ? void 0 : options.metadata;\n }\n var request = getRequest(connectionConfig.query);\n var operation = createOperationDescriptor(request, fetchVariables, cacheConfig);\n var refetchSubscription = null;\n if (this._refetchSubscription) {\n this._refetchSubscription.unsubscribe();\n }\n this._hasFetched = true;\n var onNext = function onNext(payload, complete) {\n var prevData = _this3._resolver.resolve();\n _this3._resolver.setVariables(getFragmentVariables(fragmentVariables, paginatingVariables.totalCount), operation.request.node);\n var nextData = _this3._resolver.resolve();\n if (!areEqual(prevData, nextData)) {\n _this3.setState({\n data: nextData,\n contextForChildren: {\n environment: _this3.props.__relayContext.environment\n }\n }, complete);\n } else {\n complete();\n }\n };\n var cleanup = function cleanup() {\n if (_this3._refetchSubscription === refetchSubscription) {\n _this3._refetchSubscription = null;\n _this3._isARequestInFlight = false;\n }\n };\n this._isARequestInFlight = true;\n refetchSubscription = this._getQueryFetcher().execute({\n environment: environment,\n operation: operation,\n preservePreviousReferences: true\n }).mergeMap(function (payload) {\n return Observable.create(function (sink) {\n onNext(payload, function () {\n sink.next();\n sink.complete();\n });\n });\n })[\"do\"]({\n error: cleanup,\n complete: cleanup,\n unsubscribe: cleanup\n }).subscribe(observer || {});\n this._refetchSubscription = this._isARequestInFlight ? refetchSubscription : null;\n return refetchSubscription;\n };\n _proto._cleanup = function _cleanup() {\n this._resolver.dispose();\n this._refetchVariables = null;\n this._hasFetched = false;\n if (this._refetchSubscription) {\n this._refetchSubscription.unsubscribe();\n this._refetchSubscription = null;\n this._isARequestInFlight = false;\n }\n if (this._queryFetcher) {\n this._queryFetcher.dispose();\n }\n };\n _proto.render = function render() {\n var _this$props3 = this.props,\n componentRef = _this$props3.componentRef,\n __relayContext = _this$props3.__relayContext,\n __rootIsQueryRenderer = _this$props3.__rootIsQueryRenderer,\n props = (0, _objectWithoutPropertiesLoose2[\"default\"])(_this$props3, _excluded3);\n return /*#__PURE__*/React.createElement(ReactRelayContext.Provider, {\n value: this.state.contextForChildren\n }, /*#__PURE__*/React.createElement(Component, (0, _extends2[\"default\"])({}, props, this.state.data, {\n ref: componentRef,\n relay: this.state.relayProp\n })));\n };\n return _class;\n }(React.Component), (0, _defineProperty2[\"default\"])(_class, \"displayName\", containerName), _class;\n}\nfunction createContainer(Component, fragmentSpec, connectionConfig) {\n return buildReactRelayContainer(Component, fragmentSpec, function (ComponentClass, fragments) {\n return createContainerWithFragments(ComponentClass, fragments, connectionConfig);\n });\n}\nmodule.exports = {\n createContainer: createContainer\n};","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _defineProperty2 = _interopRequireDefault(require(\"@babel/runtime/helpers/defineProperty\"));\nvar invariant = require('invariant');\nvar _require = require('relay-runtime'),\n fetchQuery = _require.__internal.fetchQuery,\n createOperationDescriptor = _require.createOperationDescriptor,\n isRelayModernEnvironment = _require.isRelayModernEnvironment;\nvar ReactRelayQueryFetcher = /*#__PURE__*/function () {\n function ReactRelayQueryFetcher(args) {\n (0, _defineProperty2[\"default\"])(this, \"_selectionReferences\", []);\n (0, _defineProperty2[\"default\"])(this, \"_didFetchFinish\", false);\n if (args != null) {\n this._cacheSelectionReference = args.cacheSelectionReference;\n this._selectionReferences = args.selectionReferences;\n }\n }\n var _proto = ReactRelayQueryFetcher.prototype;\n _proto.getSelectionReferences = function getSelectionReferences() {\n return {\n cacheSelectionReference: this._cacheSelectionReference,\n selectionReferences: this._selectionReferences\n };\n };\n _proto.lookupInStore = function lookupInStore(environment, operation, fetchPolicy) {\n if (fetchPolicy === 'store-and-network' || fetchPolicy === 'store-or-network') {\n if (environment.check(operation).status === 'available') {\n this._retainCachedOperation(environment, operation);\n return environment.lookup(operation.fragment);\n }\n }\n return null;\n };\n _proto.getFetchResult = function getFetchResult() {\n if (this._didFetchFinish) {\n if (this._error != null) {\n return {\n error: this._error\n };\n } else if (this._snapshot != null) {\n return {\n snapshot: this._snapshot\n };\n }\n } else {\n return null;\n }\n };\n _proto.execute = function execute(_ref) {\n var _this = this;\n var environment = _ref.environment,\n operation = _ref.operation,\n _ref$preservePrevious = _ref.preservePreviousReferences,\n preservePreviousReferences = _ref$preservePrevious === void 0 ? false : _ref$preservePrevious;\n var reference = environment.retain(operation);\n var error = function error() {\n _this._selectionReferences = _this._selectionReferences.concat(reference);\n };\n var complete = function complete() {\n if (!preservePreviousReferences) {\n _this.disposeSelectionReferences();\n }\n _this._selectionReferences = _this._selectionReferences.concat(reference);\n };\n var unsubscribe = function unsubscribe() {\n _this._selectionReferences = _this._selectionReferences.concat(reference);\n };\n if (!isRelayModernEnvironment(environment)) {\n return environment.execute({\n operation: operation\n })[\"do\"]({\n error: error,\n complete: complete,\n unsubscribe: unsubscribe\n });\n }\n return fetchQuery(environment, operation)[\"do\"]({\n error: error,\n complete: complete,\n unsubscribe: unsubscribe\n });\n };\n _proto.setOnDataChange = function setOnDataChange(onDataChange) {\n !this._fetchOptions ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'ReactRelayQueryFetcher: `setOnDataChange` should have been called after having called `fetch`') : invariant(false) : void 0;\n if (typeof onDataChange === 'function') {\n this._fetchOptions.onDataChangeCallbacks = this._fetchOptions.onDataChangeCallbacks || [];\n this._fetchOptions.onDataChangeCallbacks.push(onDataChange);\n if (this._didFetchFinish) {\n if (this._error != null) {\n onDataChange({\n error: this._error\n });\n } else if (this._snapshot != null) {\n onDataChange({\n snapshot: this._snapshot\n });\n }\n }\n }\n };\n _proto.fetch = function fetch(fetchOptions, cacheConfigOverride) {\n var _this2 = this;\n var environment = fetchOptions.environment,\n operation = fetchOptions.operation,\n onDataChange = fetchOptions.onDataChange;\n var fetchHasReturned = false;\n var _error;\n this.disposeRequest();\n var oldOnDataChangeCallbacks = this._fetchOptions && this._fetchOptions.onDataChangeCallbacks;\n this._fetchOptions = {\n environment: environment,\n onDataChangeCallbacks: oldOnDataChangeCallbacks || [],\n operation: operation\n };\n if (onDataChange && this._fetchOptions.onDataChangeCallbacks.indexOf(onDataChange) === -1) {\n this._fetchOptions.onDataChangeCallbacks.push(onDataChange);\n }\n var operationOverride = cacheConfigOverride ? createOperationDescriptor(operation.request.node, operation.request.variables, cacheConfigOverride) : operation;\n var request = this.execute({\n environment: environment,\n operation: operationOverride\n })[\"finally\"](function () {\n _this2._pendingRequest = null;\n }).subscribe({\n next: function next() {\n _this2._didFetchFinish = true;\n _this2._error = null;\n _this2._onQueryDataAvailable({\n notifyFirstResult: fetchHasReturned\n });\n },\n error: function error(err) {\n _this2._didFetchFinish = true;\n _this2._error = err;\n _this2._snapshot = null;\n var onDataChangeCallbacks = _this2._fetchOptions && _this2._fetchOptions.onDataChangeCallbacks;\n if (fetchHasReturned) {\n if (onDataChangeCallbacks) {\n onDataChangeCallbacks.forEach(function (onDataChange) {\n onDataChange({\n error: err\n });\n });\n }\n } else {\n _error = err;\n }\n }\n });\n this._pendingRequest = {\n dispose: function dispose() {\n request.unsubscribe();\n }\n };\n fetchHasReturned = true;\n if (_error) {\n throw _error;\n }\n return this._snapshot;\n };\n _proto.retry = function retry(cacheConfigOverride) {\n !this._fetchOptions ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'ReactRelayQueryFetcher: `retry` should be called after having called `fetch`') : invariant(false) : void 0;\n return this.fetch({\n environment: this._fetchOptions.environment,\n operation: this._fetchOptions.operation,\n onDataChange: null\n }, cacheConfigOverride);\n };\n _proto.dispose = function dispose() {\n this.disposeRequest();\n this.disposeSelectionReferences();\n };\n _proto.disposeRequest = function disposeRequest() {\n this._error = null;\n this._snapshot = null;\n if (this._pendingRequest) {\n this._pendingRequest.dispose();\n }\n if (this._rootSubscription) {\n this._rootSubscription.dispose();\n this._rootSubscription = null;\n }\n };\n _proto._retainCachedOperation = function _retainCachedOperation(environment, operation) {\n this._disposeCacheSelectionReference();\n this._cacheSelectionReference = environment.retain(operation);\n };\n _proto._disposeCacheSelectionReference = function _disposeCacheSelectionReference() {\n this._cacheSelectionReference && this._cacheSelectionReference.dispose();\n this._cacheSelectionReference = null;\n };\n _proto.disposeSelectionReferences = function disposeSelectionReferences() {\n this._disposeCacheSelectionReference();\n this._selectionReferences.forEach(function (r) {\n return r.dispose();\n });\n this._selectionReferences = [];\n };\n _proto._onQueryDataAvailable = function _onQueryDataAvailable(_ref2) {\n var _this3 = this;\n var notifyFirstResult = _ref2.notifyFirstResult;\n !this._fetchOptions ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'ReactRelayQueryFetcher: `_onQueryDataAvailable` should have been called after having called `fetch`') : invariant(false) : void 0;\n var _this$_fetchOptions = this._fetchOptions,\n environment = _this$_fetchOptions.environment,\n onDataChangeCallbacks = _this$_fetchOptions.onDataChangeCallbacks,\n operation = _this$_fetchOptions.operation;\n if (this._snapshot) {\n return;\n }\n this._snapshot = environment.lookup(operation.fragment);\n this._rootSubscription = environment.subscribe(this._snapshot, function (snapshot) {\n if (_this3._fetchOptions != null) {\n var maybeNewOnDataChangeCallbacks = _this3._fetchOptions.onDataChangeCallbacks;\n if (Array.isArray(maybeNewOnDataChangeCallbacks)) {\n maybeNewOnDataChangeCallbacks.forEach(function (onDataChange) {\n return onDataChange({\n snapshot: snapshot\n });\n });\n }\n }\n });\n if (this._snapshot && notifyFirstResult && Array.isArray(onDataChangeCallbacks)) {\n var snapshot = this._snapshot;\n onDataChangeCallbacks.forEach(function (onDataChange) {\n return onDataChange({\n snapshot: snapshot\n });\n });\n }\n };\n return ReactRelayQueryFetcher;\n}();\nmodule.exports = ReactRelayQueryFetcher;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _objectSpread2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar _assertThisInitialized2 = _interopRequireDefault(require(\"@babel/runtime/helpers/assertThisInitialized\"));\nvar _inheritsLoose2 = _interopRequireDefault(require(\"@babel/runtime/helpers/inheritsLoose\"));\nvar _defineProperty2 = _interopRequireDefault(require(\"@babel/runtime/helpers/defineProperty\"));\nvar ReactRelayContext = require('./ReactRelayContext');\nvar ReactRelayQueryFetcher = require('./ReactRelayQueryFetcher');\nvar ReactRelayQueryRendererContext = require('./ReactRelayQueryRendererContext');\nvar areEqual = require(\"fbjs/lib/areEqual\");\nvar React = require('react');\nvar _require = require('relay-runtime'),\n createOperationDescriptor = _require.createOperationDescriptor,\n deepFreeze = _require.deepFreeze,\n getRequest = _require.getRequest;\nvar requestCache = {};\nvar queryRendererContext = {\n rootIsQueryRenderer: true\n};\nvar ReactRelayQueryRenderer = /*#__PURE__*/function (_React$Component) {\n (0, _inheritsLoose2[\"default\"])(ReactRelayQueryRenderer, _React$Component);\n function ReactRelayQueryRenderer(props) {\n var _this;\n _this = _React$Component.call(this, props) || this;\n (0, _defineProperty2[\"default\"])((0, _assertThisInitialized2[\"default\"])(_this), \"_handleDataChange\", function (params) {\n var error = params.error == null ? null : params.error;\n var snapshot = params.snapshot == null ? null : params.snapshot;\n _this.setState(function (prevState) {\n var prevRequestCacheKey = prevState.requestCacheKey;\n if (prevRequestCacheKey) {\n delete requestCache[prevRequestCacheKey];\n }\n if (snapshot === prevState.snapshot && error === prevState.error) {\n return null;\n }\n return {\n renderProps: getRenderProps(error, snapshot, prevState.queryFetcher, prevState.retryCallbacks),\n snapshot: snapshot,\n requestCacheKey: null\n };\n });\n });\n var retryCallbacks = {\n handleDataChange: null,\n handleRetryAfterError: null\n };\n var queryFetcher;\n var requestCacheKey;\n if (props.query) {\n var query = props.query;\n var request = getRequest(query);\n requestCacheKey = getRequestCacheKey(request.params, props.variables);\n queryFetcher = requestCache[requestCacheKey] ? requestCache[requestCacheKey].queryFetcher : new ReactRelayQueryFetcher();\n } else {\n queryFetcher = new ReactRelayQueryFetcher();\n }\n _this._maybeHiddenOrFastRefresh = false;\n _this.state = (0, _objectSpread2[\"default\"])({\n prevPropsEnvironment: props.environment,\n prevPropsVariables: props.variables,\n prevQuery: props.query,\n queryFetcher: queryFetcher,\n retryCallbacks: retryCallbacks\n }, fetchQueryAndComputeStateFromProps(props, queryFetcher, retryCallbacks, requestCacheKey));\n return _this;\n }\n ReactRelayQueryRenderer.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, prevState) {\n if (prevState.prevQuery !== nextProps.query || prevState.prevPropsEnvironment !== nextProps.environment || !areEqual(prevState.prevPropsVariables, nextProps.variables)) {\n return resetQueryStateForUpdate(nextProps, prevState);\n }\n return null;\n };\n var _proto = ReactRelayQueryRenderer.prototype;\n _proto.componentDidMount = function componentDidMount() {\n var _this2 = this;\n if (this._maybeHiddenOrFastRefresh === true) {\n this._maybeHiddenOrFastRefresh = false;\n this.setState(function (prevState) {\n var newState = resetQueryStateForUpdate(_this2.props, prevState);\n var requestCacheKey = newState.requestCacheKey,\n queryFetcher = newState.queryFetcher;\n if (requestCacheKey != null && requestCache[requestCacheKey] != null) {\n queryFetcher.setOnDataChange(_this2._handleDataChange);\n }\n return newState;\n });\n return;\n }\n var _this$state = this.state,\n retryCallbacks = _this$state.retryCallbacks,\n queryFetcher = _this$state.queryFetcher,\n requestCacheKey = _this$state.requestCacheKey;\n if (requestCacheKey) {\n delete requestCache[requestCacheKey];\n }\n retryCallbacks.handleDataChange = this._handleDataChange;\n retryCallbacks.handleRetryAfterError = function (error) {\n return _this2.setState(function (prevState) {\n var prevRequestCacheKey = prevState.requestCacheKey;\n if (prevRequestCacheKey) {\n delete requestCache[prevRequestCacheKey];\n }\n return {\n renderProps: getLoadingRenderProps(),\n requestCacheKey: null\n };\n });\n };\n if (this.props.query) {\n queryFetcher.setOnDataChange(this._handleDataChange);\n }\n };\n _proto.componentDidUpdate = function componentDidUpdate(_prevProps, prevState) {\n var _this$state2 = this.state,\n queryFetcher = _this$state2.queryFetcher,\n requestCacheKey = _this$state2.requestCacheKey;\n if (requestCacheKey) {\n delete requestCache[requestCacheKey];\n delete this.state.requestCacheKey;\n }\n if (this.props.query && queryFetcher !== prevState.queryFetcher) {\n queryFetcher.setOnDataChange(this._handleDataChange);\n }\n };\n _proto.componentWillUnmount = function componentWillUnmount() {\n this.state.queryFetcher.dispose();\n this._maybeHiddenOrFastRefresh = true;\n };\n _proto.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) {\n return nextProps.render !== this.props.render || nextState.renderProps !== this.state.renderProps;\n };\n _proto.render = function render() {\n var _this$state3 = this.state,\n renderProps = _this$state3.renderProps,\n relayContext = _this$state3.relayContext;\n if (process.env.NODE_ENV !== \"production\") {\n deepFreeze(renderProps);\n }\n return /*#__PURE__*/React.createElement(ReactRelayContext.Provider, {\n value: relayContext\n }, /*#__PURE__*/React.createElement(ReactRelayQueryRendererContext.Provider, {\n value: queryRendererContext\n }, this.props.render(renderProps)));\n };\n return ReactRelayQueryRenderer;\n}(React.Component);\nfunction getLoadingRenderProps() {\n return {\n error: null,\n props: null,\n retry: null\n };\n}\nfunction getEmptyRenderProps() {\n return {\n error: null,\n props: {},\n retry: null\n };\n}\nfunction getRenderProps(error, snapshot, queryFetcher, retryCallbacks) {\n return {\n error: error ? error : null,\n props: snapshot ? snapshot.data : null,\n retry: function retry(cacheConfigOverride) {\n var syncSnapshot = queryFetcher.retry(cacheConfigOverride);\n if (syncSnapshot && typeof retryCallbacks.handleDataChange === 'function') {\n retryCallbacks.handleDataChange({\n snapshot: syncSnapshot\n });\n } else if (error && typeof retryCallbacks.handleRetryAfterError === 'function') {\n retryCallbacks.handleRetryAfterError(error);\n }\n }\n };\n}\nfunction getRequestCacheKey(request, variables) {\n return JSON.stringify({\n id: request.cacheID ? request.cacheID : request.id,\n variables: variables\n });\n}\nfunction resetQueryStateForUpdate(props, prevState) {\n var query = props.query;\n var prevSelectionReferences = prevState.queryFetcher.getSelectionReferences();\n prevState.queryFetcher.disposeRequest();\n var queryFetcher;\n if (query) {\n var request = getRequest(query);\n var requestCacheKey = getRequestCacheKey(request.params, props.variables);\n queryFetcher = requestCache[requestCacheKey] ? requestCache[requestCacheKey].queryFetcher : new ReactRelayQueryFetcher(prevSelectionReferences);\n } else {\n queryFetcher = new ReactRelayQueryFetcher(prevSelectionReferences);\n }\n return (0, _objectSpread2[\"default\"])({\n prevQuery: props.query,\n prevPropsEnvironment: props.environment,\n prevPropsVariables: props.variables,\n queryFetcher: queryFetcher\n }, fetchQueryAndComputeStateFromProps(props, queryFetcher, prevState.retryCallbacks));\n}\nfunction fetchQueryAndComputeStateFromProps(props, queryFetcher, retryCallbacks, requestCacheKey) {\n var environment = props.environment,\n query = props.query,\n variables = props.variables,\n cacheConfig = props.cacheConfig;\n var genericEnvironment = environment;\n if (query) {\n var request = getRequest(query);\n var operation = createOperationDescriptor(request, variables, cacheConfig);\n var relayContext = {\n environment: genericEnvironment\n };\n if (typeof requestCacheKey === 'string' && requestCache[requestCacheKey]) {\n var snapshot = requestCache[requestCacheKey].snapshot;\n if (snapshot) {\n return {\n error: null,\n relayContext: relayContext,\n renderProps: getRenderProps(null, snapshot, queryFetcher, retryCallbacks),\n snapshot: snapshot,\n requestCacheKey: requestCacheKey\n };\n } else {\n return {\n error: null,\n relayContext: relayContext,\n renderProps: getLoadingRenderProps(),\n snapshot: null,\n requestCacheKey: requestCacheKey\n };\n }\n }\n try {\n var storeSnapshot = queryFetcher.lookupInStore(genericEnvironment, operation, props.fetchPolicy);\n var querySnapshot = queryFetcher.fetch({\n environment: genericEnvironment,\n onDataChange: null,\n operation: operation\n });\n var _snapshot = querySnapshot || storeSnapshot;\n requestCacheKey = requestCacheKey || getRequestCacheKey(request.params, props.variables);\n requestCache[requestCacheKey] = {\n queryFetcher: queryFetcher,\n snapshot: _snapshot\n };\n if (!_snapshot) {\n return {\n error: null,\n relayContext: relayContext,\n renderProps: getLoadingRenderProps(),\n snapshot: null,\n requestCacheKey: requestCacheKey\n };\n }\n return {\n error: null,\n relayContext: relayContext,\n renderProps: getRenderProps(null, _snapshot, queryFetcher, retryCallbacks),\n snapshot: _snapshot,\n requestCacheKey: requestCacheKey\n };\n } catch (error) {\n return {\n error: error,\n relayContext: relayContext,\n renderProps: getRenderProps(error, null, queryFetcher, retryCallbacks),\n snapshot: null,\n requestCacheKey: requestCacheKey\n };\n }\n } else {\n queryFetcher.dispose();\n var _relayContext = {\n environment: genericEnvironment\n };\n return {\n error: null,\n relayContext: _relayContext,\n renderProps: getEmptyRenderProps(),\n requestCacheKey: null\n };\n }\n}\nmodule.exports = ReactRelayQueryRenderer;","'use strict';\n\nvar React = require('react');\nmodule.exports = React.createContext({\n rootIsQueryRenderer: false\n});","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\nvar _objectWithoutPropertiesLoose2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectWithoutPropertiesLoose\"));\nvar _objectSpread2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar _assertThisInitialized2 = _interopRequireDefault(require(\"@babel/runtime/helpers/assertThisInitialized\"));\nvar _inheritsLoose2 = _interopRequireDefault(require(\"@babel/runtime/helpers/inheritsLoose\"));\nvar _defineProperty2 = _interopRequireDefault(require(\"@babel/runtime/helpers/defineProperty\"));\nvar _excluded = [\"componentRef\", \"__relayContext\", \"__rootIsQueryRenderer\"];\nvar buildReactRelayContainer = require('./buildReactRelayContainer');\nvar getRootVariablesForFragments = require('./getRootVariablesForFragments');\nvar _require = require('./ReactRelayContainerUtils'),\n getContainerName = _require.getContainerName;\nvar ReactRelayContext = require('./ReactRelayContext');\nvar ReactRelayQueryFetcher = require('./ReactRelayQueryFetcher');\nvar _require2 = require('./RelayContext'),\n assertRelayContext = _require2.assertRelayContext;\nvar areEqual = require(\"fbjs/lib/areEqual\");\nvar React = require('react');\nvar _require3 = require('relay-runtime'),\n Observable = _require3.Observable,\n createFragmentSpecResolver = _require3.createFragmentSpecResolver,\n createOperationDescriptor = _require3.createOperationDescriptor,\n getDataIDsFromObject = _require3.getDataIDsFromObject,\n getRequest = _require3.getRequest,\n getVariablesFromObject = _require3.getVariablesFromObject,\n isScalarAndEqual = _require3.isScalarAndEqual;\nvar warning = require(\"fbjs/lib/warning\");\nfunction createContainerWithFragments(Component, fragments, taggedNode) {\n var _class;\n var containerName = getContainerName(Component);\n return _class = /*#__PURE__*/function (_React$Component) {\n (0, _inheritsLoose2[\"default\"])(_class, _React$Component);\n function _class(props) {\n var _props$__rootIsQueryR, _this;\n _this = _React$Component.call(this, props) || this;\n (0, _defineProperty2[\"default\"])((0, _assertThisInitialized2[\"default\"])(_this), \"_handleFragmentDataUpdate\", function () {\n var resolverFromThisUpdate = _this.state.resolver;\n _this.setState(function (updatedState) {\n return resolverFromThisUpdate === updatedState.resolver ? {\n data: updatedState.resolver.resolve()\n } : null;\n });\n });\n (0, _defineProperty2[\"default\"])((0, _assertThisInitialized2[\"default\"])(_this), \"_refetch\", function (refetchVariables, renderVariables, observerOrCallback, options) {\n if (_this._isUnmounted) {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'ReactRelayRefetchContainer: Unexpected call of `refetch` ' + 'on unmounted container `%s`. It looks like some instances ' + 'of your container still trying to refetch the data but they already ' + 'unmounted. Please make sure you clear all timers, intervals, async ' + 'calls, etc that may trigger `refetch`.', containerName) : void 0;\n return {\n dispose: function dispose() {}\n };\n }\n var _assertRelayContext = assertRelayContext(_this.props.__relayContext),\n environment = _assertRelayContext.environment;\n var rootVariables = getRootVariablesForFragments(fragments, _this.props);\n var fetchVariables = typeof refetchVariables === 'function' ? refetchVariables(_this._getFragmentVariables()) : refetchVariables;\n fetchVariables = (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, rootVariables), fetchVariables);\n var fragmentVariables = renderVariables ? (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, fetchVariables), renderVariables) : fetchVariables;\n var cacheConfig = options ? {\n force: !!options.force\n } : undefined;\n if (cacheConfig != null && (options === null || options === void 0 ? void 0 : options.metadata) != null) {\n cacheConfig.metadata = options === null || options === void 0 ? void 0 : options.metadata;\n }\n var observer = typeof observerOrCallback === 'function' ? {\n next: observerOrCallback,\n error: observerOrCallback\n } : observerOrCallback || {};\n var query = getRequest(taggedNode);\n var operation = createOperationDescriptor(query, fetchVariables, cacheConfig);\n _this.state.localVariables = fetchVariables;\n _this._refetchSubscription && _this._refetchSubscription.unsubscribe();\n var refetchSubscription;\n var storeSnapshot = _this._getQueryFetcher().lookupInStore(environment, operation, options === null || options === void 0 ? void 0 : options.fetchPolicy);\n if (storeSnapshot != null) {\n _this.state.resolver.setVariables(fragmentVariables, operation.request.node);\n _this.setState(function (latestState) {\n return {\n data: latestState.resolver.resolve(),\n contextForChildren: {\n environment: _this.props.__relayContext.environment\n }\n };\n }, function () {\n observer.next && observer.next();\n observer.complete && observer.complete();\n });\n return {\n dispose: function dispose() {}\n };\n }\n _this._getQueryFetcher().execute({\n environment: environment,\n operation: operation,\n preservePreviousReferences: true\n }).mergeMap(function (response) {\n _this.state.resolver.setVariables(fragmentVariables, operation.request.node);\n return Observable.create(function (sink) {\n return _this.setState(function (latestState) {\n return {\n data: latestState.resolver.resolve(),\n contextForChildren: {\n environment: _this.props.__relayContext.environment\n }\n };\n }, function () {\n sink.next();\n sink.complete();\n });\n });\n })[\"finally\"](function () {\n if (_this._refetchSubscription === refetchSubscription) {\n _this._refetchSubscription = null;\n }\n }).subscribe((0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, observer), {}, {\n start: function start(subscription) {\n _this._refetchSubscription = refetchSubscription = subscription;\n observer.start && observer.start(subscription);\n }\n }));\n return {\n dispose: function dispose() {\n refetchSubscription && refetchSubscription.unsubscribe();\n }\n };\n });\n var relayContext = assertRelayContext(props.__relayContext);\n var rootIsQueryRenderer = (_props$__rootIsQueryR = props.__rootIsQueryRenderer) !== null && _props$__rootIsQueryR !== void 0 ? _props$__rootIsQueryR : false;\n _this._refetchSubscription = null;\n var resolver = createFragmentSpecResolver(relayContext, containerName, fragments, props, rootIsQueryRenderer);\n _this.state = {\n data: resolver.resolve(),\n localVariables: null,\n prevProps: props,\n prevPropsContext: relayContext,\n contextForChildren: relayContext,\n relayProp: getRelayProp(relayContext.environment, _this._refetch),\n resolver: resolver\n };\n _this._isUnmounted = false;\n return _this;\n }\n var _proto = _class.prototype;\n _proto.componentDidMount = function componentDidMount() {\n this._isUnmounted = false;\n this._subscribeToNewResolverAndRerenderIfStoreHasChanged();\n };\n _proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {\n if (this.state.resolver !== prevState.resolver) {\n prevState.resolver.dispose();\n this._queryFetcher && this._queryFetcher.dispose();\n this._refetchSubscription && this._refetchSubscription.unsubscribe();\n this._subscribeToNewResolverAndRerenderIfStoreHasChanged();\n } else {\n this._rerenderIfStoreHasChanged();\n }\n };\n _class.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, prevState) {\n var _nextProps$__rootIsQu;\n var prevProps = prevState.prevProps;\n var relayContext = assertRelayContext(nextProps.__relayContext);\n var rootIsQueryRenderer = (_nextProps$__rootIsQu = nextProps.__rootIsQueryRenderer) !== null && _nextProps$__rootIsQu !== void 0 ? _nextProps$__rootIsQu : false;\n var prevIDs = getDataIDsFromObject(fragments, prevProps);\n var nextIDs = getDataIDsFromObject(fragments, nextProps);\n var prevRootVariables = getRootVariablesForFragments(fragments, prevProps);\n var nextRootVariables = getRootVariablesForFragments(fragments, nextProps);\n var resolver = prevState.resolver;\n if (prevState.prevPropsContext.environment !== relayContext.environment || !areEqual(prevRootVariables, nextRootVariables) || !areEqual(prevIDs, nextIDs)) {\n resolver = createFragmentSpecResolver(relayContext, containerName, fragments, nextProps, rootIsQueryRenderer);\n return {\n data: resolver.resolve(),\n localVariables: null,\n prevProps: nextProps,\n prevPropsContext: relayContext,\n contextForChildren: relayContext,\n relayProp: getRelayProp(relayContext.environment, prevState.relayProp.refetch),\n resolver: resolver\n };\n } else if (!prevState.localVariables) {\n resolver.setProps(nextProps);\n }\n var data = resolver.resolve();\n if (data !== prevState.data) {\n return {\n data: data,\n prevProps: nextProps\n };\n }\n return null;\n };\n _proto.componentWillUnmount = function componentWillUnmount() {\n this._isUnmounted = true;\n this.state.resolver.dispose();\n this._queryFetcher && this._queryFetcher.dispose();\n this._refetchSubscription && this._refetchSubscription.unsubscribe();\n };\n _proto.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) {\n if (nextState.data !== this.state.data || nextState.relayProp !== this.state.relayProp) {\n return true;\n }\n var keys = Object.keys(nextProps);\n for (var ii = 0; ii < keys.length; ii++) {\n var key = keys[ii];\n if (key === '__relayContext') {\n if (this.state.prevPropsContext.environment !== nextState.prevPropsContext.environment) {\n return true;\n }\n } else {\n if (!fragments.hasOwnProperty(key) && !isScalarAndEqual(nextProps[key], this.props[key])) {\n return true;\n }\n }\n }\n return false;\n };\n _proto._rerenderIfStoreHasChanged = function _rerenderIfStoreHasChanged() {\n var _this$state = this.state,\n data = _this$state.data,\n resolver = _this$state.resolver;\n var maybeNewData = resolver.resolve();\n if (data !== maybeNewData) {\n this.setState({\n data: maybeNewData\n });\n }\n };\n _proto._subscribeToNewResolverAndRerenderIfStoreHasChanged = function _subscribeToNewResolverAndRerenderIfStoreHasChanged() {\n var _this$state2 = this.state,\n data = _this$state2.data,\n resolver = _this$state2.resolver;\n var maybeNewData = resolver.resolve();\n resolver.setCallback(this.props, this._handleFragmentDataUpdate);\n if (data !== maybeNewData) {\n this.setState({\n data: maybeNewData\n });\n }\n };\n _proto._getFragmentVariables = function _getFragmentVariables() {\n return getVariablesFromObject(fragments, this.props);\n };\n _proto._getQueryFetcher = function _getQueryFetcher() {\n if (!this._queryFetcher) {\n this._queryFetcher = new ReactRelayQueryFetcher();\n }\n return this._queryFetcher;\n };\n _proto.render = function render() {\n var _this$props = this.props,\n componentRef = _this$props.componentRef,\n __relayContext = _this$props.__relayContext,\n __rootIsQueryRenderer = _this$props.__rootIsQueryRenderer,\n props = (0, _objectWithoutPropertiesLoose2[\"default\"])(_this$props, _excluded);\n var _this$state3 = this.state,\n relayProp = _this$state3.relayProp,\n contextForChildren = _this$state3.contextForChildren;\n return /*#__PURE__*/React.createElement(ReactRelayContext.Provider, {\n value: contextForChildren\n }, /*#__PURE__*/React.createElement(Component, (0, _extends2[\"default\"])({}, props, this.state.data, {\n ref: componentRef,\n relay: relayProp\n })));\n };\n return _class;\n }(React.Component), (0, _defineProperty2[\"default\"])(_class, \"displayName\", containerName), _class;\n}\nfunction getRelayProp(environment, refetch) {\n return {\n environment: environment,\n refetch: refetch\n };\n}\nfunction createContainer(Component, fragmentSpec, taggedNode) {\n return buildReactRelayContainer(Component, fragmentSpec, function (ComponentClass, fragments) {\n return createContainerWithFragments(ComponentClass, fragments, taggedNode);\n });\n}\nmodule.exports = {\n createContainer: createContainer\n};","'use strict';\n\nvar isRelayEnvironment = require('./isRelayEnvironment');\nvar invariant = require('invariant');\nfunction assertRelayContext(relay) {\n !isRelayContext(relay) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayContext: Expected `context.relay` to be an object conforming to ' + 'the `RelayContext` interface, got `%s`.', relay) : invariant(false) : void 0;\n return relay;\n}\nfunction isRelayContext(context) {\n return typeof context === 'object' && context !== null && !Array.isArray(context) && isRelayEnvironment(context.environment);\n}\nmodule.exports = {\n assertRelayContext: assertRelayContext,\n isRelayContext: isRelayContext\n};","'use strict';\n\nvar invariant = require('invariant');\nfunction assertFragmentMap(componentName, fragmentSpec) {\n !(fragmentSpec && typeof fragmentSpec === 'object') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Could not create Relay Container for `%s`. ' + 'Expected a set of GraphQL fragments, got `%s` instead.', componentName, fragmentSpec) : invariant(false) : void 0;\n for (var key in fragmentSpec) {\n if (fragmentSpec.hasOwnProperty(key)) {\n var fragment = fragmentSpec[key];\n !(fragment && (typeof fragment === 'object' || typeof fragment === 'function')) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Could not create Relay Container for `%s`. ' + 'The value of fragment `%s` was expected to be a fragment, got `%s` instead.', componentName, key, fragment) : invariant(false) : void 0;\n }\n }\n}\nmodule.exports = assertFragmentMap;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\nvar assertFragmentMap = require('./assertFragmentMap');\nvar _require = require('./ReactRelayContainerUtils'),\n getComponentName = _require.getComponentName,\n getContainerName = _require.getContainerName;\nvar ReactRelayContext = require('./ReactRelayContext');\nvar ReactRelayQueryRendererContext = require('./ReactRelayQueryRendererContext');\nvar invariant = require('invariant');\nvar React = require('react');\nvar _require2 = require('relay-runtime'),\n getFragment = _require2.getFragment;\nvar useContext = React.useContext;\nfunction buildReactRelayContainer(ComponentClass, fragmentSpec, createContainerWithFragments) {\n var containerName = getContainerName(ComponentClass);\n assertFragmentMap(getComponentName(ComponentClass), fragmentSpec);\n var fragments = {};\n for (var key in fragmentSpec) {\n fragments[key] = getFragment(fragmentSpec[key]);\n }\n var Container = createContainerWithFragments(ComponentClass, fragments);\n Container.displayName = containerName;\n function forwardRef(props, ref) {\n var _queryRendererContext;\n var context = useContext(ReactRelayContext);\n !(context != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, '`%s` tried to render a context that was not valid this means that ' + '`%s` was rendered outside of a query renderer.', containerName, containerName) : invariant(false) : void 0;\n var queryRendererContext = useContext(ReactRelayQueryRendererContext);\n return /*#__PURE__*/React.createElement(Container, (0, _extends2[\"default\"])({}, props, {\n __relayContext: context,\n __rootIsQueryRenderer: (_queryRendererContext = queryRendererContext === null || queryRendererContext === void 0 ? void 0 : queryRendererContext.rootIsQueryRenderer) !== null && _queryRendererContext !== void 0 ? _queryRendererContext : false,\n componentRef: props.componentRef || ref\n }));\n }\n forwardRef.displayName = containerName;\n var ForwardContainer = React.forwardRef(forwardRef);\n if (process.env.NODE_ENV !== \"production\") {\n ForwardContainer.__ComponentClass = ComponentClass;\n ForwardContainer.displayName = containerName;\n }\n return ForwardContainer;\n}\nmodule.exports = buildReactRelayContainer;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _objectSpread2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar _require = require('relay-runtime'),\n getSelector = _require.getSelector;\nfunction getRootVariablesForFragments(fragments, props) {\n var rootVariables = {};\n Object.keys(fragments).forEach(function (key) {\n var _selector$selectors$, _selector$selectors$2, _selector$owner$varia;\n var fragmentNode = fragments[key];\n var fragmentRef = props[key];\n var selector = getSelector(fragmentNode, fragmentRef);\n var fragmentOwnerVariables = selector != null && selector.kind === 'PluralReaderSelector' ? (_selector$selectors$ = (_selector$selectors$2 = selector.selectors[0]) === null || _selector$selectors$2 === void 0 ? void 0 : _selector$selectors$2.owner.variables) !== null && _selector$selectors$ !== void 0 ? _selector$selectors$ : {} : (_selector$owner$varia = selector === null || selector === void 0 ? void 0 : selector.owner.variables) !== null && _selector$owner$varia !== void 0 ? _selector$owner$varia : {};\n rootVariables = (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, rootVariables), fragmentOwnerVariables);\n });\n return rootVariables;\n}\nmodule.exports = getRootVariablesForFragments;","'use strict';\n\nvar EntryPointContainer = require('./relay-hooks/EntryPointContainer.react');\nvar loadEntryPoint = require('./relay-hooks/loadEntryPoint');\nvar _require = require('./relay-hooks/loadQuery'),\n loadQuery = _require.loadQuery;\nvar ProfilerContext = require('./relay-hooks/ProfilerContext');\nvar RelayEnvironmentProvider = require('./relay-hooks/RelayEnvironmentProvider');\nvar useEntryPointLoader = require('./relay-hooks/useEntryPointLoader');\nvar useFragment = require('./relay-hooks/useFragment');\nvar useLazyLoadQuery = require('./relay-hooks/useLazyLoadQuery');\nvar useMutation = require('./relay-hooks/useMutation');\nvar usePaginationFragment = require('./relay-hooks/usePaginationFragment');\nvar usePreloadedQuery = require('./relay-hooks/usePreloadedQuery');\nvar useQueryLoader = require('./relay-hooks/useQueryLoader');\nvar useRefetchableFragment = require('./relay-hooks/useRefetchableFragment');\nvar useRelayEnvironment = require('./relay-hooks/useRelayEnvironment');\nvar useSubscribeToInvalidationState = require('./relay-hooks/useSubscribeToInvalidationState');\nvar useSubscription = require('./relay-hooks/useSubscription');\nvar RelayRuntime = require('relay-runtime');\nmodule.exports = {\n ConnectionHandler: RelayRuntime.ConnectionHandler,\n applyOptimisticMutation: RelayRuntime.applyOptimisticMutation,\n commitLocalUpdate: RelayRuntime.commitLocalUpdate,\n commitMutation: RelayRuntime.commitMutation,\n graphql: RelayRuntime.graphql,\n readInlineData: RelayRuntime.readInlineData,\n requestSubscription: RelayRuntime.requestSubscription,\n EntryPointContainer: EntryPointContainer,\n RelayEnvironmentProvider: RelayEnvironmentProvider,\n ProfilerContext: ProfilerContext,\n fetchQuery: RelayRuntime.fetchQuery,\n loadQuery: loadQuery,\n loadEntryPoint: loadEntryPoint,\n useFragment: useFragment,\n useLazyLoadQuery: useLazyLoadQuery,\n useEntryPointLoader: useEntryPointLoader,\n useQueryLoader: useQueryLoader,\n useMutation: useMutation,\n usePaginationFragment: usePaginationFragment,\n usePreloadedQuery: usePreloadedQuery,\n useRefetchableFragment: useRefetchableFragment,\n useRelayEnvironment: useRelayEnvironment,\n useSubscribeToInvalidationState: useSubscribeToInvalidationState,\n useSubscription: useSubscription\n};","'use strict';\n\nvar ReactRelayContext = require('./ReactRelayContext');\nvar ReactRelayFragmentContainer = require('./ReactRelayFragmentContainer');\nvar ReactRelayLocalQueryRenderer = require('./ReactRelayLocalQueryRenderer');\nvar ReactRelayPaginationContainer = require('./ReactRelayPaginationContainer');\nvar ReactRelayQueryRenderer = require('./ReactRelayQueryRenderer');\nvar ReactRelayRefetchContainer = require('./ReactRelayRefetchContainer');\nvar EntryPointContainer = require('./relay-hooks/EntryPointContainer.react');\nvar loadEntryPoint = require('./relay-hooks/loadEntryPoint');\nvar _require = require('./relay-hooks/loadQuery'),\n loadQuery = _require.loadQuery;\nvar ProfilerContext = require('./relay-hooks/ProfilerContext');\nvar RelayEnvironmentProvider = require('./relay-hooks/RelayEnvironmentProvider');\nvar useClientQuery = require('./relay-hooks/useClientQuery');\nvar useEntryPointLoader = require('./relay-hooks/useEntryPointLoader');\nvar useFragment = require('./relay-hooks/useFragment');\nvar useLazyLoadQuery = require('./relay-hooks/useLazyLoadQuery');\nvar useMutation = require('./relay-hooks/useMutation');\nvar usePaginationFragment = require('./relay-hooks/usePaginationFragment');\nvar usePreloadedQuery = require('./relay-hooks/usePreloadedQuery');\nvar useQueryLoader = require('./relay-hooks/useQueryLoader');\nvar useRefetchableFragment = require('./relay-hooks/useRefetchableFragment');\nvar useRelayEnvironment = require('./relay-hooks/useRelayEnvironment');\nvar useSubscribeToInvalidationState = require('./relay-hooks/useSubscribeToInvalidationState');\nvar useSubscription = require('./relay-hooks/useSubscription');\nvar RelayRuntime = require('relay-runtime');\nmodule.exports = {\n ConnectionHandler: RelayRuntime.ConnectionHandler,\n QueryRenderer: ReactRelayQueryRenderer,\n LocalQueryRenderer: ReactRelayLocalQueryRenderer,\n MutationTypes: RelayRuntime.MutationTypes,\n RangeOperations: RelayRuntime.RangeOperations,\n ReactRelayContext: ReactRelayContext,\n applyOptimisticMutation: RelayRuntime.applyOptimisticMutation,\n commitLocalUpdate: RelayRuntime.commitLocalUpdate,\n commitMutation: RelayRuntime.commitMutation,\n createFragmentContainer: ReactRelayFragmentContainer.createContainer,\n createPaginationContainer: ReactRelayPaginationContainer.createContainer,\n createRefetchContainer: ReactRelayRefetchContainer.createContainer,\n fetchQuery_DEPRECATED: RelayRuntime.fetchQuery_DEPRECATED,\n graphql: RelayRuntime.graphql,\n readInlineData: RelayRuntime.readInlineData,\n requestSubscription: RelayRuntime.requestSubscription,\n EntryPointContainer: EntryPointContainer,\n RelayEnvironmentProvider: RelayEnvironmentProvider,\n ProfilerContext: ProfilerContext,\n fetchQuery: RelayRuntime.fetchQuery,\n loadQuery: loadQuery,\n loadEntryPoint: loadEntryPoint,\n useClientQuery: useClientQuery,\n useFragment: useFragment,\n useLazyLoadQuery: useLazyLoadQuery,\n useEntryPointLoader: useEntryPointLoader,\n useQueryLoader: useQueryLoader,\n useMutation: useMutation,\n usePaginationFragment: usePaginationFragment,\n usePreloadedQuery: usePreloadedQuery,\n useRefetchableFragment: useRefetchableFragment,\n useRelayEnvironment: useRelayEnvironment,\n useSubscribeToInvalidationState: useSubscribeToInvalidationState,\n useSubscription: useSubscription\n};","'use strict';\n\nfunction isRelayEnvironment(environment) {\n return typeof environment === 'object' && environment !== null && typeof environment.check === 'function' && typeof environment.lookup === 'function' && typeof environment.retain === 'function' && typeof environment.execute === 'function' && typeof environment.subscribe === 'function';\n}\nmodule.exports = isRelayEnvironment;","'use strict';\n\nvar ProfilerContext = require('./ProfilerContext');\nvar useRelayEnvironment = require('./useRelayEnvironment');\nvar React = require('react');\nvar _require = require('react'),\n useContext = _require.useContext,\n useEffect = _require.useEffect;\nvar warning = require(\"fbjs/lib/warning\");\nfunction EntryPointContainer(_ref) {\n var entryPointReference = _ref.entryPointReference,\n props = _ref.props;\n process.env.NODE_ENV !== \"production\" ? warning(entryPointReference.isDisposed === false, ': Expected entryPointReference to not be disposed ' + 'yet. This is because disposing the entrypoint marks it for future garbage ' + 'collection, and as such may no longer be present in the Relay store. ' + 'In the future, this will become a hard error.') : void 0;\n var getComponent = entryPointReference.getComponent,\n queries = entryPointReference.queries,\n entryPoints = entryPointReference.entryPoints,\n extraProps = entryPointReference.extraProps,\n rootModuleID = entryPointReference.rootModuleID;\n var Component = getComponent();\n var profilerContext = useContext(ProfilerContext);\n var environment = useRelayEnvironment();\n useEffect(function () {\n environment.__log({\n name: 'entrypoint.root.consume',\n profilerContext: profilerContext,\n rootModuleID: rootModuleID\n });\n }, [environment, profilerContext, rootModuleID]);\n return /*#__PURE__*/React.createElement(Component, {\n entryPoints: entryPoints,\n extraProps: extraProps,\n props: props,\n queries: queries\n });\n}\nmodule.exports = EntryPointContainer;","'use strict';\n\nvar warning = require(\"fbjs/lib/warning\");\nvar implementation = null;\nfunction inject(impl) {\n process.env.NODE_ENV !== \"production\" ? warning(implementation === null, 'Relay HooksImplementation was injected twice.') : void 0;\n implementation = impl;\n}\nfunction get() {\n return implementation;\n}\nmodule.exports = {\n inject: inject,\n get: get\n};","'use strict';\n\nvar invariant = require('invariant');\nvar LRUCache = /*#__PURE__*/function () {\n function LRUCache(capacity) {\n this._capacity = capacity;\n !(this._capacity > 0) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'LRUCache: Unable to create instance of cache with zero or negative capacity.') : invariant(false) : void 0;\n this._map = new Map();\n }\n var _proto = LRUCache.prototype;\n _proto.set = function set(key, value) {\n this._map[\"delete\"](key);\n this._map.set(key, value);\n if (this._map.size > this._capacity) {\n var firstKey = this._map.keys().next();\n if (!firstKey.done) {\n this._map[\"delete\"](firstKey.value);\n }\n }\n };\n _proto.get = function get(key) {\n var value = this._map.get(key);\n if (value != null) {\n this._map[\"delete\"](key);\n this._map.set(key, value);\n }\n return value;\n };\n _proto.has = function has(key) {\n return this._map.has(key);\n };\n _proto[\"delete\"] = function _delete(key) {\n this._map[\"delete\"](key);\n };\n _proto.size = function size() {\n return this._map.size;\n };\n _proto.capacity = function capacity() {\n return this._capacity - this._map.size;\n };\n _proto.clear = function clear() {\n this._map.clear();\n };\n return LRUCache;\n}();\nfunction create(capacity) {\n return new LRUCache(capacity);\n}\nmodule.exports = {\n create: create\n};","'use strict';\n\nvar React = require('react');\nvar ProfilerContext = React.createContext({\n wrapPrepareQueryResource: function wrapPrepareQueryResource(cb) {\n return cb();\n }\n});\nmodule.exports = ProfilerContext;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _objectSpread2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar _defineProperty2 = _interopRequireDefault(require(\"@babel/runtime/helpers/defineProperty\"));\nvar LRUCache = require('./LRUCache');\nvar SuspenseResource = require('./SuspenseResource');\nvar invariant = require('invariant');\nvar _require = require('relay-runtime'),\n isPromise = _require.isPromise;\nvar warning = require(\"fbjs/lib/warning\");\nvar CACHE_CAPACITY = 1000;\nvar DEFAULT_FETCH_POLICY = 'store-or-network';\nvar DEFAULT_LIVE_FETCH_POLICY = 'store-and-network';\nvar WEAKMAP_SUPPORTED = typeof WeakMap === 'function';\nfunction operationIsLiveQuery(operation) {\n return operation.request.node.params.metadata.live !== undefined;\n}\nfunction getQueryCacheIdentifier(environment, operation, maybeFetchPolicy, maybeRenderPolicy, cacheBreaker) {\n var fetchPolicy = maybeFetchPolicy !== null && maybeFetchPolicy !== void 0 ? maybeFetchPolicy : operationIsLiveQuery(operation) ? DEFAULT_LIVE_FETCH_POLICY : DEFAULT_FETCH_POLICY;\n var renderPolicy = maybeRenderPolicy !== null && maybeRenderPolicy !== void 0 ? maybeRenderPolicy : environment.UNSTABLE_getDefaultRenderPolicy();\n var cacheIdentifier = \"\".concat(fetchPolicy, \"-\").concat(renderPolicy, \"-\").concat(operation.request.identifier);\n if (cacheBreaker != null) {\n return \"\".concat(cacheIdentifier, \"-\").concat(cacheBreaker);\n }\n return cacheIdentifier;\n}\nfunction getQueryResult(operation, cacheIdentifier) {\n var rootFragmentRef = {\n __id: operation.fragment.dataID,\n __fragments: (0, _defineProperty2[\"default\"])({}, operation.fragment.node.name, operation.request.variables),\n __fragmentOwner: operation.request\n };\n return {\n cacheIdentifier: cacheIdentifier,\n fragmentNode: operation.request.node.fragment,\n fragmentRef: rootFragmentRef,\n operation: operation\n };\n}\nvar nextID = 200000;\nfunction createCacheEntry(cacheIdentifier, operation, operationAvailability, value, networkSubscription, onDispose) {\n var isLiveQuery = operationIsLiveQuery(operation);\n var currentValue = value;\n var currentNetworkSubscription = networkSubscription;\n var suspenseResource = new SuspenseResource(function (environment) {\n var retention = environment.retain(operation);\n return {\n dispose: function dispose() {\n if (isLiveQuery && currentNetworkSubscription != null) {\n currentNetworkSubscription.unsubscribe();\n }\n retention.dispose();\n onDispose(cacheEntry);\n }\n };\n });\n var cacheEntry = {\n cacheIdentifier: cacheIdentifier,\n id: nextID++,\n processedPayloadsCount: 0,\n operationAvailability: operationAvailability,\n getValue: function getValue() {\n return currentValue;\n },\n setValue: function setValue(val) {\n currentValue = val;\n },\n setNetworkSubscription: function setNetworkSubscription(subscription) {\n if (isLiveQuery && currentNetworkSubscription != null) {\n currentNetworkSubscription.unsubscribe();\n }\n currentNetworkSubscription = subscription;\n },\n temporaryRetain: function temporaryRetain(environment) {\n return suspenseResource.temporaryRetain(environment);\n },\n permanentRetain: function permanentRetain(environment) {\n return suspenseResource.permanentRetain(environment);\n },\n releaseTemporaryRetain: function releaseTemporaryRetain() {\n suspenseResource.releaseTemporaryRetain();\n }\n };\n return cacheEntry;\n}\nvar QueryResourceImpl = /*#__PURE__*/function () {\n function QueryResourceImpl(environment) {\n var _this = this;\n (0, _defineProperty2[\"default\"])(this, \"_clearCacheEntry\", function (cacheEntry) {\n _this._cache[\"delete\"](cacheEntry.cacheIdentifier);\n });\n this._environment = environment;\n this._cache = LRUCache.create(CACHE_CAPACITY);\n }\n var _proto = QueryResourceImpl.prototype;\n _proto.prepare = function prepare(operation, fetchObservable, maybeFetchPolicy, maybeRenderPolicy, observer, cacheBreaker, profilerContext) {\n var cacheIdentifier = getQueryCacheIdentifier(this._environment, operation, maybeFetchPolicy, maybeRenderPolicy, cacheBreaker);\n return this.prepareWithIdentifier(cacheIdentifier, operation, fetchObservable, maybeFetchPolicy, maybeRenderPolicy, observer, profilerContext);\n };\n _proto.prepareWithIdentifier = function prepareWithIdentifier(cacheIdentifier, operation, fetchObservable, maybeFetchPolicy, maybeRenderPolicy, observer, profilerContext) {\n var environment = this._environment;\n var fetchPolicy = maybeFetchPolicy !== null && maybeFetchPolicy !== void 0 ? maybeFetchPolicy : operationIsLiveQuery(operation) ? DEFAULT_LIVE_FETCH_POLICY : DEFAULT_FETCH_POLICY;\n var renderPolicy = maybeRenderPolicy !== null && maybeRenderPolicy !== void 0 ? maybeRenderPolicy : environment.UNSTABLE_getDefaultRenderPolicy();\n var cacheEntry = this._cache.get(cacheIdentifier);\n var temporaryRetainDisposable = null;\n var entryWasCached = cacheEntry != null;\n if (cacheEntry == null) {\n cacheEntry = this._fetchAndSaveQuery(cacheIdentifier, operation, fetchObservable, fetchPolicy, renderPolicy, profilerContext, (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, observer), {}, {\n unsubscribe: function unsubscribe(subscription) {\n if (temporaryRetainDisposable != null) {\n temporaryRetainDisposable.dispose();\n }\n var observerUnsubscribe = observer === null || observer === void 0 ? void 0 : observer.unsubscribe;\n observerUnsubscribe && observerUnsubscribe(subscription);\n }\n }));\n }\n temporaryRetainDisposable = cacheEntry.temporaryRetain(environment);\n var cachedValue = cacheEntry.getValue();\n if (isPromise(cachedValue)) {\n environment.__log({\n name: 'suspense.query',\n fetchPolicy: fetchPolicy,\n isPromiseCached: entryWasCached,\n operation: operation,\n queryAvailability: cacheEntry.operationAvailability,\n renderPolicy: renderPolicy\n });\n throw cachedValue;\n }\n if (cachedValue instanceof Error) {\n throw cachedValue;\n }\n return cachedValue;\n };\n _proto.retain = function retain(queryResult, profilerContext) {\n var environment = this._environment;\n var cacheIdentifier = queryResult.cacheIdentifier,\n operation = queryResult.operation;\n var cacheEntry = this._getOrCreateCacheEntry(cacheIdentifier, operation, null, queryResult, null);\n var disposable = cacheEntry.permanentRetain(environment);\n environment.__log({\n name: 'queryresource.retain',\n profilerContext: profilerContext,\n resourceID: cacheEntry.id\n });\n return {\n dispose: function dispose() {\n disposable.dispose();\n }\n };\n };\n _proto.releaseTemporaryRetain = function releaseTemporaryRetain(queryResult) {\n var cacheEntry = this._cache.get(queryResult.cacheIdentifier);\n if (cacheEntry != null) {\n cacheEntry.releaseTemporaryRetain();\n }\n };\n _proto.TESTS_ONLY__getCacheEntry = function TESTS_ONLY__getCacheEntry(operation, maybeFetchPolicy, maybeRenderPolicy, cacheBreaker) {\n var environment = this._environment;\n var cacheIdentifier = getQueryCacheIdentifier(environment, operation, maybeFetchPolicy, maybeRenderPolicy, cacheBreaker);\n return this._cache.get(cacheIdentifier);\n };\n _proto._getOrCreateCacheEntry = function _getOrCreateCacheEntry(cacheIdentifier, operation, operationAvailability, value, networkSubscription) {\n var cacheEntry = this._cache.get(cacheIdentifier);\n if (cacheEntry == null) {\n cacheEntry = createCacheEntry(cacheIdentifier, operation, operationAvailability, value, networkSubscription, this._clearCacheEntry);\n this._cache.set(cacheIdentifier, cacheEntry);\n }\n return cacheEntry;\n };\n _proto._fetchAndSaveQuery = function _fetchAndSaveQuery(cacheIdentifier, operation, fetchObservable, fetchPolicy, renderPolicy, profilerContext, observer) {\n var _this2 = this;\n var environment = this._environment;\n var queryAvailability = environment.check(operation);\n var queryStatus = queryAvailability.status;\n var hasFullQuery = queryStatus === 'available';\n var canPartialRender = hasFullQuery || renderPolicy === 'partial' && queryStatus !== 'stale';\n var shouldFetch;\n var shouldAllowRender;\n var resolveNetworkPromise = function resolveNetworkPromise() {};\n switch (fetchPolicy) {\n case 'store-only':\n {\n shouldFetch = false;\n shouldAllowRender = true;\n break;\n }\n case 'store-or-network':\n {\n shouldFetch = !hasFullQuery;\n shouldAllowRender = canPartialRender;\n break;\n }\n case 'store-and-network':\n {\n shouldFetch = true;\n shouldAllowRender = canPartialRender;\n break;\n }\n case 'network-only':\n default:\n {\n shouldFetch = true;\n shouldAllowRender = false;\n break;\n }\n }\n if (shouldAllowRender) {\n var queryResult = getQueryResult(operation, cacheIdentifier);\n var _cacheEntry = createCacheEntry(cacheIdentifier, operation, queryAvailability, queryResult, null, this._clearCacheEntry);\n this._cache.set(cacheIdentifier, _cacheEntry);\n }\n if (shouldFetch) {\n var _queryResult = getQueryResult(operation, cacheIdentifier);\n var networkSubscription;\n fetchObservable.subscribe({\n start: function start(subscription) {\n networkSubscription = subscription;\n var cacheEntry = _this2._cache.get(cacheIdentifier);\n if (cacheEntry) {\n cacheEntry.setNetworkSubscription(networkSubscription);\n }\n var observerStart = observer === null || observer === void 0 ? void 0 : observer.start;\n if (observerStart) {\n var subscriptionWithConditionalCancelation = (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, subscription), {}, {\n unsubscribe: function unsubscribe() {\n if (operationIsLiveQuery(operation)) {\n subscription.unsubscribe();\n }\n }\n });\n observerStart(subscriptionWithConditionalCancelation);\n }\n },\n next: function next() {\n var cacheEntry = _this2._getOrCreateCacheEntry(cacheIdentifier, operation, queryAvailability, _queryResult, networkSubscription);\n cacheEntry.processedPayloadsCount += 1;\n cacheEntry.setValue(_queryResult);\n resolveNetworkPromise();\n var observerNext = observer === null || observer === void 0 ? void 0 : observer.next;\n if (observerNext != null) {\n var snapshot = environment.lookup(operation.fragment);\n observerNext(snapshot);\n }\n },\n error: function error(_error) {\n var cacheEntry = _this2._getOrCreateCacheEntry(cacheIdentifier, operation, queryAvailability, _error, networkSubscription);\n if (cacheEntry.processedPayloadsCount === 0) {\n cacheEntry.setValue(_error);\n } else {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'QueryResource: An incremental payload for query `%s` returned an error: `%s`.', operation.fragment.node.name, String(_error.message)) : void 0;\n }\n resolveNetworkPromise();\n networkSubscription = null;\n cacheEntry.setNetworkSubscription(null);\n var observerError = observer === null || observer === void 0 ? void 0 : observer.error;\n observerError && observerError(_error);\n },\n complete: function complete() {\n resolveNetworkPromise();\n networkSubscription = null;\n var cacheEntry = _this2._cache.get(cacheIdentifier);\n if (cacheEntry) {\n cacheEntry.setNetworkSubscription(null);\n }\n var observerComplete = observer === null || observer === void 0 ? void 0 : observer.complete;\n observerComplete && observerComplete();\n },\n unsubscribe: observer === null || observer === void 0 ? void 0 : observer.unsubscribe\n });\n var _cacheEntry2 = this._cache.get(cacheIdentifier);\n if (!_cacheEntry2) {\n var networkPromise = new Promise(function (resolve) {\n resolveNetworkPromise = resolve;\n });\n networkPromise.displayName = 'Relay(' + operation.fragment.node.name + ')';\n _cacheEntry2 = createCacheEntry(cacheIdentifier, operation, queryAvailability, networkPromise, networkSubscription, this._clearCacheEntry);\n this._cache.set(cacheIdentifier, _cacheEntry2);\n }\n } else {\n var observerComplete = observer === null || observer === void 0 ? void 0 : observer.complete;\n observerComplete && observerComplete();\n }\n var cacheEntry = this._cache.get(cacheIdentifier);\n !(cacheEntry != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: Expected to have cached a result when attempting to fetch query.' + \"If you're seeing this, this is likely a bug in Relay.\") : invariant(false) : void 0;\n environment.__log({\n name: 'queryresource.fetch',\n resourceID: cacheEntry.id,\n operation: operation,\n profilerContext: profilerContext,\n fetchPolicy: fetchPolicy,\n renderPolicy: renderPolicy,\n queryAvailability: queryAvailability,\n shouldFetch: shouldFetch\n });\n return cacheEntry;\n };\n return QueryResourceImpl;\n}();\nfunction createQueryResource(environment) {\n return new QueryResourceImpl(environment);\n}\nvar dataResources = WEAKMAP_SUPPORTED ? new WeakMap() : new Map();\nfunction getQueryResourceForEnvironment(environment) {\n var cached = dataResources.get(environment);\n if (cached) {\n return cached;\n }\n var newDataResource = createQueryResource(environment);\n dataResources.set(environment, newDataResource);\n return newDataResource;\n}\nmodule.exports = {\n createQueryResource: createQueryResource,\n getQueryResourceForEnvironment: getQueryResourceForEnvironment,\n getQueryCacheIdentifier: getQueryCacheIdentifier\n};","'use strict';\n\nvar ReactRelayContext = require('./../ReactRelayContext');\nvar React = require('react');\nvar useMemo = React.useMemo;\nfunction RelayEnvironmentProvider(props) {\n var children = props.children,\n environment = props.environment,\n getEnvironmentForActor = props.getEnvironmentForActor;\n var context = useMemo(function () {\n return {\n environment: environment,\n getEnvironmentForActor: getEnvironmentForActor\n };\n }, [environment, getEnvironmentForActor]);\n return /*#__PURE__*/React.createElement(ReactRelayContext.Provider, {\n value: context\n }, children);\n}\nmodule.exports = RelayEnvironmentProvider;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _defineProperty2 = _interopRequireDefault(require(\"@babel/runtime/helpers/defineProperty\"));\nvar warning = require(\"fbjs/lib/warning\");\nvar TEMPORARY_RETAIN_DURATION_MS = 5 * 60 * 1000;\nvar SuspenseResource = /*#__PURE__*/function () {\n function SuspenseResource(retain) {\n var _this = this;\n (0, _defineProperty2[\"default\"])(this, \"_retainCount\", 0);\n (0, _defineProperty2[\"default\"])(this, \"_retainDisposable\", null);\n (0, _defineProperty2[\"default\"])(this, \"_releaseTemporaryRetain\", null);\n this._retain = function (environment) {\n _this._retainCount++;\n if (_this._retainCount === 1) {\n _this._retainDisposable = retain(environment);\n }\n return {\n dispose: function dispose() {\n _this._retainCount = Math.max(0, _this._retainCount - 1);\n if (_this._retainCount === 0) {\n if (_this._retainDisposable != null) {\n _this._retainDisposable.dispose();\n _this._retainDisposable = null;\n } else {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'Relay: Expected disposable to release query to be defined.' + \"If you're seeing this, this is likely a bug in Relay.\") : void 0;\n }\n }\n }\n };\n };\n }\n var _proto = SuspenseResource.prototype;\n _proto.temporaryRetain = function temporaryRetain(environment) {\n var _this2 = this;\n var _this$_releaseTempora;\n if (environment.isServer()) {\n return {\n dispose: function dispose() {}\n };\n }\n var retention = this._retain(environment);\n var releaseQueryTimeout = null;\n var releaseTemporaryRetain = function releaseTemporaryRetain() {\n clearTimeout(releaseQueryTimeout);\n releaseQueryTimeout = null;\n _this2._releaseTemporaryRetain = null;\n retention.dispose();\n };\n releaseQueryTimeout = setTimeout(releaseTemporaryRetain, TEMPORARY_RETAIN_DURATION_MS);\n (_this$_releaseTempora = this._releaseTemporaryRetain) === null || _this$_releaseTempora === void 0 ? void 0 : _this$_releaseTempora.call(this);\n this._releaseTemporaryRetain = releaseTemporaryRetain;\n return {\n dispose: function dispose() {\n var _this$_releaseTempora2;\n (_this$_releaseTempora2 = _this2._releaseTemporaryRetain) === null || _this$_releaseTempora2 === void 0 ? void 0 : _this$_releaseTempora2.call(_this2);\n }\n };\n };\n _proto.permanentRetain = function permanentRetain(environment) {\n var disposable = this._retain(environment);\n this.releaseTemporaryRetain();\n return disposable;\n };\n _proto.releaseTemporaryRetain = function releaseTemporaryRetain() {\n var _this$_releaseTempora3;\n (_this$_releaseTempora3 = this._releaseTemporaryRetain) === null || _this$_releaseTempora3 === void 0 ? void 0 : _this$_releaseTempora3.call(this);\n this._releaseTemporaryRetain = null;\n };\n _proto.getRetainCount = function getRetainCount() {\n return this._retainCount;\n };\n return SuspenseResource;\n}();\nmodule.exports = SuspenseResource;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _objectSpread2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar _defineProperty2 = _interopRequireDefault(require(\"@babel/runtime/helpers/defineProperty\"));\nvar _toConsumableArray2 = _interopRequireDefault(require(\"@babel/runtime/helpers/toConsumableArray\"));\nvar LRUCache = require('../LRUCache');\nvar _require = require('../QueryResource'),\n getQueryResourceForEnvironment = _require.getQueryResourceForEnvironment;\nvar SuspenseResource = require('../SuspenseResource');\nvar invariant = require('invariant');\nvar _require2 = require('relay-runtime'),\n _require2$__internal = _require2.__internal,\n fetchQuery = _require2$__internal.fetchQuery,\n getPromiseForActiveRequest = _require2$__internal.getPromiseForActiveRequest,\n RelayFeatureFlags = _require2.RelayFeatureFlags,\n createOperationDescriptor = _require2.createOperationDescriptor,\n getFragmentIdentifier = _require2.getFragmentIdentifier,\n getPendingOperationsForFragment = _require2.getPendingOperationsForFragment,\n getSelector = _require2.getSelector,\n getVariablesFromFragment = _require2.getVariablesFromFragment,\n handlePotentialSnapshotErrors = _require2.handlePotentialSnapshotErrors,\n isPromise = _require2.isPromise,\n recycleNodesInto = _require2.recycleNodesInto;\nvar WEAKMAP_SUPPORTED = typeof WeakMap === 'function';\nvar CACHE_CAPACITY = 1000000;\nvar CONSTANT_READONLY_EMPTY_ARRAY = Object.freeze([]);\nfunction isMissingData(snapshot) {\n if (Array.isArray(snapshot)) {\n return snapshot.some(function (s) {\n return s.isMissingData;\n });\n }\n return snapshot.isMissingData;\n}\nfunction hasMissingClientEdges(snapshot) {\n var _snapshot$missingClie, _snapshot$missingClie2;\n if (Array.isArray(snapshot)) {\n return snapshot.some(function (s) {\n var _s$missingClientEdges, _s$missingClientEdges2;\n return ((_s$missingClientEdges = (_s$missingClientEdges2 = s.missingClientEdges) === null || _s$missingClientEdges2 === void 0 ? void 0 : _s$missingClientEdges2.length) !== null && _s$missingClientEdges !== void 0 ? _s$missingClientEdges : 0) > 0;\n });\n }\n return ((_snapshot$missingClie = (_snapshot$missingClie2 = snapshot.missingClientEdges) === null || _snapshot$missingClie2 === void 0 ? void 0 : _snapshot$missingClie2.length) !== null && _snapshot$missingClie !== void 0 ? _snapshot$missingClie : 0) > 0;\n}\nfunction missingLiveResolverFields(snapshot) {\n if (Array.isArray(snapshot)) {\n return snapshot.map(function (s) {\n return s.missingLiveResolverFields;\n }).filter(Boolean).flat();\n }\n return snapshot.missingLiveResolverFields;\n}\nfunction singularOrPluralForEach(snapshot, f) {\n if (Array.isArray(snapshot)) {\n snapshot.forEach(f);\n } else {\n f(snapshot);\n }\n}\nfunction getFragmentResult(cacheKey, snapshot, storeEpoch) {\n if (Array.isArray(snapshot)) {\n return {\n cacheKey: cacheKey,\n snapshot: snapshot,\n data: snapshot.map(function (s) {\n return s.data;\n }),\n isMissingData: isMissingData(snapshot),\n storeEpoch: storeEpoch\n };\n }\n return {\n cacheKey: cacheKey,\n snapshot: snapshot,\n data: snapshot.data,\n isMissingData: isMissingData(snapshot),\n storeEpoch: storeEpoch\n };\n}\nvar ClientEdgeQueryResultsCache = /*#__PURE__*/function () {\n function ClientEdgeQueryResultsCache(environment) {\n (0, _defineProperty2[\"default\"])(this, \"_cache\", new Map());\n (0, _defineProperty2[\"default\"])(this, \"_retainCounts\", new Map());\n this._environment = environment;\n }\n var _proto = ClientEdgeQueryResultsCache.prototype;\n _proto.get = function get(fragmentIdentifier) {\n var _this$_cache$get$, _this$_cache$get;\n return (_this$_cache$get$ = (_this$_cache$get = this._cache.get(fragmentIdentifier)) === null || _this$_cache$get === void 0 ? void 0 : _this$_cache$get[0]) !== null && _this$_cache$get$ !== void 0 ? _this$_cache$get$ : undefined;\n };\n _proto.recordQueryResults = function recordQueryResults(fragmentIdentifier, value) {\n var _this = this;\n var existing = this._cache.get(fragmentIdentifier);\n if (!existing) {\n var suspenseResource = new SuspenseResource(function () {\n return _this._retain(fragmentIdentifier);\n });\n this._cache.set(fragmentIdentifier, [value, suspenseResource]);\n suspenseResource.temporaryRetain(this._environment);\n } else {\n var existingResults = existing[0],\n _suspenseResource = existing[1];\n value.forEach(function (queryResult) {\n existingResults.push(queryResult);\n });\n _suspenseResource.temporaryRetain(this._environment);\n }\n };\n _proto._retain = function _retain(id) {\n var _this2 = this;\n var _this$_retainCounts$g;\n var retainCount = ((_this$_retainCounts$g = this._retainCounts.get(id)) !== null && _this$_retainCounts$g !== void 0 ? _this$_retainCounts$g : 0) + 1;\n this._retainCounts.set(id, retainCount);\n return {\n dispose: function dispose() {\n var _this$_retainCounts$g2;\n var newRetainCount = ((_this$_retainCounts$g2 = _this2._retainCounts.get(id)) !== null && _this$_retainCounts$g2 !== void 0 ? _this$_retainCounts$g2 : 0) - 1;\n if (newRetainCount > 0) {\n _this2._retainCounts.set(id, newRetainCount);\n } else {\n _this2._retainCounts[\"delete\"](id);\n _this2._cache[\"delete\"](id);\n }\n }\n };\n };\n return ClientEdgeQueryResultsCache;\n}();\nvar FragmentResourceImpl = /*#__PURE__*/function () {\n function FragmentResourceImpl(environment) {\n this._environment = environment;\n this._cache = LRUCache.create(CACHE_CAPACITY);\n if (RelayFeatureFlags.ENABLE_CLIENT_EDGES) {\n this._clientEdgeQueryResultsCache = new ClientEdgeQueryResultsCache(environment);\n }\n }\n var _proto2 = FragmentResourceImpl.prototype;\n _proto2.read = function read(fragmentNode, fragmentRef, componentDisplayName, fragmentKey) {\n return this.readWithIdentifier(fragmentNode, fragmentRef, getFragmentIdentifier(fragmentNode, fragmentRef), componentDisplayName, fragmentKey);\n };\n _proto2.readWithIdentifier = function readWithIdentifier(fragmentNode, fragmentRef, fragmentIdentifier, componentDisplayName, fragmentKey) {\n var _this3 = this;\n var _fragmentNode$metadat, _fragmentNode$metadat2, _missingLiveResolverF2, _missingLiveResolverF3;\n var environment = this._environment;\n if (fragmentRef == null) {\n return {\n cacheKey: fragmentIdentifier,\n data: null,\n isMissingData: false,\n snapshot: null,\n storeEpoch: 0\n };\n }\n var storeEpoch = environment.getStore().getEpoch();\n if ((fragmentNode === null || fragmentNode === void 0 ? void 0 : (_fragmentNode$metadat = fragmentNode.metadata) === null || _fragmentNode$metadat === void 0 ? void 0 : _fragmentNode$metadat.plural) === true) {\n !Array.isArray(fragmentRef) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: Expected fragment pointer%s for fragment `%s` to be ' + 'an array, instead got `%s`. Remove `@relay(plural: true)` ' + 'from fragment `%s` to allow the prop to be an object.', fragmentKey != null ? \" for key `\".concat(fragmentKey, \"`\") : '', fragmentNode.name, typeof fragmentRef, fragmentNode.name) : invariant(false) : void 0;\n if (fragmentRef.length === 0) {\n return {\n cacheKey: fragmentIdentifier,\n data: CONSTANT_READONLY_EMPTY_ARRAY,\n isMissingData: false,\n snapshot: CONSTANT_READONLY_EMPTY_ARRAY,\n storeEpoch: storeEpoch\n };\n }\n }\n var cachedValue = this._cache.get(fragmentIdentifier);\n if (cachedValue != null) {\n var _missingLiveResolverF;\n if (cachedValue.kind === 'pending' && isPromise(cachedValue.promise)) {\n environment.__log({\n name: 'suspense.fragment',\n data: cachedValue.result.data,\n fragment: fragmentNode,\n isRelayHooks: true,\n isMissingData: cachedValue.result.isMissingData,\n isPromiseCached: true,\n pendingOperations: cachedValue.pendingOperations\n });\n throw cachedValue.promise;\n }\n if (cachedValue.kind === 'done' && cachedValue.result.snapshot && !((_missingLiveResolverF = missingLiveResolverFields(cachedValue.result.snapshot)) !== null && _missingLiveResolverF !== void 0 && _missingLiveResolverF.length)) {\n this._throwOrLogErrorsInSnapshot(cachedValue.result.snapshot);\n if (cachedValue.result.isMissingData) {\n environment.__log({\n name: 'fragmentresource.missing_data',\n data: cachedValue.result.data,\n fragment: fragmentNode,\n isRelayHooks: true,\n cached: true\n });\n }\n return cachedValue.result;\n }\n }\n var fragmentSelector = getSelector(fragmentNode, fragmentRef);\n !(fragmentSelector != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: Expected to receive an object where `...%s` was spread, ' + 'but the fragment reference was not found`. This is most ' + 'likely the result of:\\n' + \"- Forgetting to spread `%s` in `%s`'s parent's fragment.\\n\" + '- Conditionally fetching `%s` but unconditionally passing %s prop ' + 'to `%s`. If the parent fragment only fetches the fragment conditionally ' + '- with e.g. `@include`, `@skip`, or inside a `... on SomeType { }` ' + 'spread - then the fragment reference will not exist. ' + 'In this case, pass `null` if the conditions for evaluating the ' + 'fragment are not met (e.g. if the `@include(if)` value is false.)', fragmentNode.name, fragmentNode.name, componentDisplayName, fragmentNode.name, fragmentKey == null ? 'a fragment reference' : \"the `\".concat(fragmentKey, \"`\"), componentDisplayName) : invariant(false) : void 0;\n var fragmentResult = null;\n var snapshot = null;\n if (RelayFeatureFlags.ENABLE_RELAY_OPERATION_TRACKER_SUSPENSE && cachedValue != null && cachedValue.kind === 'missing') {\n fragmentResult = cachedValue.result;\n snapshot = cachedValue.snapshot;\n } else {\n snapshot = fragmentSelector.kind === 'PluralReaderSelector' ? fragmentSelector.selectors.map(function (s) {\n return environment.lookup(s);\n }) : environment.lookup(fragmentSelector);\n fragmentResult = getFragmentResult(fragmentIdentifier, snapshot, storeEpoch);\n }\n if (!fragmentResult.isMissingData) {\n this._throwOrLogErrorsInSnapshot(snapshot);\n this._cache.set(fragmentIdentifier, {\n kind: 'done',\n result: fragmentResult\n });\n return fragmentResult;\n }\n var clientEdgeRequests = null;\n if (RelayFeatureFlags.ENABLE_CLIENT_EDGES && ((_fragmentNode$metadat2 = fragmentNode.metadata) === null || _fragmentNode$metadat2 === void 0 ? void 0 : _fragmentNode$metadat2.hasClientEdges) === true && hasMissingClientEdges(snapshot)) {\n clientEdgeRequests = [];\n var queryResource = getQueryResourceForEnvironment(this._environment);\n var queryResults = [];\n singularOrPluralForEach(snapshot, function (snap) {\n var _snap$missingClientEd;\n (_snap$missingClientEd = snap.missingClientEdges) === null || _snap$missingClientEd === void 0 ? void 0 : _snap$missingClientEd.forEach(function (_ref) {\n var _clientEdgeRequests;\n var request = _ref.request,\n clientEdgeDestinationID = _ref.clientEdgeDestinationID;\n var _this3$_performClient = _this3._performClientEdgeQuery(queryResource, fragmentNode, fragmentRef, request, clientEdgeDestinationID),\n queryResult = _this3$_performClient.queryResult,\n requestDescriptor = _this3$_performClient.requestDescriptor;\n queryResults.push(queryResult);\n (_clientEdgeRequests = clientEdgeRequests) === null || _clientEdgeRequests === void 0 ? void 0 : _clientEdgeRequests.push(requestDescriptor);\n });\n });\n !(this._clientEdgeQueryResultsCache != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Client edge query result cache should exist when ENABLE_CLIENT_EDGES is on.') : invariant(false) : void 0;\n this._clientEdgeQueryResultsCache.recordQueryResults(fragmentIdentifier, queryResults);\n }\n var clientEdgePromises = [];\n if (RelayFeatureFlags.ENABLE_CLIENT_EDGES && clientEdgeRequests) {\n clientEdgePromises = clientEdgeRequests.map(function (request) {\n return getPromiseForActiveRequest(_this3._environment, request);\n }).filter(Boolean);\n }\n var fragmentOwner = fragmentSelector.kind === 'PluralReaderSelector' ? fragmentSelector.selectors[0].owner : fragmentSelector.owner;\n var parentQueryPromiseResult = this._getAndSavePromiseForFragmentRequestInFlight(fragmentIdentifier, fragmentNode, fragmentOwner, fragmentResult);\n var parentQueryPromiseResultPromise = parentQueryPromiseResult === null || parentQueryPromiseResult === void 0 ? void 0 : parentQueryPromiseResult.promise;\n var missingResolverFieldPromises = (_missingLiveResolverF2 = (_missingLiveResolverF3 = missingLiveResolverFields(snapshot)) === null || _missingLiveResolverF3 === void 0 ? void 0 : _missingLiveResolverF3.map(function (_ref2) {\n var liveStateID = _ref2.liveStateID;\n var store = environment.getStore();\n return store.getLiveResolverPromise(liveStateID);\n })) !== null && _missingLiveResolverF2 !== void 0 ? _missingLiveResolverF2 : [];\n if (clientEdgePromises.length || missingResolverFieldPromises.length || isPromise(parentQueryPromiseResultPromise)) {\n var _parentQueryPromiseRe, _clientEdgeRequests2;\n environment.__log({\n name: 'suspense.fragment',\n data: fragmentResult.data,\n fragment: fragmentNode,\n isRelayHooks: true,\n isPromiseCached: false,\n isMissingData: fragmentResult.isMissingData,\n pendingOperations: [].concat((0, _toConsumableArray2[\"default\"])((_parentQueryPromiseRe = parentQueryPromiseResult === null || parentQueryPromiseResult === void 0 ? void 0 : parentQueryPromiseResult.pendingOperations) !== null && _parentQueryPromiseRe !== void 0 ? _parentQueryPromiseRe : []), (0, _toConsumableArray2[\"default\"])((_clientEdgeRequests2 = clientEdgeRequests) !== null && _clientEdgeRequests2 !== void 0 ? _clientEdgeRequests2 : []))\n });\n var promises = [];\n if (clientEdgePromises.length > 0) {\n promises = promises.concat(clientEdgePromises);\n }\n if (missingResolverFieldPromises.length > 0) {\n promises = promises.concat(missingResolverFieldPromises);\n }\n if (promises.length > 0) {\n if (parentQueryPromiseResultPromise) {\n promises.push(parentQueryPromiseResultPromise);\n }\n throw Promise.all(promises);\n }\n if (parentQueryPromiseResultPromise) {\n throw parentQueryPromiseResultPromise;\n }\n }\n if (RelayFeatureFlags.ENABLE_RELAY_OPERATION_TRACKER_SUSPENSE && fragmentResult.isMissingData) {\n this._cache.set(fragmentIdentifier, {\n kind: 'done',\n result: fragmentResult\n });\n }\n this._throwOrLogErrorsInSnapshot(snapshot);\n environment.__log({\n name: 'fragmentresource.missing_data',\n data: fragmentResult.data,\n fragment: fragmentNode,\n isRelayHooks: true,\n cached: false\n });\n return getFragmentResult(fragmentIdentifier, snapshot, storeEpoch);\n };\n _proto2._performClientEdgeQuery = function _performClientEdgeQuery(queryResource, fragmentNode, fragmentRef, request, clientEdgeDestinationID) {\n var originalVariables = getVariablesFromFragment(fragmentNode, fragmentRef);\n var variables = (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, originalVariables), {}, {\n id: clientEdgeDestinationID\n });\n var operation = createOperationDescriptor(request, variables, {});\n var fetchObservable = fetchQuery(this._environment, operation);\n var queryResult = queryResource.prepare(operation, fetchObservable);\n return {\n requestDescriptor: operation.request,\n queryResult: queryResult\n };\n };\n _proto2._throwOrLogErrorsInSnapshot = function _throwOrLogErrorsInSnapshot(snapshot) {\n var _this4 = this;\n if (Array.isArray(snapshot)) {\n snapshot.forEach(function (s) {\n handlePotentialSnapshotErrors(_this4._environment, s.missingRequiredFields, s.relayResolverErrors, s.errorResponseFields);\n });\n } else {\n handlePotentialSnapshotErrors(this._environment, snapshot.missingRequiredFields, snapshot.relayResolverErrors, snapshot.errorResponseFields);\n }\n };\n _proto2.readSpec = function readSpec(fragmentNodes, fragmentRefs, componentDisplayName) {\n var result = {};\n for (var key in fragmentNodes) {\n result[key] = this.read(fragmentNodes[key], fragmentRefs[key], componentDisplayName, key);\n }\n return result;\n };\n _proto2.subscribe = function subscribe(fragmentResult, callback) {\n var _this5 = this;\n var environment = this._environment;\n var cacheKey = fragmentResult.cacheKey;\n var renderedSnapshot = fragmentResult.snapshot;\n if (!renderedSnapshot) {\n return {\n dispose: function dispose() {}\n };\n }\n var _this$checkMissedUpda = this.checkMissedUpdates(fragmentResult),\n didMissUpdates = _this$checkMissedUpda[0],\n currentSnapshot = _this$checkMissedUpda[1];\n if (didMissUpdates) {\n callback();\n }\n var disposables = [];\n if (Array.isArray(renderedSnapshot)) {\n !Array.isArray(currentSnapshot) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: Expected snapshots to be plural. ' + \"If you're seeing this, this is likely a bug in Relay.\") : invariant(false) : void 0;\n currentSnapshot.forEach(function (snapshot, idx) {\n disposables.push(environment.subscribe(snapshot, function (latestSnapshot) {\n var storeEpoch = environment.getStore().getEpoch();\n _this5._updatePluralSnapshot(cacheKey, currentSnapshot, latestSnapshot, idx, storeEpoch);\n callback();\n }));\n });\n } else {\n !(currentSnapshot != null && !Array.isArray(currentSnapshot)) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: Expected snapshot to be singular. ' + \"If you're seeing this, this is likely a bug in Relay.\") : invariant(false) : void 0;\n disposables.push(environment.subscribe(currentSnapshot, function (latestSnapshot) {\n var storeEpoch = environment.getStore().getEpoch();\n var result = getFragmentResult(cacheKey, latestSnapshot, storeEpoch);\n if (RelayFeatureFlags.ENABLE_RELAY_OPERATION_TRACKER_SUSPENSE && result.isMissingData) {\n _this5._cache.set(cacheKey, {\n kind: 'missing',\n result: result,\n snapshot: latestSnapshot\n });\n } else {\n _this5._cache.set(cacheKey, {\n kind: 'done',\n result: getFragmentResult(cacheKey, latestSnapshot, storeEpoch)\n });\n }\n callback();\n }));\n }\n if (RelayFeatureFlags.ENABLE_CLIENT_EDGES) {\n var _this$_clientEdgeQuer, _this$_clientEdgeQuer2;\n var clientEdgeQueryResults = (_this$_clientEdgeQuer = (_this$_clientEdgeQuer2 = this._clientEdgeQueryResultsCache) === null || _this$_clientEdgeQuer2 === void 0 ? void 0 : _this$_clientEdgeQuer2.get(cacheKey)) !== null && _this$_clientEdgeQuer !== void 0 ? _this$_clientEdgeQuer : undefined;\n if (clientEdgeQueryResults !== null && clientEdgeQueryResults !== void 0 && clientEdgeQueryResults.length) {\n var queryResource = getQueryResourceForEnvironment(this._environment);\n clientEdgeQueryResults.forEach(function (queryResult) {\n disposables.push(queryResource.retain(queryResult));\n });\n }\n }\n return {\n dispose: function dispose() {\n disposables.forEach(function (s) {\n return s.dispose();\n });\n _this5._cache[\"delete\"](cacheKey);\n }\n };\n };\n _proto2.subscribeSpec = function subscribeSpec(fragmentResults, callback) {\n var _this6 = this;\n var disposables = Object.keys(fragmentResults).map(function (key) {\n return _this6.subscribe(fragmentResults[key], callback);\n });\n return {\n dispose: function dispose() {\n disposables.forEach(function (disposable) {\n disposable.dispose();\n });\n }\n };\n };\n _proto2.checkMissedUpdates = function checkMissedUpdates(fragmentResult) {\n var environment = this._environment;\n var renderedSnapshot = fragmentResult.snapshot;\n if (!renderedSnapshot) {\n return [false, null];\n }\n var storeEpoch = null;\n storeEpoch = environment.getStore().getEpoch();\n if (fragmentResult.storeEpoch === storeEpoch) {\n return [false, fragmentResult.snapshot];\n }\n var cacheKey = fragmentResult.cacheKey;\n if (Array.isArray(renderedSnapshot)) {\n var didMissUpdates = false;\n var currentSnapshots = [];\n renderedSnapshot.forEach(function (snapshot, idx) {\n var currentSnapshot = environment.lookup(snapshot.selector);\n var renderData = snapshot.data;\n var currentData = currentSnapshot.data;\n var updatedData = recycleNodesInto(renderData, currentData);\n if (updatedData !== renderData) {\n currentSnapshot = (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, currentSnapshot), {}, {\n data: updatedData\n });\n didMissUpdates = true;\n }\n currentSnapshots[idx] = currentSnapshot;\n });\n if (didMissUpdates) {\n var result = getFragmentResult(cacheKey, currentSnapshots, storeEpoch);\n if (RelayFeatureFlags.ENABLE_RELAY_OPERATION_TRACKER_SUSPENSE && result.isMissingData) {\n this._cache.set(cacheKey, {\n kind: 'missing',\n result: result,\n snapshot: currentSnapshots\n });\n } else {\n this._cache.set(cacheKey, {\n kind: 'done',\n result: result\n });\n }\n }\n return [didMissUpdates, currentSnapshots];\n }\n var currentSnapshot = environment.lookup(renderedSnapshot.selector);\n var renderData = renderedSnapshot.data;\n var currentData = currentSnapshot.data;\n var updatedData = recycleNodesInto(renderData, currentData);\n var updatedCurrentSnapshot = {\n data: updatedData,\n isMissingData: currentSnapshot.isMissingData,\n missingClientEdges: currentSnapshot.missingClientEdges,\n missingLiveResolverFields: currentSnapshot.missingLiveResolverFields,\n seenRecords: currentSnapshot.seenRecords,\n selector: currentSnapshot.selector,\n missingRequiredFields: currentSnapshot.missingRequiredFields,\n relayResolverErrors: currentSnapshot.relayResolverErrors,\n errorResponseFields: currentSnapshot.errorResponseFields\n };\n if (updatedData !== renderData) {\n var _result = getFragmentResult(cacheKey, updatedCurrentSnapshot, storeEpoch);\n if (RelayFeatureFlags.ENABLE_RELAY_OPERATION_TRACKER_SUSPENSE && _result.isMissingData) {\n this._cache.set(cacheKey, {\n kind: 'missing',\n result: _result,\n snapshot: updatedCurrentSnapshot\n });\n } else {\n this._cache.set(cacheKey, {\n kind: 'done',\n result: _result\n });\n }\n }\n return [updatedData !== renderData, updatedCurrentSnapshot];\n };\n _proto2.checkMissedUpdatesSpec = function checkMissedUpdatesSpec(fragmentResults) {\n var _this7 = this;\n return Object.keys(fragmentResults).some(function (key) {\n return _this7.checkMissedUpdates(fragmentResults[key])[0];\n });\n };\n _proto2._getAndSavePromiseForFragmentRequestInFlight = function _getAndSavePromiseForFragmentRequestInFlight(cacheKey, fragmentNode, fragmentOwner, fragmentResult) {\n var _this8 = this;\n var pendingOperationsResult = getPendingOperationsForFragment(this._environment, fragmentNode, fragmentOwner);\n if (pendingOperationsResult == null) {\n return null;\n }\n var networkPromise = pendingOperationsResult.promise;\n var pendingOperations = pendingOperationsResult.pendingOperations;\n var promise = networkPromise.then(function () {\n _this8._cache[\"delete\"](cacheKey);\n })[\"catch\"](function (error) {\n _this8._cache[\"delete\"](cacheKey);\n });\n promise.displayName = networkPromise.displayName;\n this._cache.set(cacheKey, {\n kind: 'pending',\n pendingOperations: pendingOperations,\n promise: promise,\n result: fragmentResult\n });\n return {\n promise: promise,\n pendingOperations: pendingOperations\n };\n };\n _proto2._updatePluralSnapshot = function _updatePluralSnapshot(cacheKey, baseSnapshots, latestSnapshot, idx, storeEpoch) {\n var _currentFragmentResul;\n var currentFragmentResult = this._cache.get(cacheKey);\n if (isPromise(currentFragmentResult)) {\n reportInvalidCachedData(latestSnapshot.selector.node.name);\n return;\n }\n var currentSnapshot = currentFragmentResult === null || currentFragmentResult === void 0 ? void 0 : (_currentFragmentResul = currentFragmentResult.result) === null || _currentFragmentResul === void 0 ? void 0 : _currentFragmentResul.snapshot;\n if (currentSnapshot && !Array.isArray(currentSnapshot)) {\n reportInvalidCachedData(latestSnapshot.selector.node.name);\n return;\n }\n var nextSnapshots = currentSnapshot ? (0, _toConsumableArray2[\"default\"])(currentSnapshot) : (0, _toConsumableArray2[\"default\"])(baseSnapshots);\n nextSnapshots[idx] = latestSnapshot;\n var result = getFragmentResult(cacheKey, nextSnapshots, storeEpoch);\n if (RelayFeatureFlags.ENABLE_RELAY_OPERATION_TRACKER_SUSPENSE && result.isMissingData) {\n this._cache.set(cacheKey, {\n kind: 'missing',\n result: result,\n snapshot: nextSnapshots\n });\n } else {\n this._cache.set(cacheKey, {\n kind: 'done',\n result: result\n });\n }\n };\n return FragmentResourceImpl;\n}();\nfunction reportInvalidCachedData(nodeName) {\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: Expected to find cached data for plural fragment `%s` when ' + 'receiving a subscription. ' + \"If you're seeing this, this is likely a bug in Relay.\", nodeName) : invariant(false) : void 0;\n}\nfunction createFragmentResource(environment) {\n return new FragmentResourceImpl(environment);\n}\nvar dataResources = WEAKMAP_SUPPORTED ? new WeakMap() : new Map();\nfunction getFragmentResourceForEnvironment(environment) {\n var cached = dataResources.get(environment);\n if (cached) {\n return cached;\n }\n var newDataResource = createFragmentResource(environment);\n dataResources.set(environment, newDataResource);\n return newDataResource;\n}\nmodule.exports = {\n createFragmentResource: createFragmentResource,\n getFragmentResourceForEnvironment: getFragmentResourceForEnvironment\n};","'use strict';\n\nvar useRelayEnvironment = require('../useRelayEnvironment');\nvar useUnsafeRef_DEPRECATED = require('../useUnsafeRef_DEPRECATED');\nvar _require = require('./FragmentResource'),\n getFragmentResourceForEnvironment = _require.getFragmentResourceForEnvironment;\nvar _require2 = require('react'),\n useEffect = _require2.useEffect,\n useState = _require2.useState;\nvar _require3 = require('relay-runtime'),\n RelayFeatureFlags = _require3.RelayFeatureFlags,\n getFragmentIdentifier = _require3.getFragmentIdentifier;\nvar warning = require(\"fbjs/lib/warning\");\nfunction useFragmentNode(fragmentNode, fragmentRef, componentDisplayName) {\n var environment = useRelayEnvironment();\n var FragmentResource = getFragmentResourceForEnvironment(environment);\n var isMountedRef = useUnsafeRef_DEPRECATED(false);\n var _useState = useState(0),\n forceUpdate = _useState[1];\n var fragmentIdentifier = getFragmentIdentifier(fragmentNode, fragmentRef);\n var fragmentResult = FragmentResource.readWithIdentifier(fragmentNode, fragmentRef, fragmentIdentifier, componentDisplayName);\n var isListeningForUpdatesRef = useUnsafeRef_DEPRECATED(true);\n function enableStoreUpdates() {\n isListeningForUpdatesRef.current = true;\n var didMissUpdates = FragmentResource.checkMissedUpdates(fragmentResult)[0];\n if (didMissUpdates) {\n handleDataUpdate();\n }\n }\n function disableStoreUpdates() {\n isListeningForUpdatesRef.current = false;\n }\n function handleDataUpdate() {\n if (isMountedRef.current === false || isListeningForUpdatesRef.current === false) {\n return;\n }\n forceUpdate(function (count) {\n return count + 1;\n });\n }\n useEffect(function () {\n isMountedRef.current = true;\n var disposable = FragmentResource.subscribe(fragmentResult, handleDataUpdate);\n return function () {\n isMountedRef.current = false;\n disposable.dispose();\n };\n }, [environment, fragmentIdentifier]);\n if (RelayFeatureFlags.LOG_MISSING_RECORDS_IN_PROD || process.env.NODE_ENV !== \"production\") {\n if (fragmentRef != null && (fragmentResult.data === undefined || Array.isArray(fragmentResult.data) && fragmentResult.data.length > 0 && fragmentResult.data.every(function (data) {\n return data === undefined;\n }))) {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'Relay: Expected to have been able to read non-null data for ' + 'fragment `%s` declared in ' + '`%s`, since fragment reference was non-null. ' + \"Make sure that that `%s`'s parent isn't \" + 'holding on to and/or passing a fragment reference for data that ' + 'has been deleted.', fragmentNode.name, componentDisplayName, componentDisplayName) : void 0;\n }\n }\n return {\n data: fragmentResult.data,\n disableStoreUpdates: disableStoreUpdates,\n enableStoreUpdates: enableStoreUpdates\n };\n}\nmodule.exports = useFragmentNode;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _objectSpread2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar ProfilerContext = require('../ProfilerContext');\nvar _require = require('../QueryResource'),\n getQueryResourceForEnvironment = _require.getQueryResourceForEnvironment;\nvar useIsMountedRef = require('../useIsMountedRef');\nvar useQueryLoader = require('../useQueryLoader');\nvar useRelayEnvironment = require('../useRelayEnvironment');\nvar _require2 = require('./FragmentResource'),\n getFragmentResourceForEnvironment = _require2.getFragmentResourceForEnvironment;\nvar useFragmentNode = require('./useFragmentNode');\nvar invariant = require('invariant');\nvar _require3 = require('react'),\n useCallback = _require3.useCallback,\n useContext = _require3.useContext,\n useReducer = _require3.useReducer;\nvar _require4 = require('relay-runtime'),\n fetchQuery = _require4.__internal.fetchQuery,\n createOperationDescriptor = _require4.createOperationDescriptor,\n getFragmentIdentifier = _require4.getFragmentIdentifier,\n getRefetchMetadata = _require4.getRefetchMetadata,\n getSelector = _require4.getSelector,\n getValueAtPath = _require4.getValueAtPath;\nvar warning = require(\"fbjs/lib/warning\");\nfunction reducer(state, action) {\n switch (action.type) {\n case 'refetch':\n {\n var _action$refetchEnviro;\n return (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, state), {}, {\n fetchPolicy: action.fetchPolicy,\n mirroredEnvironment: (_action$refetchEnviro = action.refetchEnvironment) !== null && _action$refetchEnviro !== void 0 ? _action$refetchEnviro : state.mirroredEnvironment,\n onComplete: action.onComplete,\n refetchEnvironment: action.refetchEnvironment,\n refetchQuery: action.refetchQuery,\n renderPolicy: action.renderPolicy\n });\n }\n case 'reset':\n {\n return {\n fetchPolicy: undefined,\n mirroredEnvironment: action.environment,\n mirroredFragmentIdentifier: action.fragmentIdentifier,\n onComplete: undefined,\n refetchQuery: null,\n renderPolicy: undefined\n };\n }\n default:\n {\n action.type;\n throw new Error('useRefetchableFragmentNode: Unexpected action type');\n }\n }\n}\nfunction useRefetchableFragmentNode(fragmentNode, parentFragmentRef, componentDisplayName) {\n var parentEnvironment = useRelayEnvironment();\n var _getRefetchMetadata = getRefetchMetadata(fragmentNode, componentDisplayName),\n refetchableRequest = _getRefetchMetadata.refetchableRequest,\n fragmentRefPathInResponse = _getRefetchMetadata.fragmentRefPathInResponse;\n var fragmentIdentifier = getFragmentIdentifier(fragmentNode, parentFragmentRef);\n var _useReducer = useReducer(reducer, {\n fetchPolicy: undefined,\n mirroredEnvironment: parentEnvironment,\n mirroredFragmentIdentifier: fragmentIdentifier,\n onComplete: undefined,\n refetchEnvironment: null,\n refetchQuery: null,\n renderPolicy: undefined\n }),\n refetchState = _useReducer[0],\n dispatch = _useReducer[1];\n var fetchPolicy = refetchState.fetchPolicy,\n mirroredEnvironment = refetchState.mirroredEnvironment,\n mirroredFragmentIdentifier = refetchState.mirroredFragmentIdentifier,\n onComplete = refetchState.onComplete,\n refetchEnvironment = refetchState.refetchEnvironment,\n refetchQuery = refetchState.refetchQuery,\n renderPolicy = refetchState.renderPolicy;\n var environment = refetchEnvironment !== null && refetchEnvironment !== void 0 ? refetchEnvironment : parentEnvironment;\n var QueryResource = getQueryResourceForEnvironment(environment);\n var FragmentResource = getFragmentResourceForEnvironment(environment);\n var profilerContext = useContext(ProfilerContext);\n var shouldReset = environment !== mirroredEnvironment || fragmentIdentifier !== mirroredFragmentIdentifier;\n var _useQueryLoader = useQueryLoader(refetchableRequest),\n queryRef = _useQueryLoader[0],\n loadQuery = _useQueryLoader[1],\n disposeQuery = _useQueryLoader[2];\n var fragmentRef = parentFragmentRef;\n var _getRefetchMetadata2 = getRefetchMetadata(fragmentNode, componentDisplayName),\n identifierInfo = _getRefetchMetadata2.identifierInfo;\n if (shouldReset) {\n dispatch({\n type: 'reset',\n environment: environment,\n fragmentIdentifier: fragmentIdentifier\n });\n disposeQuery();\n } else if (refetchQuery != null && queryRef != null) {\n var debugPreviousIDAndTypename;\n if (process.env.NODE_ENV !== \"production\") {\n debugPreviousIDAndTypename = debugFunctions.getInitialIDAndType(refetchQuery.request.variables, fragmentRefPathInResponse, identifierInfo === null || identifierInfo === void 0 ? void 0 : identifierInfo.identifierQueryVariableName, environment);\n }\n var handleQueryCompleted = function handleQueryCompleted(maybeError) {\n onComplete && onComplete(maybeError !== null && maybeError !== void 0 ? maybeError : null);\n };\n var fetchObservable = queryRef.source != null ? queryRef.source : fetchQuery(environment, refetchQuery);\n var queryResult = profilerContext.wrapPrepareQueryResource(function () {\n return QueryResource.prepare(refetchQuery, fetchObservable, fetchPolicy, renderPolicy, {\n error: handleQueryCompleted,\n complete: function complete() {\n if (process.env.NODE_ENV !== \"production\") {\n debugFunctions.checkSameTypeAfterRefetch(debugPreviousIDAndTypename, environment, fragmentNode, componentDisplayName);\n }\n handleQueryCompleted();\n }\n }, queryRef.fetchKey, profilerContext);\n });\n var queryData = FragmentResource.read(queryResult.fragmentNode, queryResult.fragmentRef, componentDisplayName).data;\n !(queryData != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: Expected to be able to read refetch query response. ' + \"If you're seeing this, this is likely a bug in Relay.\") : invariant(false) : void 0;\n var refetchedFragmentRef = getValueAtPath(queryData, fragmentRefPathInResponse);\n fragmentRef = refetchedFragmentRef;\n if (process.env.NODE_ENV !== \"production\") {\n debugFunctions.checkSameIDAfterRefetch(debugPreviousIDAndTypename, fragmentRef, fragmentNode, componentDisplayName);\n }\n }\n var _useFragmentNode = useFragmentNode(fragmentNode, fragmentRef, componentDisplayName),\n fragmentData = _useFragmentNode.data,\n disableStoreUpdates = _useFragmentNode.disableStoreUpdates,\n enableStoreUpdates = _useFragmentNode.enableStoreUpdates;\n var refetch = useRefetchFunction(componentDisplayName, dispatch, disposeQuery, fragmentData, fragmentIdentifier, fragmentNode, fragmentRefPathInResponse, identifierInfo, loadQuery, parentFragmentRef, refetchableRequest);\n return {\n fragmentData: fragmentData,\n fragmentRef: fragmentRef,\n refetch: refetch,\n disableStoreUpdates: disableStoreUpdates,\n enableStoreUpdates: enableStoreUpdates\n };\n}\nfunction useRefetchFunction(componentDisplayName, dispatch, disposeQuery, fragmentData, fragmentIdentifier, fragmentNode, fragmentRefPathInResponse, identifierInfo, loadQuery, parentFragmentRef, refetchableRequest) {\n var isMountedRef = useIsMountedRef();\n var identifierValue = (identifierInfo === null || identifierInfo === void 0 ? void 0 : identifierInfo.identifierField) != null && fragmentData != null && typeof fragmentData === 'object' ? fragmentData[identifierInfo.identifierField] : null;\n return useCallback(function (providedRefetchVariables, options) {\n if (isMountedRef.current !== true) {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'Relay: Unexpected call to `refetch` on unmounted component for fragment ' + '`%s` in `%s`. It looks like some instances of your component are ' + 'still trying to fetch data but they already unmounted. ' + 'Please make sure you clear all timers, intervals, ' + 'async calls, etc that may trigger a fetch.', fragmentNode.name, componentDisplayName) : void 0;\n return {\n dispose: function dispose() {}\n };\n }\n if (parentFragmentRef == null) {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'Relay: Unexpected call to `refetch` while using a null fragment ref ' + 'for fragment `%s` in `%s`. When calling `refetch`, we expect ' + \"initial fragment data to be non-null. Please make sure you're \" + 'passing a valid fragment ref to `%s` before calling ' + '`refetch`, or make sure you pass all required variables to `refetch`.', fragmentNode.name, componentDisplayName, componentDisplayName) : void 0;\n }\n var refetchEnvironment = options === null || options === void 0 ? void 0 : options.__environment;\n var fetchPolicy = options === null || options === void 0 ? void 0 : options.fetchPolicy;\n var renderPolicy = options === null || options === void 0 ? void 0 : options.UNSTABLE_renderPolicy;\n var onComplete = options === null || options === void 0 ? void 0 : options.onComplete;\n var fragmentSelector = getSelector(fragmentNode, parentFragmentRef);\n var parentVariables;\n var fragmentVariables;\n if (fragmentSelector == null) {\n parentVariables = {};\n fragmentVariables = {};\n } else if (fragmentSelector.kind === 'PluralReaderSelector') {\n var _fragmentSelector$sel, _fragmentSelector$sel2, _fragmentSelector$sel3, _fragmentSelector$sel4;\n parentVariables = (_fragmentSelector$sel = (_fragmentSelector$sel2 = fragmentSelector.selectors[0]) === null || _fragmentSelector$sel2 === void 0 ? void 0 : _fragmentSelector$sel2.owner.variables) !== null && _fragmentSelector$sel !== void 0 ? _fragmentSelector$sel : {};\n fragmentVariables = (_fragmentSelector$sel3 = (_fragmentSelector$sel4 = fragmentSelector.selectors[0]) === null || _fragmentSelector$sel4 === void 0 ? void 0 : _fragmentSelector$sel4.variables) !== null && _fragmentSelector$sel3 !== void 0 ? _fragmentSelector$sel3 : {};\n } else {\n parentVariables = fragmentSelector.owner.variables;\n fragmentVariables = fragmentSelector.variables;\n }\n var refetchVariables = (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, parentVariables), fragmentVariables), providedRefetchVariables);\n if (identifierInfo != null && !providedRefetchVariables.hasOwnProperty(identifierInfo.identifierQueryVariableName)) {\n if (typeof identifierValue !== 'string') {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'Relay: Expected result to have a string ' + '`%s` in order to refetch, got `%s`.', identifierInfo.identifierField, identifierValue) : void 0;\n }\n refetchVariables[identifierInfo.identifierQueryVariableName] = identifierValue;\n }\n var refetchQuery = createOperationDescriptor(refetchableRequest, refetchVariables, {\n force: true\n });\n loadQuery(refetchQuery.request.variables, {\n fetchPolicy: fetchPolicy,\n __environment: refetchEnvironment,\n __nameForWarning: 'refetch'\n });\n dispatch({\n type: 'refetch',\n fetchPolicy: fetchPolicy,\n onComplete: onComplete,\n refetchEnvironment: refetchEnvironment,\n refetchQuery: refetchQuery,\n renderPolicy: renderPolicy\n });\n return {\n dispose: disposeQuery\n };\n }, [fragmentIdentifier, dispatch, disposeQuery, identifierValue, loadQuery]);\n}\nvar debugFunctions;\nif (process.env.NODE_ENV !== \"production\") {\n debugFunctions = {\n getInitialIDAndType: function getInitialIDAndType(memoRefetchVariables, fragmentRefPathInResponse, identifierQueryVariableName, environment) {\n var _require5 = require('relay-runtime'),\n Record = _require5.Record;\n var id = memoRefetchVariables === null || memoRefetchVariables === void 0 ? void 0 : memoRefetchVariables[identifierQueryVariableName !== null && identifierQueryVariableName !== void 0 ? identifierQueryVariableName : 'id'];\n if (fragmentRefPathInResponse.length !== 1 || fragmentRefPathInResponse[0] !== 'node' || id == null) {\n return null;\n }\n var recordSource = environment.getStore().getSource();\n var record = recordSource.get(id);\n var typename = record == null ? null : Record.getType(record);\n if (typename == null) {\n return null;\n }\n return {\n id: id,\n typename: typename\n };\n },\n checkSameTypeAfterRefetch: function checkSameTypeAfterRefetch(previousIDAndType, environment, fragmentNode, componentDisplayName) {\n var _require6 = require('relay-runtime'),\n Record = _require6.Record;\n if (!previousIDAndType) {\n return;\n }\n var recordSource = environment.getStore().getSource();\n var record = recordSource.get(previousIDAndType.id);\n var typename = record && Record.getType(record);\n if (typename !== previousIDAndType.typename) {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'Relay: Call to `refetch` returned data with a different ' + '__typename: was `%s`, now `%s`, on `%s` in `%s`. ' + 'Please make sure the server correctly implements' + 'unique id requirement.', previousIDAndType.typename, typename, fragmentNode.name, componentDisplayName) : void 0;\n }\n },\n checkSameIDAfterRefetch: function checkSameIDAfterRefetch(previousIDAndTypename, refetchedFragmentRef, fragmentNode, componentDisplayName) {\n if (previousIDAndTypename == null) {\n return;\n }\n var _require7 = require('relay-runtime'),\n ID_KEY = _require7.ID_KEY;\n var resultID = refetchedFragmentRef[ID_KEY];\n if (resultID != null && resultID !== previousIDAndTypename.id) {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'Relay: Call to `refetch` returned a different id, expected ' + '`%s`, got `%s`, on `%s` in `%s`. ' + 'Please make sure the server correctly implements ' + 'unique id requirement.', resultID, previousIDAndTypename.id, fragmentNode.name, componentDisplayName) : void 0;\n }\n }\n };\n}\nmodule.exports = useRefetchableFragmentNode;","'use strict';\n\nvar _require = require('./loadQuery'),\n loadQuery = _require.loadQuery;\nfunction loadEntryPoint(environmentProvider, entryPoint, entryPointParams) {\n var loadingPromise = null;\n if (entryPoint.root.getModuleIfRequired() == null) {\n loadingPromise = entryPoint.root.load();\n }\n var preloadProps = entryPoint.getPreloadProps(entryPointParams);\n var queries = preloadProps.queries,\n entryPoints = preloadProps.entryPoints,\n extraProps = preloadProps.extraProps;\n var preloadedQueries = {};\n var preloadedEntryPoints = {};\n if (queries != null) {\n var queriesPropNames = Object.keys(queries);\n queriesPropNames.forEach(function (queryPropName) {\n var _queries$queryPropNam = queries[queryPropName],\n environmentProviderOptions = _queries$queryPropNam.environmentProviderOptions,\n options = _queries$queryPropNam.options,\n parameters = _queries$queryPropNam.parameters,\n variables = _queries$queryPropNam.variables;\n var environment = environmentProvider.getEnvironment(environmentProviderOptions);\n preloadedQueries[queryPropName] = loadQuery(environment, parameters, variables, {\n fetchPolicy: options === null || options === void 0 ? void 0 : options.fetchPolicy,\n networkCacheConfig: options === null || options === void 0 ? void 0 : options.networkCacheConfig,\n __nameForWarning: 'loadEntryPoint'\n }, environmentProviderOptions);\n });\n }\n if (entryPoints != null) {\n var entryPointPropNames = Object.keys(entryPoints);\n entryPointPropNames.forEach(function (entryPointPropName) {\n var entryPointDescription = entryPoints[entryPointPropName];\n if (entryPointDescription == null) {\n return;\n }\n var nestedEntryPoint = entryPointDescription.entryPoint,\n nestedParams = entryPointDescription.entryPointParams;\n preloadedEntryPoints[entryPointPropName] = loadEntryPoint(environmentProvider, nestedEntryPoint, nestedParams);\n });\n }\n var isDisposed = false;\n return {\n dispose: function dispose() {\n if (isDisposed) {\n return;\n }\n if (preloadedQueries != null) {\n Object.values(preloadedQueries).forEach(function (_ref) {\n var innerDispose = _ref.dispose;\n innerDispose();\n });\n }\n if (preloadedEntryPoints != null) {\n Object.values(preloadedEntryPoints).forEach(function (_ref2) {\n var innerDispose = _ref2.dispose;\n innerDispose();\n });\n }\n isDisposed = true;\n },\n entryPoints: preloadedEntryPoints,\n extraProps: extraProps !== null && extraProps !== void 0 ? extraProps : null,\n getComponent: function getComponent() {\n var componentModule = entryPoint.root.getModuleIfRequired();\n if (componentModule == null) {\n var _loadingPromise;\n loadingPromise = (_loadingPromise = loadingPromise) !== null && _loadingPromise !== void 0 ? _loadingPromise : entryPoint.root.load();\n throw loadingPromise;\n }\n var component = componentModule[\"default\"] != null ? componentModule[\"default\"] : componentModule;\n return component;\n },\n get isDisposed() {\n return isDisposed;\n },\n queries: preloadedQueries,\n rootModuleID: entryPoint.root.getModuleId()\n };\n}\nmodule.exports = loadEntryPoint;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _objectSpread2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar invariant = require('invariant');\nvar React = require('react');\nvar _require = require('relay-runtime'),\n fetchQueryDeduped = _require.__internal.fetchQueryDeduped,\n Observable = _require.Observable,\n PreloadableQueryRegistry = _require.PreloadableQueryRegistry,\n RelayFeatureFlags = _require.RelayFeatureFlags,\n ReplaySubject = _require.ReplaySubject,\n createOperationDescriptor = _require.createOperationDescriptor,\n getRequest = _require.getRequest,\n getRequestIdentifier = _require.getRequestIdentifier;\nvar warning = require(\"fbjs/lib/warning\");\nvar RenderDispatcher = null;\nvar fetchKey = 100001;\nfunction useTrackLoadQueryInRender() {\n if (RenderDispatcher === null) {\n var _React$__SECRET_INTER, _React$__SECRET_INTER2;\n RenderDispatcher = (_React$__SECRET_INTER = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED) === null || _React$__SECRET_INTER === void 0 ? void 0 : (_React$__SECRET_INTER2 = _React$__SECRET_INTER.ReactCurrentDispatcher) === null || _React$__SECRET_INTER2 === void 0 ? void 0 : _React$__SECRET_INTER2.current;\n }\n}\nfunction loadQuery(environment, preloadableRequest, variables, options, environmentProviderOptions) {\n var _React$__SECRET_INTER3, _React$__SECRET_INTER4, _options$__nameForWar, _options$fetchPolicy;\n var CurrentDispatcher = (_React$__SECRET_INTER3 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED) === null || _React$__SECRET_INTER3 === void 0 ? void 0 : (_React$__SECRET_INTER4 = _React$__SECRET_INTER3.ReactCurrentDispatcher) === null || _React$__SECRET_INTER4 === void 0 ? void 0 : _React$__SECRET_INTER4.current;\n process.env.NODE_ENV !== \"production\" ? warning(RenderDispatcher == null || CurrentDispatcher !== RenderDispatcher, 'Relay: `%s` should not be called inside a React render function.', (_options$__nameForWar = options === null || options === void 0 ? void 0 : options.__nameForWarning) !== null && _options$__nameForWar !== void 0 ? _options$__nameForWar : 'loadQuery') : void 0;\n fetchKey++;\n var fetchPolicy = (_options$fetchPolicy = options === null || options === void 0 ? void 0 : options.fetchPolicy) !== null && _options$fetchPolicy !== void 0 ? _options$fetchPolicy : 'store-or-network';\n var networkCacheConfig = (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, options === null || options === void 0 ? void 0 : options.networkCacheConfig), {}, {\n force: true\n });\n var retainReference;\n var didExecuteNetworkSource = false;\n var executeWithNetworkSource = function executeWithNetworkSource(operation, networkObservable) {\n didExecuteNetworkSource = true;\n return environment.executeWithSource({\n operation: operation,\n source: networkObservable\n });\n };\n var executionSubject = new ReplaySubject();\n var returnedObservable = Observable.create(function (sink) {\n return executionSubject.subscribe(sink);\n });\n var unsubscribeFromNetworkRequest;\n var networkError = null;\n var didMakeNetworkRequest = false;\n var makeNetworkRequest = function makeNetworkRequest(params) {\n didMakeNetworkRequest = true;\n var observable;\n var subject = new ReplaySubject();\n if (RelayFeatureFlags.ENABLE_LOAD_QUERY_REQUEST_DEDUPING === true) {\n var identifier = 'raw-network-request-' + getRequestIdentifier(params, variables);\n observable = fetchQueryDeduped(environment, identifier, function () {\n var network = environment.getNetwork();\n return network.execute(params, variables, networkCacheConfig);\n });\n } else {\n var network = environment.getNetwork();\n observable = network.execute(params, variables, networkCacheConfig);\n }\n var _observable$subscribe = observable.subscribe({\n error: function error(err) {\n networkError = err;\n subject.error(err);\n },\n next: function next(data) {\n subject.next(data);\n },\n complete: function complete() {\n subject.complete();\n }\n }),\n unsubscribe = _observable$subscribe.unsubscribe;\n unsubscribeFromNetworkRequest = unsubscribe;\n return Observable.create(function (sink) {\n var subjectSubscription = subject.subscribe(sink);\n return function () {\n subjectSubscription.unsubscribe();\n unsubscribeFromNetworkRequest();\n };\n });\n };\n var unsubscribeFromExecution;\n var executeDeduped = function executeDeduped(operation, fetchFn) {\n if (RelayFeatureFlags.ENABLE_LOAD_QUERY_REQUEST_DEDUPING === true) {\n didMakeNetworkRequest = true;\n }\n var _fetchQueryDeduped$su = fetchQueryDeduped(environment, operation.request.identifier, fetchFn).subscribe({\n error: function error(err) {\n executionSubject.error(err);\n },\n next: function next(data) {\n executionSubject.next(data);\n },\n complete: function complete() {\n executionSubject.complete();\n }\n });\n unsubscribeFromExecution = _fetchQueryDeduped$su.unsubscribe;\n };\n var checkAvailabilityAndExecute = function checkAvailabilityAndExecute(concreteRequest) {\n var operation = createOperationDescriptor(concreteRequest, variables, networkCacheConfig);\n retainReference = environment.retain(operation);\n if (fetchPolicy === 'store-only') {\n return;\n }\n var shouldFetch = fetchPolicy !== 'store-or-network' || environment.check(operation).status !== 'available';\n if (shouldFetch) {\n executeDeduped(operation, function () {\n var networkObservable = makeNetworkRequest(concreteRequest.params);\n var executeObservable = executeWithNetworkSource(operation, networkObservable);\n return executeObservable;\n });\n }\n };\n var params;\n var cancelOnLoadCallback;\n var queryId;\n if (preloadableRequest.kind === 'PreloadableConcreteRequest') {\n var preloadableConcreteRequest = preloadableRequest;\n params = preloadableConcreteRequest.params;\n var _params = params;\n queryId = _params.id;\n !(queryId !== null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: `loadQuery` requires that preloadable query `%s` has a persisted query id', params.name) : invariant(false) : void 0;\n var _module = PreloadableQueryRegistry.get(queryId);\n if (_module != null) {\n checkAvailabilityAndExecute(_module);\n } else {\n var networkObservable = fetchPolicy === 'store-only' ? null : makeNetworkRequest(params);\n var _PreloadableQueryRegi = PreloadableQueryRegistry.onLoad(queryId, function (preloadedModule) {\n cancelOnLoadCallback();\n var operation = createOperationDescriptor(preloadedModule, variables, networkCacheConfig);\n retainReference = environment.retain(operation);\n if (networkObservable != null) {\n executeDeduped(operation, function () {\n return executeWithNetworkSource(operation, networkObservable);\n });\n }\n });\n cancelOnLoadCallback = _PreloadableQueryRegi.dispose;\n }\n } else {\n var graphQlTaggedNode = preloadableRequest;\n var request = getRequest(graphQlTaggedNode);\n params = request.params;\n queryId = params.cacheID != null ? params.cacheID : params.id;\n checkAvailabilityAndExecute(request);\n }\n var isDisposed = false;\n var isReleased = false;\n var isNetworkRequestCancelled = false;\n var releaseQuery = function releaseQuery() {\n if (isReleased) {\n return;\n }\n retainReference && retainReference.dispose();\n isReleased = true;\n };\n var cancelNetworkRequest = function cancelNetworkRequest() {\n if (isNetworkRequestCancelled) {\n return;\n }\n if (didExecuteNetworkSource) {\n unsubscribeFromExecution && unsubscribeFromExecution();\n } else {\n unsubscribeFromNetworkRequest && unsubscribeFromNetworkRequest();\n }\n cancelOnLoadCallback && cancelOnLoadCallback();\n isNetworkRequestCancelled = true;\n };\n return {\n kind: 'PreloadedQuery',\n environment: environment,\n environmentProviderOptions: environmentProviderOptions,\n dispose: function dispose() {\n if (isDisposed) {\n return;\n }\n releaseQuery();\n cancelNetworkRequest();\n isDisposed = true;\n },\n releaseQuery: releaseQuery,\n cancelNetworkRequest: cancelNetworkRequest,\n fetchKey: fetchKey,\n id: queryId,\n get isDisposed() {\n return isDisposed || isReleased;\n },\n get networkError() {\n return networkError;\n },\n name: params.name,\n networkCacheConfig: networkCacheConfig,\n fetchPolicy: fetchPolicy,\n source: didMakeNetworkRequest ? returnedObservable : undefined,\n variables: variables\n };\n}\nmodule.exports = {\n loadQuery: loadQuery,\n useTrackLoadQueryInRender: useTrackLoadQueryInRender\n};","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _objectSpread2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar useLazyLoadQuery = require('./useLazyLoadQuery');\nfunction useClientQuery(gqlQuery, variables, options) {\n var query = gqlQuery;\n return useLazyLoadQuery(query, variables, (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, options), {}, {\n fetchPolicy: 'store-only'\n }));\n}\nmodule.exports = useClientQuery;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _createForOfIteratorHelper2 = _interopRequireDefault(require(\"@babel/runtime/helpers/createForOfIteratorHelper\"));\nvar loadEntryPoint = require('./loadEntryPoint');\nvar _require = require('./loadQuery'),\n useTrackLoadQueryInRender = _require.useTrackLoadQueryInRender;\nvar useIsMountedRef = require('./useIsMountedRef');\nvar _require2 = require('react'),\n useCallback = _require2.useCallback,\n useEffect = _require2.useEffect,\n useRef = _require2.useRef,\n useState = _require2.useState;\nvar initialNullEntryPointReferenceState = {\n kind: 'NullEntryPointReference'\n};\nfunction useLoadEntryPoint(environmentProvider, entryPoint, options) {\n var _options$TEST_ONLY__i, _options$TEST_ONLY__i2, _options$TEST_ONLY__i3, _options$TEST_ONLY__i4;\n useTrackLoadQueryInRender();\n var initialEntryPointReferenceInternal = (_options$TEST_ONLY__i = options === null || options === void 0 ? void 0 : (_options$TEST_ONLY__i2 = options.TEST_ONLY__initialEntryPointData) === null || _options$TEST_ONLY__i2 === void 0 ? void 0 : _options$TEST_ONLY__i2.entryPointReference) !== null && _options$TEST_ONLY__i !== void 0 ? _options$TEST_ONLY__i : initialNullEntryPointReferenceState;\n var initialEntryPointParamsInternal = (_options$TEST_ONLY__i3 = options === null || options === void 0 ? void 0 : (_options$TEST_ONLY__i4 = options.TEST_ONLY__initialEntryPointData) === null || _options$TEST_ONLY__i4 === void 0 ? void 0 : _options$TEST_ONLY__i4.entryPointParams) !== null && _options$TEST_ONLY__i3 !== void 0 ? _options$TEST_ONLY__i3 : null;\n var isMountedRef = useIsMountedRef();\n var undisposedEntryPointReferencesRef = useRef(new Set([initialEntryPointReferenceInternal]));\n var _useState = useState(initialEntryPointReferenceInternal),\n entryPointReference = _useState[0],\n setEntryPointReference = _useState[1];\n var _useState2 = useState(initialEntryPointParamsInternal),\n entryPointParams = _useState2[0],\n setEntryPointParams = _useState2[1];\n var disposeEntryPoint = useCallback(function () {\n if (isMountedRef.current) {\n var nullEntryPointReference = {\n kind: 'NullEntryPointReference'\n };\n undisposedEntryPointReferencesRef.current.add(nullEntryPointReference);\n setEntryPointReference(nullEntryPointReference);\n }\n }, [setEntryPointReference, isMountedRef]);\n var entryPointLoaderCallback = useCallback(function (params) {\n if (isMountedRef.current) {\n var updatedEntryPointReference = loadEntryPoint(environmentProvider, entryPoint, params);\n undisposedEntryPointReferencesRef.current.add(updatedEntryPointReference);\n setEntryPointReference(updatedEntryPointReference);\n setEntryPointParams(params);\n }\n }, [environmentProvider, entryPoint, setEntryPointReference, isMountedRef]);\n var maybeHiddenOrFastRefresh = useRef(false);\n useEffect(function () {\n return function () {\n maybeHiddenOrFastRefresh.current = true;\n };\n }, []);\n useEffect(function () {\n if (maybeHiddenOrFastRefresh.current === true) {\n maybeHiddenOrFastRefresh.current = false;\n if (entryPointReference.kind !== 'NullEntryPointReference' && entryPointParams != null) {\n entryPointLoaderCallback(entryPointParams);\n }\n return;\n }\n var undisposedEntryPointReferences = undisposedEntryPointReferencesRef.current;\n if (isMountedRef.current) {\n var _iterator = (0, _createForOfIteratorHelper2[\"default\"])(undisposedEntryPointReferences),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var undisposedEntryPointReference = _step.value;\n if (undisposedEntryPointReference === entryPointReference) {\n break;\n }\n undisposedEntryPointReferences[\"delete\"](undisposedEntryPointReference);\n if (undisposedEntryPointReference.kind !== 'NullEntryPointReference') {\n undisposedEntryPointReference.dispose();\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n }\n }, [entryPointReference, entryPointParams, entryPointLoaderCallback, isMountedRef]);\n useEffect(function () {\n return function disposeAllRemainingEntryPointReferences() {\n var _iterator2 = (0, _createForOfIteratorHelper2[\"default\"])(undisposedEntryPointReferencesRef.current),\n _step2;\n try {\n for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n var unhandledStateChange = _step2.value;\n if (unhandledStateChange.kind !== 'NullEntryPointReference') {\n unhandledStateChange.dispose();\n }\n }\n } catch (err) {\n _iterator2.e(err);\n } finally {\n _iterator2.f();\n }\n };\n }, []);\n return [entryPointReference.kind === 'NullEntryPointReference' ? null : entryPointReference, entryPointLoaderCallback, disposeEntryPoint];\n}\nmodule.exports = useLoadEntryPoint;","'use strict';\n\nvar useUnsafeRef_DEPRECATED = require('./useUnsafeRef_DEPRECATED');\nvar _require = require('react'),\n useCallback = _require.useCallback,\n useEffect = _require.useEffect;\nfunction useFetchTrackingRef() {\n var subscriptionRef = useUnsafeRef_DEPRECATED(null);\n var isFetchingRef = useUnsafeRef_DEPRECATED(false);\n var disposeFetch = useCallback(function () {\n if (subscriptionRef.current != null) {\n subscriptionRef.current.unsubscribe();\n subscriptionRef.current = null;\n }\n isFetchingRef.current = false;\n }, []);\n var startFetch = useCallback(function (subscription) {\n subscriptionRef.current = subscription;\n isFetchingRef.current = true;\n }, []);\n var completeFetch = useCallback(function () {\n subscriptionRef.current = null;\n isFetchingRef.current = false;\n }, []);\n useEffect(function () {\n return disposeFetch;\n }, [disposeFetch]);\n return {\n isFetchingRef: isFetchingRef,\n startFetch: startFetch,\n disposeFetch: disposeFetch,\n completeFetch: completeFetch\n };\n}\nmodule.exports = useFetchTrackingRef;","'use strict';\n\nvar HooksImplementation = require('./HooksImplementation');\nvar useFragmentNode = require('./legacy/useFragmentNode');\nvar _require = require('./loadQuery'),\n useTrackLoadQueryInRender = _require.useTrackLoadQueryInRender;\nvar useStaticFragmentNodeWarning = require('./useStaticFragmentNodeWarning');\nvar _require2 = require('react'),\n useDebugValue = _require2.useDebugValue;\nvar _require3 = require('relay-runtime'),\n getFragment = _require3.getFragment;\nfunction useFragment_LEGACY(fragment, key) {\n useTrackLoadQueryInRender();\n var fragmentNode = getFragment(fragment);\n useStaticFragmentNodeWarning(fragmentNode, 'first argument of useFragment()');\n var _useFragmentNode = useFragmentNode(fragmentNode, key, 'useFragment()'),\n data = _useFragmentNode.data;\n if (process.env.NODE_ENV !== \"production\") {\n useDebugValue({\n fragment: fragmentNode.name,\n data: data\n });\n }\n return data;\n}\nfunction useFragment(fragment, key) {\n var impl = HooksImplementation.get();\n if (impl) {\n return impl.useFragment(fragment, key);\n } else {\n return useFragment_LEGACY(fragment, key);\n }\n}\nmodule.exports = useFragment;","'use strict';\n\nvar _require = require('react'),\n useEffect = _require.useEffect,\n useRef = _require.useRef;\nfunction useIsMountedRef() {\n var isMountedRef = useRef(true);\n useEffect(function () {\n isMountedRef.current = true;\n return function () {\n isMountedRef.current = false;\n };\n }, []);\n return isMountedRef;\n}\nmodule.exports = useIsMountedRef;","'use strict';\n\nvar useRelayEnvironment = require('./useRelayEnvironment');\nvar invariant = require('invariant');\nvar React = require('react');\nvar _require = require('relay-runtime'),\n getObservableForActiveRequest = _require.__internal.getObservableForActiveRequest,\n getSelector = _require.getSelector;\nvar useEffect = React.useEffect,\n useState = React.useState,\n useMemo = React.useMemo;\nfunction useIsOperationNodeActive(fragmentNode, fragmentRef) {\n var environment = useRelayEnvironment();\n var observable = useMemo(function () {\n var selector = getSelector(fragmentNode, fragmentRef);\n if (selector == null) {\n return null;\n }\n !(selector.kind === 'SingularReaderSelector') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'useIsOperationNodeActive: Plural fragments are not supported.') : invariant(false) : void 0;\n return getObservableForActiveRequest(environment, selector.owner);\n }, [environment, fragmentNode, fragmentRef]);\n var _useState = useState(observable != null),\n isActive = _useState[0],\n setIsActive = _useState[1];\n useEffect(function () {\n var subscription;\n setIsActive(observable != null);\n if (observable != null) {\n var onCompleteOrError = function onCompleteOrError() {\n setIsActive(false);\n };\n subscription = observable.subscribe({\n complete: onCompleteOrError,\n error: onCompleteOrError\n });\n }\n return function () {\n if (subscription) {\n subscription.unsubscribe();\n }\n };\n }, [observable]);\n return isActive;\n}\nmodule.exports = useIsOperationNodeActive;","'use strict';\n\nvar _require = require('./loadQuery'),\n useTrackLoadQueryInRender = _require.useTrackLoadQueryInRender;\nvar useLazyLoadQueryNode = require('./useLazyLoadQueryNode');\nvar useMemoOperationDescriptor = require('./useMemoOperationDescriptor');\nvar useRelayEnvironment = require('./useRelayEnvironment');\nvar _require2 = require('relay-runtime'),\n fetchQuery = _require2.__internal.fetchQuery;\nfunction useLazyLoadQuery(gqlQuery, variables, options) {\n useTrackLoadQueryInRender();\n var environment = useRelayEnvironment();\n var query = useMemoOperationDescriptor(gqlQuery, variables, options && options.networkCacheConfig ? options.networkCacheConfig : {\n force: true\n });\n var data = useLazyLoadQueryNode({\n componentDisplayName: 'useLazyLoadQuery()',\n fetchKey: options === null || options === void 0 ? void 0 : options.fetchKey,\n fetchObservable: fetchQuery(environment, query),\n fetchPolicy: options === null || options === void 0 ? void 0 : options.fetchPolicy,\n query: query,\n renderPolicy: options === null || options === void 0 ? void 0 : options.UNSTABLE_renderPolicy\n });\n return data;\n}\nmodule.exports = useLazyLoadQuery;","'use strict';\n\nvar HooksImplementation = require('./HooksImplementation');\nvar useFragmentNode = require('./legacy/useFragmentNode');\nvar ProfilerContext = require('./ProfilerContext');\nvar _require = require('./QueryResource'),\n getQueryCacheIdentifier = _require.getQueryCacheIdentifier,\n getQueryResourceForEnvironment = _require.getQueryResourceForEnvironment;\nvar useFetchTrackingRef = require('./useFetchTrackingRef');\nvar useRelayEnvironment = require('./useRelayEnvironment');\nvar React = require('react');\nvar useContext = React.useContext,\n useEffect = React.useEffect,\n useState = React.useState,\n useRef = React.useRef;\nfunction useLazyLoadQueryNode(_ref) {\n var query = _ref.query,\n componentDisplayName = _ref.componentDisplayName,\n fetchObservable = _ref.fetchObservable,\n fetchPolicy = _ref.fetchPolicy,\n fetchKey = _ref.fetchKey,\n renderPolicy = _ref.renderPolicy;\n var environment = useRelayEnvironment();\n var profilerContext = useContext(ProfilerContext);\n var QueryResource = getQueryResourceForEnvironment(environment);\n var _useState = useState(0),\n forceUpdateKey = _useState[0],\n forceUpdate = _useState[1];\n var _useFetchTrackingRef = useFetchTrackingRef(),\n startFetch = _useFetchTrackingRef.startFetch,\n completeFetch = _useFetchTrackingRef.completeFetch;\n var cacheBreaker = \"\".concat(forceUpdateKey, \"-\").concat(fetchKey !== null && fetchKey !== void 0 ? fetchKey : '');\n var cacheIdentifier = getQueryCacheIdentifier(environment, query, fetchPolicy, renderPolicy, cacheBreaker);\n var preparedQueryResult = profilerContext.wrapPrepareQueryResource(function () {\n return QueryResource.prepareWithIdentifier(cacheIdentifier, query, fetchObservable, fetchPolicy, renderPolicy, {\n start: startFetch,\n complete: completeFetch,\n error: completeFetch\n }, profilerContext);\n });\n var maybeHiddenOrFastRefresh = useRef(false);\n useEffect(function () {\n return function () {\n maybeHiddenOrFastRefresh.current = true;\n };\n }, []);\n useEffect(function () {\n if (maybeHiddenOrFastRefresh.current === true) {\n maybeHiddenOrFastRefresh.current = false;\n forceUpdate(function (n) {\n return n + 1;\n });\n return;\n }\n var disposable = QueryResource.retain(preparedQueryResult, profilerContext);\n return function () {\n disposable.dispose();\n };\n }, [environment, cacheIdentifier]);\n useEffect(function () {\n QueryResource.releaseTemporaryRetain(preparedQueryResult);\n });\n var fragmentNode = preparedQueryResult.fragmentNode,\n fragmentRef = preparedQueryResult.fragmentRef;\n var data = useFragmentNodeImpl(fragmentNode, fragmentRef, componentDisplayName);\n return data;\n}\nfunction useFragmentNodeImpl(fragment, key, componentDisplayName) {\n var impl = HooksImplementation.get();\n if (impl && impl.useFragment__internal) {\n return impl.useFragment__internal(fragment, key, componentDisplayName);\n } else {\n var _useFragmentNode = useFragmentNode(fragment, key, componentDisplayName),\n data = _useFragmentNode.data;\n return data;\n }\n}\nmodule.exports = useLazyLoadQueryNode;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _objectSpread2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar useFetchTrackingRef = require('./useFetchTrackingRef');\nvar useIsMountedRef = require('./useIsMountedRef');\nvar useIsOperationNodeActive = require('./useIsOperationNodeActive');\nvar useRelayEnvironment = require('./useRelayEnvironment');\nvar invariant = require('invariant');\nvar _require = require('react'),\n useCallback = _require.useCallback,\n useEffect = _require.useEffect,\n useState = _require.useState;\nvar _require2 = require('relay-runtime'),\n fetchQuery = _require2.__internal.fetchQuery,\n ConnectionInterface = _require2.ConnectionInterface,\n createOperationDescriptor = _require2.createOperationDescriptor,\n getPaginationVariables = _require2.getPaginationVariables,\n getRefetchMetadata = _require2.getRefetchMetadata,\n getSelector = _require2.getSelector,\n getValueAtPath = _require2.getValueAtPath;\nvar warning = require(\"fbjs/lib/warning\");\nfunction useLoadMoreFunction(args) {\n var direction = args.direction,\n fragmentNode = args.fragmentNode,\n fragmentRef = args.fragmentRef,\n fragmentIdentifier = args.fragmentIdentifier,\n fragmentData = args.fragmentData,\n connectionPathInFragmentData = args.connectionPathInFragmentData,\n paginationRequest = args.paginationRequest,\n paginationMetadata = args.paginationMetadata,\n componentDisplayName = args.componentDisplayName,\n observer = args.observer,\n onReset = args.onReset;\n var environment = useRelayEnvironment();\n var _useFetchTrackingRef = useFetchTrackingRef(),\n isFetchingRef = _useFetchTrackingRef.isFetchingRef,\n startFetch = _useFetchTrackingRef.startFetch,\n disposeFetch = _useFetchTrackingRef.disposeFetch,\n completeFetch = _useFetchTrackingRef.completeFetch;\n var _getRefetchMetadata = getRefetchMetadata(fragmentNode, componentDisplayName),\n identifierInfo = _getRefetchMetadata.identifierInfo;\n var identifierValue = (identifierInfo === null || identifierInfo === void 0 ? void 0 : identifierInfo.identifierField) != null && fragmentData != null && typeof fragmentData === 'object' ? fragmentData[identifierInfo.identifierField] : null;\n var isMountedRef = useIsMountedRef();\n var _useState = useState(environment),\n mirroredEnvironment = _useState[0],\n setMirroredEnvironment = _useState[1];\n var _useState2 = useState(fragmentIdentifier),\n mirroredFragmentIdentifier = _useState2[0],\n setMirroredFragmentIdentifier = _useState2[1];\n var isParentQueryActive = useIsOperationNodeActive(fragmentNode, fragmentRef);\n var shouldReset = environment !== mirroredEnvironment || fragmentIdentifier !== mirroredFragmentIdentifier;\n if (shouldReset) {\n disposeFetch();\n onReset();\n setMirroredEnvironment(environment);\n setMirroredFragmentIdentifier(fragmentIdentifier);\n }\n var _getConnectionState = getConnectionState(direction, fragmentNode, fragmentData, connectionPathInFragmentData),\n cursor = _getConnectionState.cursor,\n hasMore = _getConnectionState.hasMore;\n useEffect(function () {\n return function () {\n disposeFetch();\n };\n }, [disposeFetch]);\n var loadMore = useCallback(function (count, options) {\n var onComplete = options === null || options === void 0 ? void 0 : options.onComplete;\n if (isMountedRef.current !== true) {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'Relay: Unexpected fetch on unmounted component for fragment ' + '`%s` in `%s`. It looks like some instances of your component are ' + 'still trying to fetch data but they already unmounted. ' + 'Please make sure you clear all timers, intervals, ' + 'async calls, etc that may trigger a fetch.', fragmentNode.name, componentDisplayName) : void 0;\n return {\n dispose: function dispose() {}\n };\n }\n var fragmentSelector = getSelector(fragmentNode, fragmentRef);\n if (isFetchingRef.current === true || fragmentData == null || isParentQueryActive) {\n if (fragmentSelector == null) {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'Relay: Unexpected fetch while using a null fragment ref ' + 'for fragment `%s` in `%s`. When fetching more items, we expect ' + \"initial fragment data to be non-null. Please make sure you're \" + 'passing a valid fragment ref to `%s` before paginating.', fragmentNode.name, componentDisplayName, componentDisplayName) : void 0;\n }\n if (onComplete) {\n onComplete(null);\n }\n return {\n dispose: function dispose() {}\n };\n }\n !(fragmentSelector != null && fragmentSelector.kind !== 'PluralReaderSelector') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: Expected to be able to find a non-plural fragment owner for ' + \"fragment `%s` when using `%s`. If you're seeing this, \" + 'this is likely a bug in Relay.', fragmentNode.name, componentDisplayName) : invariant(false) : void 0;\n var parentVariables = fragmentSelector.owner.variables;\n var fragmentVariables = fragmentSelector.variables;\n var extraVariables = options === null || options === void 0 ? void 0 : options.UNSTABLE_extraVariables;\n var baseVariables = (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, parentVariables), fragmentVariables);\n var paginationVariables = getPaginationVariables(direction, count, cursor, baseVariables, (0, _objectSpread2[\"default\"])({}, extraVariables), paginationMetadata);\n if (identifierInfo != null) {\n if (typeof identifierValue !== 'string') {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'Relay: Expected result to have a string ' + '`%s` in order to refetch, got `%s`.', identifierInfo.identifierField, identifierValue) : void 0;\n }\n paginationVariables[identifierInfo.identifierQueryVariableName] = identifierValue;\n }\n var paginationQuery = createOperationDescriptor(paginationRequest, paginationVariables, {\n force: true\n });\n fetchQuery(environment, paginationQuery).subscribe((0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, observer), {}, {\n start: function start(subscription) {\n startFetch(subscription);\n observer.start && observer.start(subscription);\n },\n complete: function complete() {\n completeFetch();\n observer.complete && observer.complete();\n onComplete && onComplete(null);\n },\n error: function error(_error) {\n completeFetch();\n observer.error && observer.error(_error);\n onComplete && onComplete(_error);\n }\n }));\n return {\n dispose: disposeFetch\n };\n }, [environment, identifierValue, direction, cursor, startFetch, disposeFetch, completeFetch, isFetchingRef, isParentQueryActive, fragmentData, fragmentNode.name, fragmentRef, componentDisplayName]);\n return [loadMore, hasMore, disposeFetch];\n}\nfunction getConnectionState(direction, fragmentNode, fragmentData, connectionPathInFragmentData) {\n var _pageInfo$END_CURSOR, _pageInfo$START_CURSO;\n var _ConnectionInterface$ = ConnectionInterface.get(),\n EDGES = _ConnectionInterface$.EDGES,\n PAGE_INFO = _ConnectionInterface$.PAGE_INFO,\n HAS_NEXT_PAGE = _ConnectionInterface$.HAS_NEXT_PAGE,\n HAS_PREV_PAGE = _ConnectionInterface$.HAS_PREV_PAGE,\n END_CURSOR = _ConnectionInterface$.END_CURSOR,\n START_CURSOR = _ConnectionInterface$.START_CURSOR;\n var connection = getValueAtPath(fragmentData, connectionPathInFragmentData);\n if (connection == null) {\n return {\n cursor: null,\n hasMore: false\n };\n }\n !(typeof connection === 'object') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: Expected connection in fragment `%s` to have been `null`, or ' + 'a plain object with %s and %s properties. Instead got `%s`.', fragmentNode.name, EDGES, PAGE_INFO, connection) : invariant(false) : void 0;\n var edges = connection[EDGES];\n var pageInfo = connection[PAGE_INFO];\n if (edges == null || pageInfo == null) {\n return {\n cursor: null,\n hasMore: false\n };\n }\n !Array.isArray(edges) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: Expected connection in fragment `%s` to have a plural `%s` field. ' + 'Instead got `%s`.', fragmentNode.name, EDGES, edges) : invariant(false) : void 0;\n !(typeof pageInfo === 'object') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: Expected connection in fragment `%s` to have a `%s` field. ' + 'Instead got `%s`.', fragmentNode.name, PAGE_INFO, pageInfo) : invariant(false) : void 0;\n var cursor = direction === 'forward' ? (_pageInfo$END_CURSOR = pageInfo[END_CURSOR]) !== null && _pageInfo$END_CURSOR !== void 0 ? _pageInfo$END_CURSOR : null : (_pageInfo$START_CURSO = pageInfo[START_CURSOR]) !== null && _pageInfo$START_CURSO !== void 0 ? _pageInfo$START_CURSO : null;\n !(cursor === null || typeof cursor === 'string') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: Expected page info for connection in fragment `%s` to have a ' + 'valid `%s`. Instead got `%s`.', fragmentNode.name, START_CURSOR, cursor) : invariant(false) : void 0;\n var hasMore;\n if (direction === 'forward') {\n hasMore = cursor != null && pageInfo[HAS_NEXT_PAGE] === true;\n } else {\n hasMore = cursor != null && pageInfo[HAS_PREV_PAGE] === true;\n }\n return {\n cursor: cursor,\n hasMore: hasMore\n };\n}\nmodule.exports = useLoadMoreFunction;","'use strict';\n\nvar useMemoVariables = require('./useMemoVariables');\nvar React = require('react');\nvar _require = require('relay-runtime'),\n createOperationDescriptor = _require.createOperationDescriptor,\n getRequest = _require.getRequest;\nvar useMemo = React.useMemo;\nfunction useMemoOperationDescriptor(gqlQuery, variables, cacheConfig) {\n var memoVariables = useMemoVariables(variables);\n var memoCacheConfig = useMemoVariables(cacheConfig || {});\n return useMemo(function () {\n return createOperationDescriptor(getRequest(gqlQuery), memoVariables, memoCacheConfig);\n }, [gqlQuery, memoVariables, memoCacheConfig]);\n}\nmodule.exports = useMemoOperationDescriptor;","'use strict';\n\nvar areEqual = require(\"fbjs/lib/areEqual\");\nvar _require = require('react'),\n useState = _require.useState;\nfunction useMemoVariables(variables) {\n var _useState = useState(variables),\n mirroredVariables = _useState[0],\n setMirroredVariables = _useState[1];\n if (areEqual(variables, mirroredVariables)) {\n return mirroredVariables;\n } else {\n setMirroredVariables(variables);\n return variables;\n }\n}\nmodule.exports = useMemoVariables;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _objectSpread2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar useIsMountedRef = require('./useIsMountedRef');\nvar useRelayEnvironment = require('./useRelayEnvironment');\nvar React = require('react');\nvar _require = require('relay-runtime'),\n defaultCommitMutation = _require.commitMutation;\nvar useState = React.useState,\n useEffect = React.useEffect,\n useRef = React.useRef,\n useCallback = React.useCallback;\nfunction useMutation(mutation) {\n var commitMutationFn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultCommitMutation;\n var environment = useRelayEnvironment();\n var isMountedRef = useIsMountedRef();\n var environmentRef = useRef(environment);\n var mutationRef = useRef(mutation);\n var inFlightMutationsRef = useRef(new Set());\n var _useState = useState(false),\n isMutationInFlight = _useState[0],\n setMutationInFlight = _useState[1];\n var cleanup = useCallback(function (disposable) {\n if (environmentRef.current === environment && mutationRef.current === mutation) {\n inFlightMutationsRef.current[\"delete\"](disposable);\n if (isMountedRef.current) {\n setMutationInFlight(inFlightMutationsRef.current.size > 0);\n }\n }\n }, [environment, isMountedRef, mutation]);\n useEffect(function () {\n if (environmentRef.current !== environment || mutationRef.current !== mutation) {\n inFlightMutationsRef.current = new Set();\n if (isMountedRef.current) {\n setMutationInFlight(false);\n }\n environmentRef.current = environment;\n mutationRef.current = mutation;\n }\n }, [environment, isMountedRef, mutation]);\n var commit = useCallback(function (config) {\n if (isMountedRef.current) {\n setMutationInFlight(true);\n }\n var disposable = commitMutationFn(environment, (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, config), {}, {\n mutation: mutation,\n onCompleted: function onCompleted(response, errors) {\n var _config$onCompleted;\n cleanup(disposable);\n (_config$onCompleted = config.onCompleted) === null || _config$onCompleted === void 0 ? void 0 : _config$onCompleted.call(config, response, errors);\n },\n onError: function onError(error) {\n var _config$onError;\n cleanup(disposable);\n (_config$onError = config.onError) === null || _config$onError === void 0 ? void 0 : _config$onError.call(config, error);\n },\n onUnsubscribe: function onUnsubscribe() {\n var _config$onUnsubscribe;\n cleanup(disposable);\n (_config$onUnsubscribe = config.onUnsubscribe) === null || _config$onUnsubscribe === void 0 ? void 0 : _config$onUnsubscribe.call(config);\n },\n onNext: function onNext() {\n var _config$onNext;\n (_config$onNext = config.onNext) === null || _config$onNext === void 0 ? void 0 : _config$onNext.call(config);\n }\n }));\n inFlightMutationsRef.current.add(disposable);\n return disposable;\n }, [cleanup, commitMutationFn, environment, isMountedRef, mutation]);\n return [commit, isMutationInFlight];\n}\nmodule.exports = useMutation;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _objectSpread2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar HooksImplementation = require('./HooksImplementation');\nvar useRefetchableFragmentNode = require('./legacy/useRefetchableFragmentNode');\nvar useLoadMoreFunction = require('./useLoadMoreFunction');\nvar useStaticFragmentNodeWarning = require('./useStaticFragmentNodeWarning');\nvar _require = require('react'),\n useCallback = _require.useCallback,\n useDebugValue = _require.useDebugValue,\n useState = _require.useState;\nvar _require2 = require('relay-runtime'),\n getFragment = _require2.getFragment,\n getFragmentIdentifier = _require2.getFragmentIdentifier,\n getPaginationMetadata = _require2.getPaginationMetadata;\nfunction usePaginationFragment_LEGACY(fragmentInput, parentFragmentRef) {\n var fragmentNode = getFragment(fragmentInput);\n useStaticFragmentNodeWarning(fragmentNode, 'first argument of usePaginationFragment()');\n var componentDisplayName = 'usePaginationFragment()';\n var _getPaginationMetadat = getPaginationMetadata(fragmentNode, componentDisplayName),\n connectionPathInFragmentData = _getPaginationMetadat.connectionPathInFragmentData,\n paginationRequest = _getPaginationMetadat.paginationRequest,\n paginationMetadata = _getPaginationMetadat.paginationMetadata;\n var _useRefetchableFragme = useRefetchableFragmentNode(fragmentNode, parentFragmentRef, componentDisplayName),\n fragmentData = _useRefetchableFragme.fragmentData,\n fragmentRef = _useRefetchableFragme.fragmentRef,\n refetch = _useRefetchableFragme.refetch;\n var fragmentIdentifier = getFragmentIdentifier(fragmentNode, fragmentRef);\n var _useLoadMore = useLoadMore({\n componentDisplayName: componentDisplayName,\n connectionPathInFragmentData: connectionPathInFragmentData,\n direction: 'backward',\n fragmentData: fragmentData,\n fragmentIdentifier: fragmentIdentifier,\n fragmentNode: fragmentNode,\n fragmentRef: fragmentRef,\n paginationMetadata: paginationMetadata,\n paginationRequest: paginationRequest\n }),\n loadPrevious = _useLoadMore[0],\n hasPrevious = _useLoadMore[1],\n isLoadingPrevious = _useLoadMore[2],\n disposeFetchPrevious = _useLoadMore[3];\n var _useLoadMore2 = useLoadMore({\n componentDisplayName: componentDisplayName,\n connectionPathInFragmentData: connectionPathInFragmentData,\n direction: 'forward',\n fragmentData: fragmentData,\n fragmentIdentifier: fragmentIdentifier,\n fragmentNode: fragmentNode,\n fragmentRef: fragmentRef,\n paginationMetadata: paginationMetadata,\n paginationRequest: paginationRequest\n }),\n loadNext = _useLoadMore2[0],\n hasNext = _useLoadMore2[1],\n isLoadingNext = _useLoadMore2[2],\n disposeFetchNext = _useLoadMore2[3];\n var refetchPagination = useCallback(function (variables, options) {\n disposeFetchNext();\n disposeFetchPrevious();\n return refetch(variables, (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, options), {}, {\n __environment: undefined\n }));\n }, [disposeFetchNext, disposeFetchPrevious, refetch]);\n if (process.env.NODE_ENV !== \"production\") {\n useDebugValue({\n fragment: fragmentNode.name,\n data: fragmentData,\n hasNext: hasNext,\n isLoadingNext: isLoadingNext,\n hasPrevious: hasPrevious,\n isLoadingPrevious: isLoadingPrevious\n });\n }\n return {\n data: fragmentData,\n loadNext: loadNext,\n loadPrevious: loadPrevious,\n hasNext: hasNext,\n hasPrevious: hasPrevious,\n isLoadingNext: isLoadingNext,\n isLoadingPrevious: isLoadingPrevious,\n refetch: refetchPagination\n };\n}\nfunction useLoadMore(args) {\n var _useState = useState(false),\n isLoadingMore = _useState[0],\n setIsLoadingMore = _useState[1];\n var observer = {\n start: function start() {\n return setIsLoadingMore(true);\n },\n complete: function complete() {\n return setIsLoadingMore(false);\n },\n error: function error() {\n return setIsLoadingMore(false);\n }\n };\n var handleReset = function handleReset() {\n return setIsLoadingMore(false);\n };\n var _useLoadMoreFunction = useLoadMoreFunction((0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, args), {}, {\n observer: observer,\n onReset: handleReset\n })),\n loadMore = _useLoadMoreFunction[0],\n hasMore = _useLoadMoreFunction[1],\n disposeFetch = _useLoadMoreFunction[2];\n return [loadMore, hasMore, isLoadingMore, disposeFetch];\n}\nfunction usePaginationFragment(fragmentInput, parentFragmentRef) {\n var impl = HooksImplementation.get();\n if (impl) {\n return impl.usePaginationFragment(fragmentInput, parentFragmentRef);\n } else {\n return usePaginationFragment_LEGACY(fragmentInput, parentFragmentRef);\n }\n}\nmodule.exports = usePaginationFragment;","'use strict';\n\nvar _require = require('./loadQuery'),\n useTrackLoadQueryInRender = _require.useTrackLoadQueryInRender;\nvar useLazyLoadQueryNode = require('./useLazyLoadQueryNode');\nvar useMemoOperationDescriptor = require('./useMemoOperationDescriptor');\nvar useRelayEnvironment = require('./useRelayEnvironment');\nvar invariant = require('invariant');\nvar _require2 = require('react'),\n useDebugValue = _require2.useDebugValue;\nvar _require3 = require('relay-runtime'),\n _require3$__internal = _require3.__internal,\n fetchQueryDeduped = _require3$__internal.fetchQueryDeduped,\n fetchQuery = _require3$__internal.fetchQuery;\nvar warning = require(\"fbjs/lib/warning\");\nfunction usePreloadedQuery(gqlQuery, preloadedQuery, options) {\n useTrackLoadQueryInRender();\n var environment = useRelayEnvironment();\n var fetchKey = preloadedQuery.fetchKey,\n fetchPolicy = preloadedQuery.fetchPolicy,\n source = preloadedQuery.source,\n variables = preloadedQuery.variables,\n networkCacheConfig = preloadedQuery.networkCacheConfig;\n var operation = useMemoOperationDescriptor(gqlQuery, variables, networkCacheConfig);\n var useLazyLoadQueryNodeParams;\n if (preloadedQuery.kind === 'PreloadedQuery_DEPRECATED') {\n !(operation.request.node.params.name === preloadedQuery.name) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'usePreloadedQuery(): Expected data to be prefetched for query `%s`, ' + 'got prefetch results for query `%s`.', operation.request.node.params.name, preloadedQuery.name) : invariant(false) : void 0;\n useLazyLoadQueryNodeParams = {\n componentDisplayName: 'usePreloadedQuery()',\n fetchKey: fetchKey,\n fetchObservable: fetchQueryDeduped(environment, operation.request.identifier, function () {\n if (environment === preloadedQuery.environment && source != null) {\n return environment.executeWithSource({\n operation: operation,\n source: source\n });\n } else {\n return environment.execute({\n operation: operation\n });\n }\n }),\n fetchPolicy: fetchPolicy,\n query: operation,\n renderPolicy: options === null || options === void 0 ? void 0 : options.UNSTABLE_renderPolicy\n };\n } else {\n process.env.NODE_ENV !== \"production\" ? warning(preloadedQuery.isDisposed === false, 'usePreloadedQuery(): Expected preloadedQuery to not be disposed yet. ' + 'This is because disposing the query marks it for future garbage ' + 'collection, and as such query results may no longer be present in the Relay ' + 'store. In the future, this will become a hard error.') : void 0;\n var fallbackFetchObservable = fetchQuery(environment, operation);\n var fetchObservable;\n if (source != null && environment === preloadedQuery.environment) {\n fetchObservable = source.ifEmpty(fallbackFetchObservable);\n } else if (environment !== preloadedQuery.environment) {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'usePreloadedQuery(): usePreloadedQuery was passed a preloaded query ' + 'that was created with a different environment than the one that is currently ' + 'in context. In the future, this will become a hard error.') : void 0;\n fetchObservable = fallbackFetchObservable;\n } else {\n fetchObservable = fallbackFetchObservable;\n }\n useLazyLoadQueryNodeParams = {\n componentDisplayName: 'usePreloadedQuery()',\n fetchObservable: fetchObservable,\n fetchKey: fetchKey,\n fetchPolicy: fetchPolicy,\n query: operation,\n renderPolicy: options === null || options === void 0 ? void 0 : options.UNSTABLE_renderPolicy\n };\n }\n var data = useLazyLoadQueryNode(useLazyLoadQueryNodeParams);\n if (process.env.NODE_ENV !== \"production\") {\n useDebugValue({\n query: preloadedQuery.name,\n variables: preloadedQuery.variables,\n data: data,\n fetchKey: fetchKey,\n fetchPolicy: fetchPolicy,\n renderPolicy: options === null || options === void 0 ? void 0 : options.UNSTABLE_renderPolicy\n });\n }\n return data;\n}\nmodule.exports = usePreloadedQuery;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _createForOfIteratorHelper2 = _interopRequireDefault(require(\"@babel/runtime/helpers/createForOfIteratorHelper\"));\nvar _require = require('./loadQuery'),\n loadQuery = _require.loadQuery,\n useTrackLoadQueryInRender = _require.useTrackLoadQueryInRender;\nvar useIsMountedRef = require('./useIsMountedRef');\nvar useRelayEnvironment = require('./useRelayEnvironment');\nvar _require2 = require('react'),\n useCallback = _require2.useCallback,\n useEffect = _require2.useEffect,\n useRef = _require2.useRef,\n useState = _require2.useState;\nvar _require3 = require('relay-runtime'),\n getRequest = _require3.getRequest;\nvar initialNullQueryReferenceState = {\n kind: 'NullQueryReference'\n};\nfunction requestIsLiveQuery(preloadableRequest) {\n if (preloadableRequest.kind === 'PreloadableConcreteRequest') {\n return preloadableRequest.params.metadata.live !== undefined;\n }\n var request = getRequest(preloadableRequest);\n return request.params.metadata.live !== undefined;\n}\nfunction useQueryLoader(preloadableRequest, initialQueryReference) {\n var initialQueryReferenceInternal = initialQueryReference !== null && initialQueryReference !== void 0 ? initialQueryReference : initialNullQueryReferenceState;\n var environment = useRelayEnvironment();\n useTrackLoadQueryInRender();\n var isMountedRef = useIsMountedRef();\n var undisposedQueryReferencesRef = useRef(new Set([initialQueryReferenceInternal]));\n var _useState = useState(function () {\n return initialQueryReferenceInternal;\n }),\n queryReference = _useState[0],\n setQueryReference = _useState[1];\n var _useState2 = useState(function () {\n return initialQueryReferenceInternal;\n }),\n previousInitialQueryReference = _useState2[0],\n setPreviousInitialQueryReference = _useState2[1];\n if (initialQueryReferenceInternal !== previousInitialQueryReference) {\n undisposedQueryReferencesRef.current.add(initialQueryReferenceInternal);\n setPreviousInitialQueryReference(initialQueryReferenceInternal);\n setQueryReference(initialQueryReferenceInternal);\n }\n var disposeQuery = useCallback(function () {\n if (isMountedRef.current) {\n undisposedQueryReferencesRef.current.add(initialNullQueryReferenceState);\n setQueryReference(initialNullQueryReferenceState);\n }\n }, [isMountedRef]);\n var queryLoaderCallback = useCallback(function (variables, options) {\n var mergedOptions = options != null && options.hasOwnProperty('__environment') ? {\n fetchPolicy: options.fetchPolicy,\n networkCacheConfig: options.networkCacheConfig,\n __nameForWarning: options.__nameForWarning\n } : options;\n if (isMountedRef.current) {\n var _options$__environmen;\n var updatedQueryReference = loadQuery((_options$__environmen = options === null || options === void 0 ? void 0 : options.__environment) !== null && _options$__environmen !== void 0 ? _options$__environmen : environment, preloadableRequest, variables, mergedOptions);\n undisposedQueryReferencesRef.current.add(updatedQueryReference);\n setQueryReference(updatedQueryReference);\n }\n }, [environment, preloadableRequest, setQueryReference, isMountedRef]);\n var maybeHiddenOrFastRefresh = useRef(false);\n useEffect(function () {\n return function () {\n maybeHiddenOrFastRefresh.current = true;\n };\n }, []);\n useEffect(function () {\n if (maybeHiddenOrFastRefresh.current === true) {\n maybeHiddenOrFastRefresh.current = false;\n if (queryReference.kind !== 'NullQueryReference') {\n queryLoaderCallback(queryReference.variables, {\n fetchPolicy: queryReference.fetchPolicy,\n networkCacheConfig: queryReference.networkCacheConfig\n });\n }\n return;\n }\n var undisposedQueryReferences = undisposedQueryReferencesRef.current;\n if (isMountedRef.current) {\n var _iterator = (0, _createForOfIteratorHelper2[\"default\"])(undisposedQueryReferences),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var undisposedQueryReference = _step.value;\n if (undisposedQueryReference === queryReference) {\n break;\n }\n undisposedQueryReferences[\"delete\"](undisposedQueryReference);\n if (undisposedQueryReference.kind !== 'NullQueryReference') {\n if (requestIsLiveQuery(preloadableRequest)) {\n undisposedQueryReference.dispose && undisposedQueryReference.dispose();\n } else {\n undisposedQueryReference.releaseQuery && undisposedQueryReference.releaseQuery();\n }\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n }\n }, [queryReference, isMountedRef, queryLoaderCallback, preloadableRequest]);\n useEffect(function () {\n return function disposeAllRemainingQueryReferences() {\n var _iterator2 = (0, _createForOfIteratorHelper2[\"default\"])(undisposedQueryReferencesRef.current),\n _step2;\n try {\n for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n var undisposedQueryReference = _step2.value;\n if (undisposedQueryReference.kind !== 'NullQueryReference') {\n if (requestIsLiveQuery(preloadableRequest)) {\n undisposedQueryReference.dispose && undisposedQueryReference.dispose();\n } else {\n undisposedQueryReference.releaseQuery && undisposedQueryReference.releaseQuery();\n }\n }\n }\n } catch (err) {\n _iterator2.e(err);\n } finally {\n _iterator2.f();\n }\n };\n }, [preloadableRequest]);\n return [queryReference.kind === 'NullQueryReference' ? null : queryReference, queryLoaderCallback, disposeQuery];\n}\nmodule.exports = useQueryLoader;","'use strict';\n\nvar HooksImplementation = require('./HooksImplementation');\nvar useRefetchableFragmentNode = require('./legacy/useRefetchableFragmentNode');\nvar useStaticFragmentNodeWarning = require('./useStaticFragmentNodeWarning');\nvar _require = require('react'),\n useDebugValue = _require.useDebugValue;\nvar _require2 = require('relay-runtime'),\n getFragment = _require2.getFragment;\nfunction useRefetchableFragment_LEGACY(fragmentInput, fragmentRef) {\n var fragmentNode = getFragment(fragmentInput);\n useStaticFragmentNodeWarning(fragmentNode, 'first argument of useRefetchableFragment()');\n var _useRefetchableFragme = useRefetchableFragmentNode(fragmentNode, fragmentRef, 'useRefetchableFragment()'),\n fragmentData = _useRefetchableFragme.fragmentData,\n refetch = _useRefetchableFragme.refetch;\n if (process.env.NODE_ENV !== \"production\") {\n useDebugValue({\n fragment: fragmentNode.name,\n data: fragmentData\n });\n }\n return [fragmentData, refetch];\n}\nfunction useRefetchableFragment(fragmentInput, parentFragmentRef) {\n var impl = HooksImplementation.get();\n if (impl) {\n return impl.useRefetchableFragment(fragmentInput, parentFragmentRef);\n } else {\n return useRefetchableFragment_LEGACY(fragmentInput, parentFragmentRef);\n }\n}\nmodule.exports = useRefetchableFragment;","'use strict';\n\nvar ReactRelayContext = require('./../ReactRelayContext');\nvar invariant = require('invariant');\nvar _require = require('react'),\n useContext = _require.useContext;\nfunction useRelayEnvironment() {\n var context = useContext(ReactRelayContext);\n !(context != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'useRelayEnvironment: Expected to have found a Relay environment provided by ' + 'a `RelayEnvironmentProvider` component. ' + 'This usually means that useRelayEnvironment was used in a ' + 'component that is not a descendant of a `RelayEnvironmentProvider`. ' + 'Please make sure a `RelayEnvironmentProvider` has been rendered somewhere ' + 'as a parent or ancestor of your component.') : invariant(false) : void 0;\n return context.environment;\n}\nmodule.exports = useRelayEnvironment;","'use strict';\n\nvar useUnsafeRef_DEPRECATED = require('./useUnsafeRef_DEPRECATED');\nvar warning = require(\"fbjs/lib/warning\");\nfunction useStaticFragmentNodeWarning(fragmentNode, warningContext) {\n if (process.env.NODE_ENV !== \"production\") {\n var initialPropRef = useUnsafeRef_DEPRECATED(fragmentNode.name);\n process.env.NODE_ENV !== \"production\" ? warning(initialPropRef.current === fragmentNode.name, 'Relay: The %s has to remain the same over the lifetime of a component. ' + 'Changing it is not supported and will result in unexpected behavior.', warningContext) : void 0;\n }\n}\nmodule.exports = useStaticFragmentNodeWarning;","'use strict';\n\nvar useRelayEnvironment = require('./useRelayEnvironment');\nvar _require = require('react'),\n useEffect = _require.useEffect,\n useRef = _require.useRef;\nfunction useSubscribeToInvalidationState(dataIDs, callback) {\n var environment = useRelayEnvironment();\n var disposableRef = useRef(null);\n var stableDataIDs = Array.from(dataIDs).sort().join('');\n useEffect(function () {\n var store = environment.getStore();\n var invalidationState = store.lookupInvalidationState(dataIDs);\n var disposable = store.subscribeToInvalidationState(invalidationState, callback);\n disposableRef.current = disposable;\n return function () {\n return disposable.dispose();\n };\n }, [stableDataIDs, callback, environment]);\n return {\n dispose: function dispose() {\n if (disposableRef.current != null) {\n disposableRef.current.dispose();\n }\n }\n };\n}\nmodule.exports = useSubscribeToInvalidationState;","'use strict';\n\nvar useRelayEnvironment = require('./useRelayEnvironment');\nvar _require = require('react'),\n useEffect = _require.useEffect;\nvar _require2 = require('relay-runtime'),\n requestSubscription = _require2.requestSubscription;\nfunction useSubscription(config, requestSubscriptionFn) {\n var actualRequestSubscription = requestSubscriptionFn !== null && requestSubscriptionFn !== void 0 ? requestSubscriptionFn : requestSubscription;\n var environment = useRelayEnvironment();\n useEffect(function () {\n var _actualRequestSubscri = actualRequestSubscription(environment, config),\n dispose = _actualRequestSubscri.dispose;\n return dispose;\n }, [environment, config, actualRequestSubscription]);\n}\nmodule.exports = useSubscription;","'use strict';\n\nvar _require = require('react'),\n useMemo = _require.useMemo;\nfunction useUnsafeRef_DEPRECATED(init) {\n return useMemo(function () {\n return {\n current: init\n };\n }, []);\n}\nmodule.exports = useUnsafeRef_DEPRECATED;","import React from 'react';\nimport PropTypes from 'prop-types';\nimport { Link, NavLink } from 'react-router-dom';\n\n/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nvar __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n return __assign.apply(this, arguments);\r\n};\r\n\r\nfunction __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\n\nvar hashFragment = '';\r\nvar observer = null;\r\nvar asyncTimerId = null;\r\nvar scrollFunction = null;\r\nfunction reset() {\r\n hashFragment = '';\r\n if (observer !== null)\r\n observer.disconnect();\r\n if (asyncTimerId !== null) {\r\n window.clearTimeout(asyncTimerId);\r\n asyncTimerId = null;\r\n }\r\n}\r\nfunction isInteractiveElement(element) {\r\n var formTags = ['BUTTON', 'INPUT', 'SELECT', 'TEXTAREA'];\r\n var linkTags = ['A', 'AREA'];\r\n return ((formTags.includes(element.tagName) && !element.hasAttribute('disabled')) ||\r\n (linkTags.includes(element.tagName) && element.hasAttribute('href')));\r\n}\r\nfunction getElAndScroll() {\r\n var element = null;\r\n if (hashFragment === '#') {\r\n // use document.body instead of document.documentElement because of a bug in smoothscroll-polyfill in safari\r\n // see https://github.com/iamdustan/smoothscroll/issues/138\r\n // while smoothscroll-polyfill is not included, it is the recommended way to implement smoothscroll\r\n // in browsers that don't natively support el.scrollIntoView({ behavior: 'smooth' })\r\n element = document.body;\r\n }\r\n else {\r\n // check for element with matching id before assume '#top' is the top of the document\r\n // see https://html.spec.whatwg.org/multipage/browsing-the-web.html#target-element\r\n var id = hashFragment.replace('#', '');\r\n element = document.getElementById(id);\r\n if (element === null && hashFragment === '#top') {\r\n // see above comment for why document.body instead of document.documentElement\r\n element = document.body;\r\n }\r\n }\r\n if (element !== null) {\r\n scrollFunction(element);\r\n // update focus to where the page is scrolled to\r\n // unfortunately this doesn't work in safari (desktop and iOS) when blur() is called\r\n var originalTabIndex = element.getAttribute('tabindex');\r\n if (originalTabIndex === null && !isInteractiveElement(element)) {\r\n element.setAttribute('tabindex', -1);\r\n }\r\n element.focus({ preventScroll: true });\r\n if (originalTabIndex === null && !isInteractiveElement(element)) {\r\n // for some reason calling blur() in safari resets the focus region to where it was previously,\r\n // if blur() is not called it works in safari, but then are stuck with default focus styles\r\n // on an element that otherwise might never had focus styles applied, so not an option\r\n element.blur();\r\n element.removeAttribute('tabindex');\r\n }\r\n reset();\r\n return true;\r\n }\r\n return false;\r\n}\r\nfunction hashLinkScroll(timeout) {\r\n // Push onto callback queue so it runs after the DOM is updated\r\n window.setTimeout(function () {\r\n if (getElAndScroll() === false) {\r\n if (observer === null) {\r\n observer = new MutationObserver(getElAndScroll);\r\n }\r\n observer.observe(document, {\r\n attributes: true,\r\n childList: true,\r\n subtree: true,\r\n });\r\n // if the element doesn't show up in specified timeout or 10 seconds, stop checking\r\n asyncTimerId = window.setTimeout(function () {\r\n reset();\r\n }, timeout || 10000);\r\n }\r\n }, 0);\r\n}\r\nfunction genericHashLink(As) {\r\n return React.forwardRef(function (props, ref) {\r\n var linkHash = '';\r\n if (typeof props.to === 'string' && props.to.includes('#')) {\r\n linkHash = \"#\" + props.to.split('#').slice(1).join('#');\r\n }\r\n else if (typeof props.to === 'object' &&\r\n typeof props.to.hash === 'string') {\r\n linkHash = props.to.hash;\r\n }\r\n var passDownProps = {};\r\n if (As === NavLink) {\r\n passDownProps.isActive = function (match, location) {\r\n return match && match.isExact && location.hash === linkHash;\r\n };\r\n }\r\n function handleClick(e) {\r\n reset();\r\n hashFragment = props.elementId ? \"#\" + props.elementId : linkHash;\r\n if (props.onClick)\r\n props.onClick(e);\r\n if (hashFragment !== '' &&\r\n // ignore non-vanilla click events, same as react-router\r\n // below logic adapted from react-router: https://github.com/ReactTraining/react-router/blob/fc91700e08df8147bd2bb1be19a299cbb14dbcaa/packages/react-router-dom/modules/Link.js#L43-L48\r\n !e.defaultPrevented && // onClick prevented default\r\n e.button === 0 && // ignore everything but left clicks\r\n (!props.target || props.target === '_self') && // let browser handle \"target=_blank\" etc\r\n !(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) // ignore clicks with modifier keys\r\n ) {\r\n scrollFunction =\r\n props.scroll ||\r\n (function (el) {\r\n return props.smooth\r\n ? el.scrollIntoView({ behavior: 'smooth' })\r\n : el.scrollIntoView();\r\n });\r\n hashLinkScroll(props.timeout);\r\n }\r\n }\r\n var filteredProps = __rest(props, [\"scroll\", \"smooth\", \"timeout\", \"elementId\"]);\r\n return (React.createElement(As, __assign({}, passDownProps, filteredProps, { onClick: handleClick, ref: ref }), props.children));\r\n });\r\n}\r\nvar HashLink = genericHashLink(Link);\r\nvar NavHashLink = genericHashLink(NavLink);\r\nif (process.env.NODE_ENV !== 'production') {\r\n HashLink.displayName = 'HashLink';\r\n NavHashLink.displayName = 'NavHashLink';\r\n var propTypes = {\r\n onClick: PropTypes.func,\r\n children: PropTypes.node,\r\n scroll: PropTypes.func,\r\n timeout: PropTypes.number,\r\n elementId: PropTypes.string,\r\n to: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),\r\n };\r\n HashLink.propTypes = propTypes;\r\n NavHashLink.propTypes = propTypes;\r\n}\n\nexport { HashLink, NavHashLink, genericHashLink };\n//# sourceMappingURL=react-router-hash-link.esm.js.map\n","'use strict';\n\nfunction _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\nvar React = require('react');\nvar React__default = _interopDefault(React);\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nfunction _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n subClass.__proto__ = superClass;\n}\n\nvar canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);\nfunction withSideEffect(reducePropsToState, handleStateChangeOnClient, mapStateOnServer) {\n if (typeof reducePropsToState !== 'function') {\n throw new Error('Expected reducePropsToState to be a function.');\n }\n\n if (typeof handleStateChangeOnClient !== 'function') {\n throw new Error('Expected handleStateChangeOnClient to be a function.');\n }\n\n if (typeof mapStateOnServer !== 'undefined' && typeof mapStateOnServer !== 'function') {\n throw new Error('Expected mapStateOnServer to either be undefined or a function.');\n }\n\n function getDisplayName(WrappedComponent) {\n return WrappedComponent.displayName || WrappedComponent.name || 'Component';\n }\n\n return function wrap(WrappedComponent) {\n if (typeof WrappedComponent !== 'function') {\n throw new Error('Expected WrappedComponent to be a React component.');\n }\n\n var mountedInstances = [];\n var state;\n\n function emitChange() {\n state = reducePropsToState(mountedInstances.map(function (instance) {\n return instance.props;\n }));\n\n if (SideEffect.canUseDOM) {\n handleStateChangeOnClient(state);\n } else if (mapStateOnServer) {\n state = mapStateOnServer(state);\n }\n }\n\n var SideEffect =\n /*#__PURE__*/\n function (_PureComponent) {\n _inheritsLoose(SideEffect, _PureComponent);\n\n function SideEffect() {\n return _PureComponent.apply(this, arguments) || this;\n }\n\n // Try to use displayName of wrapped component\n // Expose canUseDOM so tests can monkeypatch it\n SideEffect.peek = function peek() {\n return state;\n };\n\n SideEffect.rewind = function rewind() {\n if (SideEffect.canUseDOM) {\n throw new Error('You may only call rewind() on the server. Call peek() to read the current state.');\n }\n\n var recordedState = state;\n state = undefined;\n mountedInstances = [];\n return recordedState;\n };\n\n var _proto = SideEffect.prototype;\n\n _proto.UNSAFE_componentWillMount = function UNSAFE_componentWillMount() {\n mountedInstances.push(this);\n emitChange();\n };\n\n _proto.componentDidUpdate = function componentDidUpdate() {\n emitChange();\n };\n\n _proto.componentWillUnmount = function componentWillUnmount() {\n var index = mountedInstances.indexOf(this);\n mountedInstances.splice(index, 1);\n emitChange();\n };\n\n _proto.render = function render() {\n return React__default.createElement(WrappedComponent, this.props);\n };\n\n return SideEffect;\n }(React.PureComponent);\n\n _defineProperty(SideEffect, \"displayName\", \"SideEffect(\" + getDisplayName(WrappedComponent) + \")\");\n\n _defineProperty(SideEffect, \"canUseDOM\", canUseDOM);\n\n return SideEffect;\n };\n}\n\nmodule.exports = withSideEffect;\n","import { useLayoutEffect } from 'react';\n\nvar index = useLayoutEffect ;\n\nexport default index;\n","import * as React from 'react';\nimport useIsomorphicLayoutEffect from 'use-isomorphic-layout-effect';\n\nvar useLatest = function useLatest(value) {\n var ref = React.useRef(value);\n useIsomorphicLayoutEffect(function () {\n ref.current = value;\n });\n return ref;\n};\n\nexport { useLatest as default };\n","import { useRef, useCallback } from 'react';\n\nvar updateRef = function updateRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n return;\n }\n ref.current = value;\n};\n\nvar useComposedRef = function useComposedRef(libRef, userRef) {\n var prevUserRef = useRef();\n return useCallback(function (instance) {\n libRef.current = instance;\n\n if (prevUserRef.current) {\n updateRef(prevUserRef.current, null);\n }\n\n prevUserRef.current = userRef;\n\n if (!userRef) {\n return;\n }\n\n updateRef(userRef, instance);\n }, [userRef]);\n};\n\nexport default useComposedRef;\n","import _extends from '@babel/runtime/helpers/esm/extends';\nimport _objectWithoutPropertiesLoose from '@babel/runtime/helpers/esm/objectWithoutPropertiesLoose';\nimport * as React from 'react';\nimport useLatest from 'use-latest';\nimport useComposedRef from 'use-composed-ref';\n\nvar HIDDEN_TEXTAREA_STYLE = {\n 'min-height': '0',\n 'max-height': 'none',\n height: '0',\n visibility: 'hidden',\n overflow: 'hidden',\n position: 'absolute',\n 'z-index': '-1000',\n top: '0',\n right: '0',\n display: 'block'\n};\nvar forceHiddenStyles = function forceHiddenStyles(node) {\n Object.keys(HIDDEN_TEXTAREA_STYLE).forEach(function (key) {\n node.style.setProperty(key, HIDDEN_TEXTAREA_STYLE[key], 'important');\n });\n};\nvar forceHiddenStyles$1 = forceHiddenStyles;\n\nvar hiddenTextarea = null;\nvar getHeight = function getHeight(node, sizingData) {\n var height = node.scrollHeight;\n if (sizingData.sizingStyle.boxSizing === 'border-box') {\n // border-box: add border, since height = content + padding + border\n return height + sizingData.borderSize;\n }\n\n // remove padding, since height = content\n return height - sizingData.paddingSize;\n};\nfunction calculateNodeHeight(sizingData, value, minRows, maxRows) {\n if (minRows === void 0) {\n minRows = 1;\n }\n if (maxRows === void 0) {\n maxRows = Infinity;\n }\n if (!hiddenTextarea) {\n hiddenTextarea = document.createElement('textarea');\n hiddenTextarea.setAttribute('tabindex', '-1');\n hiddenTextarea.setAttribute('aria-hidden', 'true');\n forceHiddenStyles$1(hiddenTextarea);\n }\n if (hiddenTextarea.parentNode === null) {\n document.body.appendChild(hiddenTextarea);\n }\n var paddingSize = sizingData.paddingSize,\n borderSize = sizingData.borderSize,\n sizingStyle = sizingData.sizingStyle;\n var boxSizing = sizingStyle.boxSizing;\n Object.keys(sizingStyle).forEach(function (_key) {\n var key = _key;\n hiddenTextarea.style[key] = sizingStyle[key];\n });\n forceHiddenStyles$1(hiddenTextarea);\n hiddenTextarea.value = value;\n var height = getHeight(hiddenTextarea, sizingData);\n // Double set and calc due to Firefox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1795904\n hiddenTextarea.value = value;\n height = getHeight(hiddenTextarea, sizingData);\n\n // measure height of a textarea with a single row\n hiddenTextarea.value = 'x';\n var rowHeight = hiddenTextarea.scrollHeight - paddingSize;\n var minHeight = rowHeight * minRows;\n if (boxSizing === 'border-box') {\n minHeight = minHeight + paddingSize + borderSize;\n }\n height = Math.max(minHeight, height);\n var maxHeight = rowHeight * maxRows;\n if (boxSizing === 'border-box') {\n maxHeight = maxHeight + paddingSize + borderSize;\n }\n height = Math.min(maxHeight, height);\n return [height, rowHeight];\n}\n\nvar noop = function noop() {};\nvar pick = function pick(props, obj) {\n return props.reduce(function (acc, prop) {\n acc[prop] = obj[prop];\n return acc;\n }, {});\n};\n\nvar SIZING_STYLE = ['borderBottomWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth', 'boxSizing', 'fontFamily', 'fontSize', 'fontStyle', 'fontWeight', 'letterSpacing', 'lineHeight', 'paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop',\n// non-standard\n'tabSize', 'textIndent',\n// non-standard\n'textRendering', 'textTransform', 'width', 'wordBreak'];\nvar isIE = !!document.documentElement.currentStyle ;\nvar getSizingData = function getSizingData(node) {\n var style = window.getComputedStyle(node);\n if (style === null) {\n return null;\n }\n var sizingStyle = pick(SIZING_STYLE, style);\n var boxSizing = sizingStyle.boxSizing;\n\n // probably node is detached from DOM, can't read computed dimensions\n if (boxSizing === '') {\n return null;\n }\n\n // IE (Edge has already correct behaviour) returns content width as computed width\n // so we need to add manually padding and border widths\n if (isIE && boxSizing === 'border-box') {\n sizingStyle.width = parseFloat(sizingStyle.width) + parseFloat(sizingStyle.borderRightWidth) + parseFloat(sizingStyle.borderLeftWidth) + parseFloat(sizingStyle.paddingRight) + parseFloat(sizingStyle.paddingLeft) + 'px';\n }\n var paddingSize = parseFloat(sizingStyle.paddingBottom) + parseFloat(sizingStyle.paddingTop);\n var borderSize = parseFloat(sizingStyle.borderBottomWidth) + parseFloat(sizingStyle.borderTopWidth);\n return {\n sizingStyle: sizingStyle,\n paddingSize: paddingSize,\n borderSize: borderSize\n };\n};\nvar getSizingData$1 = getSizingData;\n\nfunction useListener(target, type, listener) {\n var latestListener = useLatest(listener);\n React.useLayoutEffect(function () {\n var handler = function handler(ev) {\n return latestListener.current(ev);\n };\n\n // might happen if document.fonts is not defined, for instance\n if (!target) {\n return;\n }\n target.addEventListener(type, handler);\n return function () {\n return target.removeEventListener(type, handler);\n };\n }, []);\n}\nvar useWindowResizeListener = function useWindowResizeListener(listener) {\n useListener(window, 'resize', listener);\n};\nvar useFontsLoadedListener = function useFontsLoadedListener(listener) {\n useListener(document.fonts, 'loadingdone', listener);\n};\n\nvar _excluded = [\"cacheMeasurements\", \"maxRows\", \"minRows\", \"onChange\", \"onHeightChange\"];\nvar TextareaAutosize = function TextareaAutosize(_ref, userRef) {\n var cacheMeasurements = _ref.cacheMeasurements,\n maxRows = _ref.maxRows,\n minRows = _ref.minRows,\n _ref$onChange = _ref.onChange,\n onChange = _ref$onChange === void 0 ? noop : _ref$onChange,\n _ref$onHeightChange = _ref.onHeightChange,\n onHeightChange = _ref$onHeightChange === void 0 ? noop : _ref$onHeightChange,\n props = _objectWithoutPropertiesLoose(_ref, _excluded);\n var isControlled = props.value !== undefined;\n var libRef = React.useRef(null);\n var ref = useComposedRef(libRef, userRef);\n var heightRef = React.useRef(0);\n var measurementsCacheRef = React.useRef();\n var resizeTextarea = function resizeTextarea() {\n var node = libRef.current;\n var nodeSizingData = cacheMeasurements && measurementsCacheRef.current ? measurementsCacheRef.current : getSizingData$1(node);\n if (!nodeSizingData) {\n return;\n }\n measurementsCacheRef.current = nodeSizingData;\n var _calculateNodeHeight = calculateNodeHeight(nodeSizingData, node.value || node.placeholder || 'x', minRows, maxRows),\n height = _calculateNodeHeight[0],\n rowHeight = _calculateNodeHeight[1];\n if (heightRef.current !== height) {\n heightRef.current = height;\n node.style.setProperty('height', height + \"px\", 'important');\n onHeightChange(height, {\n rowHeight: rowHeight\n });\n }\n };\n var handleChange = function handleChange(event) {\n if (!isControlled) {\n resizeTextarea();\n }\n onChange(event);\n };\n {\n React.useLayoutEffect(resizeTextarea);\n useWindowResizeListener(resizeTextarea);\n useFontsLoadedListener(resizeTextarea);\n return /*#__PURE__*/React.createElement(\"textarea\", _extends({}, props, {\n onChange: handleChange,\n ref: ref\n }));\n }\n};\nvar index = /* #__PURE__ */React.forwardRef(TextareaAutosize);\n\nexport { index as default };\n","/**\r\n * Copyright (c) Facebook, Inc. and its affiliates.\r\n *\r\n * This source code is licensed under the MIT license found in the\r\n * LICENSE file in the root directory of this source tree.\r\n *\r\n * @flow strict-local\r\n * @format\r\n */\n'use strict';\n\nimport React from 'react';\nimport { __internal } from 'relay-runtime';\nvar createRelayContext = __internal.createRelayContext;\nexport var ReactRelayContext = createRelayContext(React);","export var NETWORK_ONLY = 'network-only';\nexport var STORE_THEN_NETWORK = 'store-and-network';\nexport var STORE_OR_NETWORK = 'store-or-network';\nexport var STORE_ONLY = 'store-only';\nexport var PAGINATION_NAME = 'usePagination';\nexport var REFETCHABLE_NAME = 'useRefetchable';\nexport var FRAGMENT_NAME = 'useFragment'; // pagination\n\nexport var FORWARD = 'forward';","import { createOperationDescriptor, getRequest } from 'relay-runtime';\nimport { STORE_OR_NETWORK, STORE_THEN_NETWORK, NETWORK_ONLY } from './RelayHooksTypes';\nexport var isNetworkPolicy = function (policy, full) {\n return policy === NETWORK_ONLY || policy === STORE_THEN_NETWORK || policy === STORE_OR_NETWORK && !full;\n};\nexport var isStorePolicy = function (policy) {\n return policy !== NETWORK_ONLY;\n};\nexport var forceCache = {\n force: true\n}; // Fetcher\n\nexport function createOperation(gqlQuery, variables, cacheConfig) {\n return createOperationDescriptor(getRequest(gqlQuery), variables, cacheConfig);\n}","import { __internal } from 'relay-runtime';\nimport { isNetworkPolicy, isStorePolicy } from './Utils';\nvar fetchQuery = __internal.fetchQuery;\nvar DATA_RETENTION_TIMEOUT = 30 * 1000;\nexport function fetchResolver(_a) {\n var _b = _a.doRetain,\n doRetain = _b === void 0 ? true : _b,\n disposeTemporary = _a.disposeTemporary;\n var _refetchSubscription = null;\n var disposable = null;\n var releaseQueryTimeout;\n var isLoading = false;\n var query;\n var promise;\n var error = null;\n var env;\n\n var update = function (loading, e) {\n if (e === void 0) {\n e = null;\n }\n\n isLoading = loading;\n error = e;\n };\n\n var lookupInStore = function (environment, operation, fetchPolicy, renderPolicy) {\n if (isStorePolicy(fetchPolicy)) {\n var check = environment.check(operation);\n var queryStatus = check.status;\n var hasFullQuery = queryStatus === 'available';\n var canPartialRender = hasFullQuery || renderPolicy === 'partial' && queryStatus !== 'stale';\n\n if (canPartialRender) {\n return {\n snapshot: environment.lookup(operation.fragment),\n full: hasFullQuery\n };\n }\n }\n\n return {\n snapshot: null,\n full: false\n };\n };\n\n var dispose = function () {\n clearTemporaryRetain();\n disposable && disposable.dispose();\n disposeRequest();\n disposable = null;\n env = null;\n query = null;\n };\n\n var clearTemporaryRetain = function () {\n clearTimeout(releaseQueryTimeout);\n releaseQueryTimeout = null;\n };\n\n var temporaryRetain = function () {\n var localReleaseTemporaryRetain = function () {\n clearTemporaryRetain();\n dispose();\n disposeTemporary && disposeTemporary();\n };\n\n releaseQueryTimeout = setTimeout(localReleaseTemporaryRetain, DATA_RETENTION_TIMEOUT);\n };\n\n var disposeRequest = function () {\n _refetchSubscription && _refetchSubscription.unsubscribe();\n error = null;\n isLoading = false;\n };\n\n var fetch = function (environment, operation, fetchPolicy, onComplete, onNext, onResponse, renderPolicy) {\n if (fetchPolicy === void 0) {\n fetchPolicy = 'network-only';\n }\n\n if (onComplete === void 0) {\n onComplete = function (_e, _u) {\n return undefined;\n };\n }\n\n var fetchHasReturned = false;\n\n if (env != environment || query.request.identifier !== operation.request.identifier) {\n dispose();\n\n if (doRetain) {\n disposable = environment.retain(operation);\n }\n }\n\n env = environment;\n query = operation;\n disposeRequest();\n\n var _a = lookupInStore(environment, operation, fetchPolicy, renderPolicy),\n snapshot = _a.snapshot,\n full = _a.full;\n\n var isNetwork = isNetworkPolicy(fetchPolicy, full);\n\n if (snapshot != null) {\n var onlyStore = !isNetwork;\n onNext(operation, snapshot, fetchHasReturned && !onlyStore);\n\n if (onlyStore) {\n onComplete(null, fetchHasReturned);\n }\n } // Cancel any previously running refetch.\n\n\n _refetchSubscription && _refetchSubscription.unsubscribe();\n var refetchSubscription;\n\n if (isNetwork) {\n var resolveNetworkPromise_1 = function () {}; // Declare refetchSubscription before assigning it in .start(), since\n // synchronous completion may call callbacks .subscribe() returns.\n\n\n var cleanup_1 = function () {\n if (_refetchSubscription === refetchSubscription) {\n _refetchSubscription = null;\n }\n\n isLoading = false;\n promise = null;\n };\n\n var complete_1 = function (error) {\n if (error === void 0) {\n error = null;\n }\n\n resolveNetworkPromise_1();\n update(false, error);\n cleanup_1();\n onComplete(error, fetchHasReturned);\n };\n\n fetchQuery(environment, operation).subscribe({\n unsubscribe: function () {\n cleanup_1();\n },\n complete: complete_1,\n error: function (e) {\n return complete_1(e);\n },\n next: function (response) {\n var store = environment.lookup(operation.fragment);\n promise = null;\n var responses = Array.isArray(response) ? response : [response];\n var cacheConfig = operation.request.cacheConfig;\n var isQueryPolling = !!cacheConfig && !!cacheConfig.poll;\n var isIncremental = responses.some(function (x) {\n return x != null && x.hasNext === true;\n });\n isQueryPolling && update(false);\n resolveNetworkPromise_1();\n onResponse && onResponse(response);\n onNext(operation, store, fetchHasReturned && (isIncremental || isQueryPolling));\n },\n start: function (subscription) {\n refetchSubscription = subscription;\n _refetchSubscription = refetchSubscription;\n update(true);\n }\n });\n\n if (!snapshot) {\n promise = new Promise(function (resolve) {\n resolveNetworkPromise_1 = resolve;\n });\n }\n }\n\n fetchHasReturned = true;\n return {\n dispose: function () {\n refetchSubscription && refetchSubscription.unsubscribe();\n }\n };\n };\n\n var checkAndSuspense = function (suspense, useLazy) {\n clearTemporaryRetain();\n var toThrow = promise || error;\n\n if (suspense && toThrow) {\n if (promise && useLazy) {\n temporaryRetain();\n }\n\n throw toThrow;\n }\n\n return toThrow;\n };\n\n var getData = function () {\n return {\n isLoading: isLoading,\n error: error\n };\n };\n\n return {\n fetch: fetch,\n getData: getData,\n dispose: dispose,\n checkAndSuspense: checkAndSuspense\n };\n}","import areEqual from 'fbjs/lib/areEqual';\nimport { handlePotentialSnapshotErrors } from 'relay-runtime';\nimport { fetchResolver } from './FetchResolver';\nimport { createOperation } from './Utils';\nvar defaultPolicy = 'store-or-network';\nvar cache = new Map();\nexport function getOrCreateQueryFetcher(useLazy, gqlQuery, variables, networkCacheConfig) {\n var query = createOperation(gqlQuery, variables, networkCacheConfig);\n var toGet = useLazy && cache.has(query.request.identifier);\n var queryFetcher = toGet ? cache.get(query.request.identifier) : new QueryFetcher();\n queryFetcher.setQuery(gqlQuery, variables, networkCacheConfig, query);\n return queryFetcher;\n}\n\nvar emptyforceUpdate = function () {\n return undefined;\n};\n\nvar QueryFetcher =\n/** @class */\nfunction () {\n function QueryFetcher() {\n var _this = this;\n\n this.forceUpdate = emptyforceUpdate;\n this.result = null;\n\n this.retry = function (cacheConfigOverride, options) {\n if (options === void 0) {\n options = {};\n }\n\n var _a = options.fetchPolicy,\n fetchPolicy = _a === void 0 ? 'network-only' : _a;\n /* eslint-disable indent */\n\n var query = cacheConfigOverride ? createOperation(_this.query.request.node, _this.query.request.variables, cacheConfigOverride) : _this.query;\n\n _this.fetch(query, fetchPolicy, options);\n\n _this.resolveResult();\n\n _this.forceUpdate();\n };\n\n this.result = {\n retry: this.retry,\n error: null,\n data: null,\n isLoading: false\n };\n this.fetcher = fetchResolver({\n disposeTemporary: function () {\n _this.dispose();\n\n _this.query && cache.delete(_this.query.request.identifier);\n }\n });\n }\n\n QueryFetcher.prototype.setQuery = function (gqlQuery, variables, networkCacheConfig, query) {\n this.gqlQuery = gqlQuery;\n this.variables = variables;\n this.query = query;\n this.cacheConfig = networkCacheConfig;\n };\n\n QueryFetcher.prototype.getForceUpdate = function () {\n return this.forceUpdate;\n };\n\n QueryFetcher.prototype.setForceUpdate = function (forceUpdate) {\n this.forceUpdate = forceUpdate;\n };\n\n QueryFetcher.prototype.dispose = function () {\n this.fetcher.dispose();\n this.disposeSnapshot();\n };\n\n QueryFetcher.prototype.disposeSnapshot = function () {\n this.snapshot = null;\n\n if (this.rootSubscription) {\n this.rootSubscription.dispose();\n this.rootSubscription = null;\n }\n };\n\n QueryFetcher.prototype.fetch = function (query, fetchPolicy, options, skip) {\n var _this = this;\n\n this.disposeSnapshot();\n\n if (skip) {\n this.fetcher.dispose();\n return;\n }\n\n var onComplete = options.onComplete,\n onResponse = options.onResponse;\n\n var resolveUpdate = function (doUpdate) {\n _this.resolveResult();\n\n if (doUpdate) {\n _this.forceUpdate();\n }\n };\n\n var onNext = function (operation, snapshot, doUpdate) {\n if (!_this.snapshot) {\n _this.snapshot = snapshot;\n\n _this.subscribe(snapshot);\n\n resolveUpdate(doUpdate);\n }\n };\n\n var complete = function (error, doUpdate) {\n // doUpdate is False only if fetch is Sync\n resolveUpdate(doUpdate);\n onComplete && onComplete(error);\n };\n\n this.fetcher.fetch(this.environment, query, fetchPolicy, complete, onNext, onResponse, options.UNSTABLE_renderPolicy);\n };\n\n QueryFetcher.prototype.getQuery = function (gqlQuery, variables, networkCacheConfig) {\n if (gqlQuery != this.gqlQuery || networkCacheConfig != this.cacheConfig || variables != this.variables || !areEqual(variables, this.variables)) {\n this.variables = variables;\n this.gqlQuery = gqlQuery;\n this.cacheConfig = networkCacheConfig;\n return createOperation(gqlQuery, variables, networkCacheConfig);\n }\n\n return this.query;\n };\n\n QueryFetcher.prototype.resolveEnvironment = function (environment) {\n this.resolve(environment, this.gqlQuery, this.variables, this.options);\n };\n\n QueryFetcher.prototype.resolve = function (environment, gqlQuery, variables, options) {\n var query = this.getQuery(gqlQuery, variables, options.networkCacheConfig);\n var _a = options.fetchPolicy,\n fetchPolicy = _a === void 0 ? defaultPolicy : _a,\n fetchKey = options.fetchKey,\n skip = options.skip;\n this.options = options;\n var diffQuery = !this.query || query.request.identifier !== this.query.request.identifier;\n\n if (diffQuery || environment !== this.environment || fetchPolicy !== this.fetchPolicy || fetchKey !== this.fetchKey || skip !== this.skip) {\n this.environment = environment;\n this.query = query;\n this.skip = skip;\n this.fetchPolicy = fetchPolicy;\n this.fetchKey = fetchKey;\n this.fetch(query, fetchPolicy, options, skip);\n this.resolveResult();\n }\n };\n\n QueryFetcher.prototype.checkAndSuspense = function (suspense, useLazy) {\n if (useLazy) {\n this.setForceUpdate(emptyforceUpdate);\n cache.set(this.query.request.identifier, this);\n }\n\n var result = this.fetcher.checkAndSuspense(suspense, useLazy);\n\n if (useLazy) {\n cache.delete(this.query.request.identifier);\n }\n\n return result;\n };\n\n QueryFetcher.prototype.getData = function () {\n return this.result;\n };\n\n QueryFetcher.prototype.resolveResult = function () {\n var _a = this.fetcher.getData(),\n error = _a.error,\n isLoading = _a.isLoading;\n\n var snapshot = this.snapshot;\n\n if (snapshot && snapshot.missingRequiredFields) {\n handlePotentialSnapshotErrors(this.environment, snapshot.missingRequiredFields, snapshot.relayResolverErrors);\n }\n\n this.result = {\n retry: this.retry,\n error: error,\n data: snapshot ? snapshot.data : null,\n isLoading: isLoading\n };\n };\n\n QueryFetcher.prototype.subscribe = function (snapshot) {\n var _this = this;\n\n if (this.rootSubscription) {\n this.rootSubscription.dispose();\n }\n\n this.rootSubscription = this.environment.subscribe(snapshot, function (snapshot) {\n // Read from this._fetchOptions in case onDataChange() was lazily added.\n _this.snapshot = snapshot; //this.error = null;\n\n _this.resolveResult();\n\n _this.forceUpdate();\n });\n };\n\n return QueryFetcher;\n}();\n\nexport { QueryFetcher };","import { useCallback, useEffect, useRef, useState } from 'react';\nexport function useForceUpdate() {\n var _a = useState([]),\n forceUpdate = _a[1];\n\n var mountState = useRef({\n mounted: false,\n pending: false\n });\n useEffect(function () {\n mountState.current.mounted = true;\n\n if (mountState.current.pending) {\n mountState.current.pending = false;\n forceUpdate([]);\n }\n\n return function () {\n mountState.current = {\n mounted: false,\n pending: false\n };\n };\n }, []);\n var update = useCallback(function () {\n if (mountState.current.mounted) {\n forceUpdate([]);\n } else {\n mountState.current.pending = true;\n }\n }, [forceUpdate]);\n return update;\n}","import React from 'react';\nimport { ReactRelayContext } from './ReactRelayContext';\nexport function useRelayEnvironment() {\n var environment = React.useContext(ReactRelayContext).environment;\n return environment;\n}","import { useRef, useEffect } from 'react';\nimport { getOrCreateQueryFetcher } from './QueryFetcher';\nimport { useForceUpdate } from './useForceUpdate';\nimport { useRelayEnvironment } from './useRelayEnvironment';\nimport { forceCache } from './Utils';\n\nvar useInternalQuery = function (gqlQuery, variables, options, suspense) {\n var environment = useRelayEnvironment();\n var forceUpdate = useForceUpdate();\n var ref = useRef();\n var maybeHiddenOrFastRefresh = useRef(false);\n\n if (ref.current === null || ref.current === undefined || maybeHiddenOrFastRefresh.current == true) {\n ref.current = {\n queryFetcher: getOrCreateQueryFetcher(suspense, gqlQuery, variables, options.networkCacheConfig)\n };\n maybeHiddenOrFastRefresh.current = false;\n }\n\n useEffect(function () {\n if (maybeHiddenOrFastRefresh.current == true) {\n forceUpdate();\n }\n\n return function () {\n ref.current.queryFetcher.dispose();\n maybeHiddenOrFastRefresh.current = true;\n }; // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n var queryFetcher = ref.current.queryFetcher;\n queryFetcher.resolve(environment, gqlQuery, variables, options);\n queryFetcher.checkAndSuspense(suspense, suspense);\n queryFetcher.setForceUpdate(forceUpdate);\n return queryFetcher.getData();\n};\n\nexport var useQuery = function (gqlQuery, variables, options) {\n if (variables === void 0) {\n variables = {};\n }\n\n if (options === void 0) {\n options = {};\n }\n\n return useInternalQuery(gqlQuery, variables, options, false);\n};\nexport var useLazyLoadQuery = function (gqlQuery, variables, options) {\n var _a;\n\n if (variables === void 0) {\n variables = {};\n }\n\n if (options === void 0) {\n options = {};\n }\n\n options.networkCacheConfig = (_a = options.networkCacheConfig) !== null && _a !== void 0 ? _a : forceCache;\n return useInternalQuery(gqlQuery, variables, options, true);\n};","import invariant from 'fbjs/lib/invariant';\nimport { ConnectionInterface, getValueAtPath } from 'relay-runtime';\nexport function getStateFromConnection(direction, fragmentNode, connection) {\n var _a, _b;\n\n if (connection == null) {\n return {\n cursor: null,\n hasMore: false\n };\n }\n\n var _c = ConnectionInterface.get(),\n EDGES = _c.EDGES,\n PAGE_INFO = _c.PAGE_INFO,\n HAS_NEXT_PAGE = _c.HAS_NEXT_PAGE,\n HAS_PREV_PAGE = _c.HAS_PREV_PAGE,\n END_CURSOR = _c.END_CURSOR,\n START_CURSOR = _c.START_CURSOR;\n\n !(typeof connection === 'object') ? process.env.NODE_ENV !== \"production\" ? !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: Expected connection in fragment `%s` to have been `null`, or ' + 'a plain object with %s and %s properties. Instead got `%s`.', fragmentNode.name, EDGES, PAGE_INFO, connection) : invariant(false) : void 0 : !false ? process.env.NODE_ENV !== \"production\" ? invariant(false) : invariant(false) : void 0 : void 0;\n var edges = connection[EDGES];\n var pageInfo = connection[PAGE_INFO];\n\n if (edges == null || pageInfo == null) {\n return {\n cursor: null,\n hasMore: false\n };\n }\n\n !Array.isArray(edges) ? process.env.NODE_ENV !== \"production\" ? !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: Expected connection in fragment `%s` to have a plural `%s` field. ' + 'Instead got `%s`.', fragmentNode.name, EDGES, edges) : invariant(false) : void 0 : !false ? process.env.NODE_ENV !== \"production\" ? invariant(false) : invariant(false) : void 0 : void 0;\n !(typeof pageInfo === 'object') ? process.env.NODE_ENV !== \"production\" ? !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: Expected connection in fragment `%s` to have a `%s` field. ' + 'Instead got `%s`.', fragmentNode.name, PAGE_INFO, pageInfo) : invariant(false) : void 0 : !false ? process.env.NODE_ENV !== \"production\" ? invariant(false) : invariant(false) : void 0 : void 0;\n var cursor = direction === 'forward' ? (_a = pageInfo[END_CURSOR]) !== null && _a !== void 0 ? _a : null : (_b = pageInfo[START_CURSOR]) !== null && _b !== void 0 ? _b : null;\n !(cursor === null || typeof cursor === 'string') ? process.env.NODE_ENV !== \"production\" ? !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: Expected page info for connection in fragment `%s` to have a ' + 'valid `%s`. Instead got `%s`.', fragmentNode.name, START_CURSOR, cursor) : invariant(false) : void 0 : !false ? process.env.NODE_ENV !== \"production\" ? invariant(false) : invariant(false) : void 0 : void 0;\n var hasMore;\n\n if (direction === 'forward') {\n hasMore = cursor != null && pageInfo[HAS_NEXT_PAGE] === true;\n } else {\n hasMore = cursor != null && pageInfo[HAS_PREV_PAGE] === true;\n }\n\n return {\n cursor: cursor,\n hasMore: hasMore\n };\n}\nexport function getConnectionState(direction, fragmentNode, fragmentData, connectionPathInFragmentData) {\n var connection = getValueAtPath(fragmentData, connectionPathInFragmentData);\n return getStateFromConnection(direction, fragmentNode, connection);\n}","var __assign = this && this.__assign || function () {\n __assign = Object.assign || function (t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n\n return t;\n };\n\n return __assign.apply(this, arguments);\n};\n\nimport areEqual from 'fbjs/lib/areEqual';\nimport invariant from 'fbjs/lib/invariant';\nimport warning from 'fbjs/lib/warning';\nimport { __internal, getSelector, getVariablesFromFragment, getFragmentIdentifier, getDataIDsFromFragment, getPaginationMetadata, getPaginationVariables, getRefetchMetadata, getValueAtPath, handlePotentialSnapshotErrors } from 'relay-runtime';\nimport { fetchResolver } from './FetchResolver';\nimport { getConnectionState, getStateFromConnection } from './getConnectionState';\nimport { PAGINATION_NAME, REFETCHABLE_NAME } from './RelayHooksTypes';\nimport { createOperation, forceCache } from './Utils';\nvar getPromiseForActiveRequest = __internal.getPromiseForActiveRequest; // eslint-disable-next-line @typescript-eslint/no-empty-function\n\nfunction emptyVoid() {}\n\nfunction lookupFragment(environment, selector) {\n return selector.kind === 'PluralReaderSelector' ? selector.selectors.map(function (s) {\n return environment.lookup(s);\n }) : environment.lookup(selector);\n}\n\nfunction getFragmentResult(snapshot) {\n var missData = isMissingData(snapshot);\n\n if (Array.isArray(snapshot)) {\n return {\n snapshot: snapshot,\n data: snapshot.map(function (s) {\n return s.data;\n }),\n isMissingData: missData\n };\n }\n\n return {\n snapshot: snapshot,\n data: snapshot.data,\n isMissingData: missData\n };\n}\n\nfunction isMissingData(snapshot) {\n if (Array.isArray(snapshot)) {\n return snapshot.some(function (s) {\n return s.isMissingData;\n });\n }\n\n return snapshot.isMissingData;\n}\n\nfunction _getAndSavePromiseForFragmentRequestInFlight(fragmentNode, fragmentOwner, env) {\n var _a, _b;\n\n var networkPromise = getPromiseForActiveRequest(env, fragmentOwner);\n var pendingOperationName;\n\n if (networkPromise != null) {\n pendingOperationName = fragmentOwner.node.params.name;\n } else {\n var result = env.getOperationTracker().getPendingOperationsAffectingOwner(fragmentOwner);\n var pendingOperations = result === null || result === void 0 ? void 0 : result.pendingOperations;\n networkPromise = (_a = result === null || result === void 0 ? void 0 : result.promise) !== null && _a !== void 0 ? _a : null;\n pendingOperationName = (_b = pendingOperations === null || pendingOperations === void 0 ? void 0 : pendingOperations.map(function (op) {\n return op.node.params.name;\n }).join(',')) !== null && _b !== void 0 ? _b : null;\n }\n\n if (!networkPromise) {\n return null;\n }\n\n if (pendingOperationName == null || pendingOperationName.length === 0) {\n pendingOperationName = 'Unknown pending operation';\n } // When the Promise for the request resolves, we need to make sure to\n // update the cache with the latest data available in the store before\n // resolving the Promise\n\n\n var fragmentName = fragmentNode.name;\n var promiseDisplayName = pendingOperationName === fragmentName ? \"Relay(\".concat(pendingOperationName, \")\") : \"Relay(\".concat(pendingOperationName, \":\").concat(fragmentName, \")\");\n networkPromise.displayName = promiseDisplayName;\n return networkPromise;\n}\n\nvar FragmentResolver =\n/** @class */\nfunction () {\n function FragmentResolver(name) {\n var _this = this;\n\n this.unmounted = false;\n this.refetchable = false;\n this.pagination = false;\n\n this.refetch = function (variables, options) {\n var _a, _b, _c, _d;\n\n if (options === void 0) {\n options = {};\n }\n\n var name = _this.name;\n\n if (_this.unmounted === true) {\n process.env.NODE_ENV !== \"production\" ? process.env.NODE_ENV !== \"production\" ? warning(false, 'Relay: Unexpected call to `refetch` on unmounted component for fragment ' + '`%s` in `%s`. It looks like some instances of your component are ' + 'still trying to fetch data but they already unmounted. ' + 'Please make sure you clear all timers, intervals, ' + 'async calls, etc that may trigger a fetch.', _this._fragment.name, name) : void 0 : void 0;\n return {\n dispose: emptyVoid\n };\n }\n\n if (_this._selector == null) {\n process.env.NODE_ENV !== \"production\" ? process.env.NODE_ENV !== \"production\" ? warning(false, 'Relay: Unexpected call to `refetch` while using a null fragment ref ' + 'for fragment `%s` in `%s`. When calling `refetch`, we expect ' + \"initial fragment data to be non-null. Please make sure you're \" + 'passing a valid fragment ref to `%s` before calling ' + '`refetch`, or make sure you pass all required variables to `refetch`.', _this._fragment.name, name, name) : void 0 : void 0;\n }\n\n var _e = getRefetchMetadata(_this._fragment, name),\n fragmentRefPathInResponse = _e.fragmentRefPathInResponse,\n identifierInfo = _e.identifierInfo,\n refetchableRequest = _e.refetchableRequest;\n\n var fragmentData = _this.getData().data;\n\n var identifierValue = (identifierInfo === null || identifierInfo === void 0 ? void 0 : identifierInfo.identifierField) != null && fragmentData != null && typeof fragmentData === 'object' ? fragmentData[identifierInfo.identifierField] : null;\n var parentVariables;\n var fragmentVariables;\n\n if (_this._selector == null) {\n parentVariables = {};\n fragmentVariables = {};\n } else if (_this._selector.kind === 'PluralReaderSelector') {\n parentVariables = (_b = (_a = _this._selector.selectors[0]) === null || _a === void 0 ? void 0 : _a.owner.variables) !== null && _b !== void 0 ? _b : {};\n fragmentVariables = (_d = (_c = _this._selector.selectors[0]) === null || _c === void 0 ? void 0 : _c.variables) !== null && _d !== void 0 ? _d : {};\n } else {\n parentVariables = _this._selector.owner.variables;\n fragmentVariables = _this._selector.variables;\n } // NOTE: A user of `useRefetchableFragment()` may pass a subset of\n // all variables required by the fragment when calling `refetch()`.\n // We fill in any variables not passed by the call to `refetch()` with the\n // variables from the original parent fragment owner.\n\n /* $FlowFixMe[cannot-spread-indexer] (>=0.123.0) This comment suppresses\r\n * an error found when Flow v0.123.0 was deployed. To see the error\r\n * delete this comment and run Flow. */\n\n\n var refetchVariables = __assign(__assign(__assign({}, parentVariables), fragmentVariables), variables);\n\n if (identifierInfo != null && !variables.hasOwnProperty(identifierInfo.identifierQueryVariableName)) {\n // @refetchable fragments are guaranteed to have an `id` selection\n // if the type is Node, implements Node, or is @fetchable. Double-check\n // that there actually is a value at runtime.\n if (typeof identifierValue !== 'string') {\n process.env.NODE_ENV !== \"production\" ? process.env.NODE_ENV !== \"production\" ? warning(false, 'Relay: Expected result to have a string ' + '`%s` in order to refetch, got `%s`.', identifierInfo, identifierValue) : void 0 : void 0;\n }\n\n refetchVariables[identifierInfo.identifierQueryVariableName] = identifierValue;\n }\n\n var onNext = function (operation, snapshot, doUpdate) {\n var fragmentRef = getValueAtPath(snapshot.data, fragmentRefPathInResponse);\n\n var isEquals = _this.isEqualsFragmentRef(_this._fragmentRefRefetch || _this._fragmentRef, fragmentRef);\n\n var missData = isMissingData(snapshot); //fromStore && isMissingData(snapshot);\n\n if (!isEquals || missData) {\n _this._fragmentRefRefetch = fragmentRef;\n _this._idfragmentrefetch = getFragmentIdentifier(_this._fragment, fragmentRef);\n\n _this.lookup(_this._fragment, fragmentRef);\n\n _this.subscribe();\n /*if (!missData) {\r\n this.subscribe();\r\n }*/\n\n\n _this.resolverData.isMissingData = missData;\n _this.resolverData.owner = operation.request;\n doUpdate && _this.refreshHooks();\n }\n };\n\n if (_this.pagination) {\n _this.fetcherNext.dispose();\n\n _this.fetcherPrevious.dispose();\n }\n\n var complete = function (error, doUpdate) {\n doUpdate && _this.refreshHooks();\n options.onComplete && options.onComplete(error);\n };\n\n var operation = createOperation(refetchableRequest, refetchVariables, forceCache);\n\n var disposable = _this.fetcherRefecth.fetch(_this._environment, operation, options.fetchPolicy, complete, onNext, options.onResponse, options.UNSTABLE_renderPolicy);\n\n _this.refreshHooks();\n\n return disposable;\n };\n\n this.loadPrevious = function (count, options) {\n return _this.loadMore('backward', count, options);\n };\n\n this.loadNext = function (count, options) {\n return _this.loadMore('forward', count, options);\n };\n\n this.loadMore = function (direction, count, options) {\n var _a;\n\n if (options === void 0) {\n options = {};\n }\n\n var onComplete = (_a = options.onComplete) !== null && _a !== void 0 ? _a : emptyVoid;\n\n var fragmentData = _this.getData().data;\n\n var emptyDispose = {\n dispose: emptyVoid\n };\n var fetcher = direction === 'backward' ? _this.fetcherPrevious : _this.fetcherNext;\n\n if (_this.unmounted === true) {\n // Bail out and warn if we're trying to paginate after the component\n // has unmounted\n process.env.NODE_ENV !== \"production\" ? process.env.NODE_ENV !== \"production\" ? warning(false, 'Relay: Unexpected fetch on unmounted component for fragment ' + '`%s` in `%s`. It looks like some instances of your component are ' + 'still trying to fetch data but they already unmounted. ' + 'Please make sure you clear all timers, intervals, ' + 'async calls, etc that may trigger a fetch.', _this._fragment.name, _this.name) : void 0 : void 0;\n return emptyDispose;\n }\n\n if (_this._selector == null) {\n process.env.NODE_ENV !== \"production\" ? process.env.NODE_ENV !== \"production\" ? warning(false, 'Relay: Unexpected fetch while using a null fragment ref ' + 'for fragment `%s` in `%s`. When fetching more items, we expect ' + \"initial fragment data to be non-null. Please make sure you're \" + 'passing a valid fragment ref to `%s` before paginating.', _this._fragment.name, _this.name, _this.name) : void 0 : void 0;\n onComplete(null);\n return emptyDispose;\n }\n\n var isRequestActive = _this._environment.isRequestActive(_this._selector.owner.identifier);\n\n if (isRequestActive || fetcher.getData().isLoading === true || fragmentData == null) {\n onComplete(null);\n return emptyDispose;\n }\n\n !(_this._selector != null && _this._selector.kind !== 'PluralReaderSelector') ? process.env.NODE_ENV !== \"production\" ? !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: Expected to be able to find a non-plural fragment owner for ' + \"fragment `%s` when using `%s`. If you're seeing this, \" + 'this is likely a bug in Relay.', _this._fragment.name, _this.name) : invariant(false) : void 0 : !false ? process.env.NODE_ENV !== \"production\" ? invariant(false) : invariant(false) : void 0 : void 0;\n\n var _b = getPaginationMetadata(_this._fragment, _this.name),\n paginationRequest = _b.paginationRequest,\n paginationMetadata = _b.paginationMetadata,\n connectionPathInFragmentData = _b.connectionPathInFragmentData;\n\n var identifierInfo = getRefetchMetadata(_this._fragment, _this._fragment.name).identifierInfo;\n var identifierValue = identifierInfo != null && fragmentData != null && typeof fragmentData === 'object' ? fragmentData[identifierInfo.identifierField] : null;\n var parentVariables = _this._selector.owner.variables;\n var fragmentVariables = _this._selector.variables;\n var extraVariables = options.UNSTABLE_extraVariables;\n\n var baseVariables = __assign(__assign({}, parentVariables), fragmentVariables);\n\n var cursor = getConnectionState(direction, _this._fragment, fragmentData, connectionPathInFragmentData).cursor;\n var paginationVariables = getPaginationVariables(direction, count, cursor, baseVariables, __assign({}, extraVariables), paginationMetadata); // If the query needs an identifier value ('id' or similar) and one\n // was not explicitly provided, read it from the fragment data.\n\n if (identifierInfo != null) {\n // @refetchable fragments are guaranteed to have an `id` selection\n // if the type is Node, implements Node, or is @fetchable. Double-check\n // that there actually is a value at runtime.\n if (typeof identifierValue !== 'string') {\n process.env.NODE_ENV !== \"production\" ? process.env.NODE_ENV !== \"production\" ? warning(false, 'Relay: Expected result to have a string ' + '`%s` in order to refetch, got `%s`.', identifierInfo, identifierValue) : void 0 : void 0;\n }\n\n paginationVariables[identifierInfo.identifierQueryVariableName] = identifierValue;\n }\n\n var complete = function (error, doUpdate) {\n if (doUpdate) _this.refreshHooks();\n onComplete(error);\n };\n\n var operation = createOperation(paginationRequest, paginationVariables, forceCache);\n var disposable = fetcher.fetch(_this._environment, operation, undefined, //options?.fetchPolicy,\n complete, emptyVoid, options.onResponse);\n\n _this.refreshHooks();\n\n return disposable;\n };\n\n this.name = name;\n this.pagination = name === PAGINATION_NAME;\n this.refetchable = name === REFETCHABLE_NAME || this.pagination;\n\n if (this.refetchable) {\n this.fetcherRefecth = fetchResolver({\n doRetain: true\n });\n }\n\n if (this.pagination) {\n this.fetcherNext = fetchResolver({});\n this.fetcherPrevious = fetchResolver({});\n }\n\n this.setForceUpdate();\n\n this.refreshHooks = function () {\n _this.resolveResult();\n\n _this.forceUpdate();\n };\n }\n\n FragmentResolver.prototype.setForceUpdate = function (forceUpdate) {\n if (forceUpdate === void 0) {\n forceUpdate = emptyVoid;\n }\n\n this.forceUpdate = forceUpdate;\n };\n\n FragmentResolver.prototype.subscribeResolve = function (subscribeResolve) {\n if (this._subscribeResolve && this._subscribeResolve != subscribeResolve) {\n subscribeResolve(this.getData());\n }\n\n this._subscribeResolve = subscribeResolve;\n };\n\n FragmentResolver.prototype.setUnmounted = function () {\n this.unmounted = true;\n };\n\n FragmentResolver.prototype.isEqualsFragmentRef = function (prevFragment, fragmentRef) {\n if (this._fragmentRef !== fragmentRef) {\n var prevIDs = getDataIDsFromFragment(this._fragment, prevFragment);\n var nextIDs = getDataIDsFromFragment(this._fragment, fragmentRef);\n\n if (!areEqual(prevIDs, nextIDs) || !areEqual(this.getFragmentVariables(fragmentRef), this.getFragmentVariables(prevFragment))) {\n return false;\n }\n }\n\n return true;\n };\n\n FragmentResolver.prototype.dispose = function () {\n this.unsubscribe();\n this.fetcherNext && this.fetcherNext.dispose();\n this.fetcherPrevious && this.fetcherPrevious.dispose();\n this._idfragmentrefetch = null;\n this._fragmentRefRefetch = null;\n this.fetcherRefecth && this.fetcherRefecth.dispose();\n };\n\n FragmentResolver.prototype.getFragmentVariables = function (fRef) {\n if (fRef === void 0) {\n fRef = this._fragmentRef;\n }\n\n return getVariablesFromFragment(this._fragment, fRef);\n };\n\n FragmentResolver.prototype.resolve = function (environment, idfragment, fragment, fragmentRef) {\n if (!this.resolverData || this._environment !== environment || idfragment !== this._idfragment && (!this._idfragmentrefetch || this._idfragmentrefetch && idfragment !== this._idfragmentrefetch)) {\n this._fragment = fragment;\n this._fragmentRef = fragmentRef;\n this._idfragment = idfragment;\n this._selector = null;\n this.dispose();\n this._environment = environment;\n this.lookup(fragment, this._fragmentRef);\n this.resolveResult();\n }\n };\n\n FragmentResolver.prototype.lookup = function (fragment, fragmentRef) {\n if (fragmentRef == null) {\n this.resolverData = {\n data: null\n };\n return;\n }\n\n var isPlural = fragment.metadata && fragment.metadata.plural && fragment.metadata.plural === true;\n\n if (isPlural) {\n if (fragmentRef.length === 0) {\n this.resolverData = {\n data: []\n };\n return;\n }\n }\n\n this._selector = getSelector(fragment, fragmentRef);\n var snapshot = lookupFragment(this._environment, this._selector);\n this.resolverData = getFragmentResult(snapshot);\n var owner = this._selector ? this._selector.kind === 'PluralReaderSelector' ? this._selector.selectors[0].owner : this._selector.owner : null;\n this.resolverData.owner = owner; //this.subscribe();\n };\n\n FragmentResolver.prototype.checkAndSuspense = function (suspense) {\n var _this = this;\n\n var _a;\n\n if (suspense && this.resolverData.isMissingData && this.resolverData.owner) {\n var fragmentOwner = this.resolverData.owner;\n\n var networkPromise = _getAndSavePromiseForFragmentRequestInFlight(this._fragment, fragmentOwner, this._environment);\n\n var parentQueryName = (_a = fragmentOwner.node.params.name) !== null && _a !== void 0 ? _a : 'Unknown Parent Query';\n\n if (networkPromise != null) {\n // When the Promise for the request resolves, we need to make sure to\n // update the cache with the latest data available in the store before\n // resolving the Promise\n var promise = networkPromise.then(function () {\n if (_this._idfragmentrefetch) {\n _this.resolveResult();\n } else {\n _this._idfragment = null;\n\n _this.dispose();\n } //;\n\n }).catch(function (_error) {\n if (_this._idfragmentrefetch) {\n _this.resolveResult();\n } else {\n _this._idfragment = null;\n\n _this.dispose();\n }\n }); // $FlowExpectedError[prop-missing] Expando to annotate Promises.\n\n promise.displayName = 'Relay(' + parentQueryName + ')';\n this.unsubscribe();\n this.refreshHooks = emptyVoid;\n throw promise;\n }\n\n process.env.NODE_ENV !== \"production\" ? process.env.NODE_ENV !== \"production\" ? warning(false, 'Relay: Tried reading fragment `%s` declared in ' + '`%s`, but it has missing data and its parent query `%s` is not ' + 'being fetched.\\n' + 'This might be fixed by by re-running the Relay Compiler. ' + ' Otherwise, make sure of the following:\\n' + '* You are correctly fetching `%s` if you are using a ' + '\"store-only\" `fetchPolicy`.\\n' + \"* Other queries aren't accidentally fetching and overwriting \" + 'the data for this fragment.\\n' + '* Any related mutations or subscriptions are fetching all of ' + 'the data for this fragment.\\n' + \"* Any related store updaters aren't accidentally deleting \" + 'data for this fragment.', this._fragment.name, this.name, parentQueryName, parentQueryName) : void 0 : void 0;\n }\n\n this.fetcherRefecth && this.fetcherRefecth.checkAndSuspense(suspense);\n };\n\n FragmentResolver.prototype.getData = function () {\n return this.result;\n };\n\n FragmentResolver.prototype.resolveResult = function () {\n var data = this.resolverData.data;\n\n if (this.refetchable || this.pagination) {\n var _a = this.fetcherRefecth.getData(),\n isLoading = _a.isLoading,\n error = _a.error;\n\n var refetch = this.refetch;\n\n if (!this.pagination) {\n // useRefetchable\n if ('production' !== process.env.NODE_ENV) {\n getRefetchMetadata(this._fragment, this.name);\n }\n\n this.result = {\n data: data,\n isLoading: isLoading,\n error: error,\n refetch: refetch\n };\n } else {\n // usePagination\n var connectionPathInFragmentData = getPaginationMetadata(this._fragment, this.name).connectionPathInFragmentData;\n var connection = getValueAtPath(data, connectionPathInFragmentData);\n var hasNext = getStateFromConnection('forward', this._fragment, connection).hasMore;\n var hasPrevious = getStateFromConnection('backward', this._fragment, connection).hasMore;\n\n var _b = this.fetcherNext.getData(),\n isLoadingNext = _b.isLoading,\n errorNext = _b.error;\n\n var _c = this.fetcherPrevious.getData(),\n isLoadingPrevious = _c.isLoading,\n errorPrevious = _c.error;\n\n this.result = {\n data: data,\n hasNext: hasNext,\n isLoadingNext: isLoadingNext,\n hasPrevious: hasPrevious,\n isLoadingPrevious: isLoadingPrevious,\n isLoading: isLoading,\n errorNext: errorNext,\n errorPrevious: errorPrevious,\n error: error,\n refetch: refetch,\n loadNext: this.loadNext,\n loadPrevious: this.loadPrevious\n };\n }\n } else {\n // useFragment\n this.result = data;\n }\n\n var snap = this.resolverData.snapshot;\n\n if (snap) {\n this._throwOrLogErrorsInSnapshot(snap);\n }\n\n this._subscribeResolve && this._subscribeResolve(this.result);\n };\n\n FragmentResolver.prototype.unsubscribe = function () {\n this._disposable && this._disposable.dispose();\n };\n\n FragmentResolver.prototype.subscribe = function () {\n var _this = this;\n\n var environment = this._environment;\n var renderedSnapshot = this.resolverData.snapshot;\n this.unsubscribe();\n var dataSubscriptions = [];\n\n if (renderedSnapshot) {\n if (Array.isArray(renderedSnapshot)) {\n renderedSnapshot.forEach(function (snapshot, idx) {\n dataSubscriptions.push(environment.subscribe(snapshot, function (latestSnapshot) {\n _this.resolverData.snapshot[idx] = latestSnapshot;\n _this.resolverData.data[idx] = latestSnapshot.data;\n _this.resolverData.isMissingData = isMissingData(_this.resolverData.snapshot);\n\n _this.refreshHooks();\n }));\n });\n } else {\n dataSubscriptions.push(environment.subscribe(renderedSnapshot, function (latestSnapshot) {\n _this.resolverData = getFragmentResult(latestSnapshot);\n\n _this.refreshHooks();\n }));\n }\n }\n\n this._disposable = {\n dispose: function () {\n dataSubscriptions.map(function (s) {\n return s.dispose();\n });\n _this._disposable = undefined;\n }\n };\n };\n\n FragmentResolver.prototype._throwOrLogErrorsInSnapshot = function (snapshot) {\n var _this = this;\n\n if (Array.isArray(snapshot)) {\n snapshot.forEach(function (s) {\n if (s.missingRequiredFields) {\n handlePotentialSnapshotErrors(_this._environment, s.missingRequiredFields, s.relayResolverErrors);\n }\n });\n } else {\n if (snapshot.missingRequiredFields) {\n handlePotentialSnapshotErrors(this._environment, snapshot.missingRequiredFields, snapshot.relayResolverErrors);\n }\n }\n };\n\n return FragmentResolver;\n}();\n\nexport { FragmentResolver };","import warning from 'fbjs/lib/warning';\nimport { useEffect, useRef, useMemo } from 'react';\nimport { getFragmentIdentifier, getFragment } from 'relay-runtime';\nimport { FragmentResolver } from './FragmentResolver';\nimport { useForceUpdate } from './useForceUpdate';\nimport { useRelayEnvironment } from './useRelayEnvironment';\nexport function useOssFragment(fragmentNode, fragmentRef, suspense, name, subscribeResolve) {\n var environment = useRelayEnvironment();\n var forceUpdate = useForceUpdate();\n var ref = useRef(null);\n var maybeHiddenOrFastRefresh = useRef(false);\n\n if (ref.current === null || ref.current === undefined || maybeHiddenOrFastRefresh.current) {\n ref.current = {\n resolver: new FragmentResolver(name)\n };\n maybeHiddenOrFastRefresh.current = false;\n }\n\n var resolver = ref.current.resolver;\n useEffect(function () {\n if (maybeHiddenOrFastRefresh.current == true) {\n forceUpdate();\n }\n\n return function () {\n ref.current.resolver.setUnmounted();\n maybeHiddenOrFastRefresh.current = true;\n }; // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n useEffect(function () {\n return function () {\n resolver.dispose();\n };\n }, [resolver]);\n var fragment = useMemo(function () {\n return getFragment(fragmentNode);\n }, [fragmentNode]);\n var idfragment = useMemo(function () {\n return getFragmentIdentifier(fragment, fragmentRef);\n }, [fragment, fragmentRef]);\n useEffect(function () {\n resolver.subscribe();\n return function () {\n resolver.unsubscribe();\n };\n }, [resolver, idfragment, environment]);\n resolver.subscribeResolve(subscribeResolve);\n resolver.resolve(environment, idfragment, fragment, fragmentRef);\n\n if (subscribeResolve) {\n return;\n }\n\n resolver.checkAndSuspense(suspense);\n resolver.setForceUpdate(forceUpdate);\n var data = resolver.getData();\n\n if ('production' !== process.env.NODE_ENV) {\n if (fragmentRef != null && (data === undefined || Array.isArray(data) && data.length > 0 && data.every(function (data) {\n return data === undefined;\n }))) {\n process.env.NODE_ENV !== \"production\" ? process.env.NODE_ENV !== \"production\" ? warning(false, 'Relay: Expected to have been able to read non-null data for ' + 'fragment `%s` declared in ' + '`%s`, since fragment reference was non-null. ' + \"Make sure that that `%s`'s parent isn't \" + 'holding on to and/or passing a fragment reference for data that ' + 'has been deleted.', fragment, name, name) : void 0 : void 0;\n }\n }\n\n return [data, resolver];\n}","import { FRAGMENT_NAME } from './RelayHooksTypes';\nimport { useOssFragment } from './useOssFragment';\nexport function useFragment(fragmentNode, fragmentRef) {\n var data = useOssFragment(fragmentNode, fragmentRef, false, FRAGMENT_NAME)[0];\n return data;\n}\nexport function useSuspenseFragment(fragmentNode, fragmentRef) {\n var data = useOssFragment(fragmentNode, fragmentRef, true, FRAGMENT_NAME)[0];\n return data;\n}\nexport function useFragmentSubscription(fragmentNode, fragmentRef, callback) {\n useOssFragment(fragmentNode, fragmentRef, false, FRAGMENT_NAME, callback);\n}","var __assign = this && this.__assign || function () {\n __assign = Object.assign || function (t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n\n return t;\n };\n\n return __assign.apply(this, arguments);\n};\n\nimport useMounted from '@restart/hooks/useMounted';\nimport invariant from 'fbjs/lib/invariant';\nimport React from 'react';\nimport { commitMutation } from 'relay-runtime';\nimport { useRelayEnvironment } from './useRelayEnvironment';\nvar useCallback = React.useCallback,\n useState = React.useState;\nexport function useMutation(mutation, userConfig,\n/** if not provided, the context environment will be used. */\nenvironment) {\n if (userConfig === void 0) {\n userConfig = {};\n }\n\n var _a = useState({\n loading: false,\n data: null,\n error: null\n }),\n state = _a[0],\n setState = _a[1];\n\n var isMounted = useMounted();\n var relayEnvironment = useRelayEnvironment();\n var resolvedEnvironment = environment || relayEnvironment;\n var configs = userConfig.configs,\n variables = userConfig.variables,\n uploadables = userConfig.uploadables,\n onCompleted = userConfig.onCompleted,\n onError = userConfig.onError,\n optimisticUpdater = userConfig.optimisticUpdater,\n optimisticResponse = userConfig.optimisticResponse,\n updater = userConfig.updater;\n var mutate = useCallback(function (config) {\n var mergedConfig = __assign({\n configs: configs,\n variables: variables,\n uploadables: uploadables,\n onCompleted: onCompleted,\n onError: onError,\n optimisticUpdater: optimisticUpdater,\n optimisticResponse: optimisticResponse,\n updater: updater\n }, config);\n\n !mergedConfig.variables ? process.env.NODE_ENV !== \"production\" ? !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'you must specify variables') : invariant(false) : void 0 : !false ? process.env.NODE_ENV !== \"production\" ? invariant(false) : invariant(false) : void 0 : void 0;\n\n if (isMounted()) {\n setState({\n loading: true,\n data: mergedConfig.optimisticResponse,\n error: null\n });\n }\n\n return new Promise(function (resolve, reject) {\n function handleError(error) {\n if (isMounted()) {\n setState({\n loading: false,\n data: null,\n error: error\n });\n }\n\n if (mergedConfig.onError) {\n mergedConfig.onError(error);\n resolve(null);\n } else {\n reject(error);\n }\n }\n\n commitMutation(resolvedEnvironment, __assign(__assign({}, mergedConfig), {\n mutation: mutation,\n variables: mergedConfig.variables,\n onCompleted: function (response, errors) {\n if (errors) {\n // FIXME: This isn't right. onError expects a single error.\n handleError(errors);\n return;\n }\n\n if (isMounted()) {\n setState({\n loading: false,\n data: response,\n error: null\n });\n }\n\n if (mergedConfig.onCompleted) {\n mergedConfig.onCompleted(response);\n }\n\n resolve(response);\n },\n onError: handleError\n }));\n });\n }, [resolvedEnvironment, configs, mutation, variables, uploadables, onCompleted, onError, optimisticUpdater, optimisticResponse, updater, isMounted]);\n return [mutate, state];\n}","import { useRef, useEffect } from 'react';\n\n/**\n * Track whether a component is current mounted. Generally less preferable than\n * properlly canceling effects so they don't run after a component is unmounted,\n * but helpful in cases where that isn't feasible, such as a `Promise` resolution.\n *\n * @returns a function that returns the current isMounted state of the component\n *\n * ```ts\n * const [data, setData] = useState(null)\n * const isMounted = useMounted()\n *\n * useEffect(() => {\n * fetchdata().then((newData) => {\n * if (isMounted()) {\n * setData(newData);\n * }\n * })\n * })\n * ```\n */\nexport default function useMounted() {\n const mounted = useRef(true);\n const isMounted = useRef(() => mounted.current);\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n };\n }, []);\n return isMounted.current;\n}","import { REFETCHABLE_NAME } from './RelayHooksTypes';\nimport { useOssFragment } from './useOssFragment';\nexport function useRefetchable(fragmentInput, fragmentRef) {\n var data = useOssFragment(fragmentInput, fragmentRef, false, REFETCHABLE_NAME)[0];\n return data;\n}\nexport function useRefetchableFragment(fragmentInput, fragmentRef) {\n var data = useOssFragment(fragmentInput, fragmentRef, true, REFETCHABLE_NAME)[0];\n return data;\n}\nexport function useRefetchableSubscription(fragmentInput, fragmentRef, callback) {\n useOssFragment(fragmentInput, fragmentRef, false, REFETCHABLE_NAME, callback);\n}","/**\n * Relay v16.2.0\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nmodule.exports = require('./lib/index.js');\n","'use strict';\n\nvar ConnectionHandler = require('./connection/ConnectionHandler');\nvar MutationHandlers = require('./connection/MutationHandlers');\nvar invariant = require('invariant');\nfunction RelayDefaultHandlerProvider(handle) {\n switch (handle) {\n case 'connection':\n return ConnectionHandler;\n case 'deleteRecord':\n return MutationHandlers.DeleteRecordHandler;\n case 'deleteEdge':\n return MutationHandlers.DeleteEdgeHandler;\n case 'appendEdge':\n return MutationHandlers.AppendEdgeHandler;\n case 'prependEdge':\n return MutationHandlers.PrependEdgeHandler;\n case 'appendNode':\n return MutationHandlers.AppendNodeHandler;\n case 'prependNode':\n return MutationHandlers.PrependNodeHandler;\n }\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayDefaultHandlerProvider: No handler provided for `%s`.', handle) : invariant(false) : void 0;\n}\nmodule.exports = RelayDefaultHandlerProvider;","'use strict';\n\nvar _require = require('../../store/ClientID'),\n generateClientID = _require.generateClientID;\nvar _require2 = require('../../store/RelayStoreUtils'),\n getStableStorageKey = _require2.getStableStorageKey;\nvar getRelayHandleKey = require('../../util/getRelayHandleKey');\nvar ConnectionInterface = require('./ConnectionInterface');\nvar invariant = require('invariant');\nvar warning = require(\"fbjs/lib/warning\");\nvar CONNECTION = 'connection';\nvar NEXT_EDGE_INDEX = '__connection_next_edge_index';\nfunction update(store, payload) {\n var record = store.get(payload.dataID);\n if (!record) {\n return;\n }\n var _ConnectionInterface$ = ConnectionInterface.get(),\n EDGES = _ConnectionInterface$.EDGES,\n END_CURSOR = _ConnectionInterface$.END_CURSOR,\n HAS_NEXT_PAGE = _ConnectionInterface$.HAS_NEXT_PAGE,\n HAS_PREV_PAGE = _ConnectionInterface$.HAS_PREV_PAGE,\n PAGE_INFO = _ConnectionInterface$.PAGE_INFO,\n PAGE_INFO_TYPE = _ConnectionInterface$.PAGE_INFO_TYPE,\n START_CURSOR = _ConnectionInterface$.START_CURSOR;\n var serverConnection = record.getLinkedRecord(payload.fieldKey);\n var serverPageInfo = serverConnection && serverConnection.getLinkedRecord(PAGE_INFO);\n if (!serverConnection) {\n record.setValue(null, payload.handleKey);\n return;\n }\n var clientConnectionID = generateClientID(record.getDataID(), payload.handleKey);\n var clientConnectionField = record.getLinkedRecord(payload.handleKey);\n var clientConnection = clientConnectionField !== null && clientConnectionField !== void 0 ? clientConnectionField : store.get(clientConnectionID);\n var clientPageInfo = clientConnection && clientConnection.getLinkedRecord(PAGE_INFO);\n if (!clientConnection) {\n var connection = store.create(clientConnectionID, serverConnection.getType());\n connection.setValue(0, NEXT_EDGE_INDEX);\n connection.copyFieldsFrom(serverConnection);\n var serverEdges = serverConnection.getLinkedRecords(EDGES);\n if (serverEdges) {\n serverEdges = serverEdges.map(function (edge) {\n return buildConnectionEdge(store, connection, edge);\n });\n connection.setLinkedRecords(serverEdges, EDGES);\n }\n record.setLinkedRecord(connection, payload.handleKey);\n clientPageInfo = store.create(generateClientID(connection.getDataID(), PAGE_INFO), PAGE_INFO_TYPE);\n clientPageInfo.setValue(false, HAS_NEXT_PAGE);\n clientPageInfo.setValue(false, HAS_PREV_PAGE);\n clientPageInfo.setValue(null, END_CURSOR);\n clientPageInfo.setValue(null, START_CURSOR);\n if (serverPageInfo) {\n clientPageInfo.copyFieldsFrom(serverPageInfo);\n }\n connection.setLinkedRecord(clientPageInfo, PAGE_INFO);\n } else {\n if (clientConnectionField == null) {\n record.setLinkedRecord(clientConnection, payload.handleKey);\n }\n var _connection = clientConnection;\n var _serverEdges = serverConnection.getLinkedRecords(EDGES);\n if (_serverEdges) {\n _serverEdges = _serverEdges.map(function (edge) {\n return buildConnectionEdge(store, _connection, edge);\n });\n }\n var prevEdges = _connection.getLinkedRecords(EDGES);\n var prevPageInfo = _connection.getLinkedRecord(PAGE_INFO);\n _connection.copyFieldsFrom(serverConnection);\n if (prevEdges) {\n _connection.setLinkedRecords(prevEdges, EDGES);\n }\n if (prevPageInfo) {\n _connection.setLinkedRecord(prevPageInfo, PAGE_INFO);\n }\n var nextEdges = [];\n var args = payload.args;\n if (prevEdges && _serverEdges) {\n if (args.after != null) {\n var _clientPageInfo;\n var clientEndCursor = (_clientPageInfo = clientPageInfo) === null || _clientPageInfo === void 0 ? void 0 : _clientPageInfo.getValue(END_CURSOR);\n var serverEndCursor = serverPageInfo === null || serverPageInfo === void 0 ? void 0 : serverPageInfo.getValue(END_CURSOR);\n var isAddingEdgesAfterCurrentPage = clientPageInfo && args.after === clientEndCursor;\n var isFillingOutCurrentPage = clientPageInfo && clientEndCursor === serverEndCursor;\n if (isAddingEdgesAfterCurrentPage || isFillingOutCurrentPage) {\n var nodeIDs = new Set();\n mergeEdges(prevEdges, nextEdges, nodeIDs);\n mergeEdges(_serverEdges, nextEdges, nodeIDs);\n } else {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'Relay: Unexpected after cursor `%s`, edges must ' + 'be fetched from the end of the list (`%s`).', args.after, clientPageInfo && clientPageInfo.getValue(END_CURSOR)) : void 0;\n return;\n }\n } else if (args.before != null) {\n if (clientPageInfo && args.before === clientPageInfo.getValue(START_CURSOR)) {\n var _nodeIDs = new Set();\n mergeEdges(_serverEdges, nextEdges, _nodeIDs);\n mergeEdges(prevEdges, nextEdges, _nodeIDs);\n } else {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'Relay: Unexpected before cursor `%s`, edges must ' + 'be fetched from the beginning of the list (`%s`).', args.before, clientPageInfo && clientPageInfo.getValue(START_CURSOR)) : void 0;\n return;\n }\n } else {\n nextEdges = _serverEdges;\n }\n } else if (_serverEdges) {\n nextEdges = _serverEdges;\n } else {\n nextEdges = prevEdges;\n }\n if (nextEdges != null && nextEdges !== prevEdges) {\n _connection.setLinkedRecords(nextEdges, EDGES);\n }\n if (clientPageInfo && serverPageInfo) {\n if (args.after == null && args.before == null) {\n clientPageInfo.copyFieldsFrom(serverPageInfo);\n } else if (args.before != null || args.after == null && args.last) {\n clientPageInfo.setValue(!!serverPageInfo.getValue(HAS_PREV_PAGE), HAS_PREV_PAGE);\n var startCursor = serverPageInfo.getValue(START_CURSOR);\n if (typeof startCursor === 'string') {\n clientPageInfo.setValue(startCursor, START_CURSOR);\n }\n } else if (args.after != null || args.before == null && args.first) {\n clientPageInfo.setValue(!!serverPageInfo.getValue(HAS_NEXT_PAGE), HAS_NEXT_PAGE);\n var endCursor = serverPageInfo.getValue(END_CURSOR);\n if (typeof endCursor === 'string') {\n clientPageInfo.setValue(endCursor, END_CURSOR);\n }\n }\n }\n }\n}\nfunction getConnection(record, key, filters) {\n var handleKey = getRelayHandleKey(CONNECTION, key, null);\n return record.getLinkedRecord(handleKey, filters);\n}\nfunction getConnectionID(recordID, key, filters) {\n var handleKey = getRelayHandleKey(CONNECTION, key, null);\n var storageKey = getStableStorageKey(handleKey, filters);\n return generateClientID(recordID, storageKey);\n}\nfunction insertEdgeAfter(record, newEdge, cursor) {\n var _ConnectionInterface$2 = ConnectionInterface.get(),\n CURSOR = _ConnectionInterface$2.CURSOR,\n EDGES = _ConnectionInterface$2.EDGES;\n var edges = record.getLinkedRecords(EDGES);\n if (!edges) {\n record.setLinkedRecords([newEdge], EDGES);\n return;\n }\n var nextEdges;\n if (cursor == null) {\n nextEdges = edges.concat(newEdge);\n } else {\n nextEdges = [];\n var foundCursor = false;\n for (var ii = 0; ii < edges.length; ii++) {\n var edge = edges[ii];\n nextEdges.push(edge);\n if (edge == null) {\n continue;\n }\n var edgeCursor = edge.getValue(CURSOR);\n if (cursor === edgeCursor) {\n nextEdges.push(newEdge);\n foundCursor = true;\n }\n }\n if (!foundCursor) {\n nextEdges.push(newEdge);\n }\n }\n record.setLinkedRecords(nextEdges, EDGES);\n}\nfunction createEdge(store, record, node, edgeType) {\n var _ConnectionInterface$3 = ConnectionInterface.get(),\n NODE = _ConnectionInterface$3.NODE;\n var edgeID = generateClientID(record.getDataID(), node.getDataID());\n var edge = store.get(edgeID);\n if (!edge) {\n edge = store.create(edgeID, edgeType);\n }\n edge.setLinkedRecord(node, NODE);\n if (edge.getValue('cursor') == null) {\n edge.setValue(null, 'cursor');\n }\n return edge;\n}\nfunction insertEdgeBefore(record, newEdge, cursor) {\n var _ConnectionInterface$4 = ConnectionInterface.get(),\n CURSOR = _ConnectionInterface$4.CURSOR,\n EDGES = _ConnectionInterface$4.EDGES;\n var edges = record.getLinkedRecords(EDGES);\n if (!edges) {\n record.setLinkedRecords([newEdge], EDGES);\n return;\n }\n var nextEdges;\n if (cursor == null) {\n nextEdges = [newEdge].concat(edges);\n } else {\n nextEdges = [];\n var foundCursor = false;\n for (var ii = 0; ii < edges.length; ii++) {\n var edge = edges[ii];\n if (edge != null) {\n var edgeCursor = edge.getValue(CURSOR);\n if (cursor === edgeCursor) {\n nextEdges.push(newEdge);\n foundCursor = true;\n }\n }\n nextEdges.push(edge);\n }\n if (!foundCursor) {\n nextEdges.unshift(newEdge);\n }\n }\n record.setLinkedRecords(nextEdges, EDGES);\n}\nfunction deleteNode(record, nodeID) {\n var _ConnectionInterface$5 = ConnectionInterface.get(),\n EDGES = _ConnectionInterface$5.EDGES,\n NODE = _ConnectionInterface$5.NODE;\n var edges = record.getLinkedRecords(EDGES);\n if (!edges) {\n return;\n }\n var nextEdges;\n for (var ii = 0; ii < edges.length; ii++) {\n var edge = edges[ii];\n var node = edge && edge.getLinkedRecord(NODE);\n if (node != null && node.getDataID() === nodeID) {\n if (nextEdges === undefined) {\n nextEdges = edges.slice(0, ii);\n }\n } else if (nextEdges !== undefined) {\n nextEdges.push(edge);\n }\n }\n if (nextEdges !== undefined) {\n record.setLinkedRecords(nextEdges, EDGES);\n }\n}\nfunction buildConnectionEdge(store, connection, edge) {\n if (edge == null) {\n return edge;\n }\n var _ConnectionInterface$6 = ConnectionInterface.get(),\n EDGES = _ConnectionInterface$6.EDGES;\n var edgeIndex = connection.getValue(NEXT_EDGE_INDEX);\n !(typeof edgeIndex === 'number') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'ConnectionHandler: Expected %s to be a number, got `%s`.', NEXT_EDGE_INDEX, edgeIndex) : invariant(false) : void 0;\n var edgeID = generateClientID(connection.getDataID(), EDGES, edgeIndex);\n var connectionEdge = store.create(edgeID, edge.getType());\n connectionEdge.copyFieldsFrom(edge);\n if (connectionEdge.getValue('cursor') == null) {\n connectionEdge.setValue(null, 'cursor');\n }\n connection.setValue(edgeIndex + 1, NEXT_EDGE_INDEX);\n return connectionEdge;\n}\nfunction mergeEdges(sourceEdges, targetEdges, nodeIDs) {\n var _ConnectionInterface$7 = ConnectionInterface.get(),\n NODE = _ConnectionInterface$7.NODE;\n for (var ii = 0; ii < sourceEdges.length; ii++) {\n var edge = sourceEdges[ii];\n if (!edge) {\n continue;\n }\n var node = edge.getLinkedRecord(NODE);\n var nodeID = node && node.getDataID();\n if (nodeID) {\n if (nodeIDs.has(nodeID)) {\n continue;\n }\n nodeIDs.add(nodeID);\n }\n targetEdges.push(edge);\n }\n}\nmodule.exports = {\n buildConnectionEdge: buildConnectionEdge,\n createEdge: createEdge,\n deleteNode: deleteNode,\n getConnection: getConnection,\n getConnectionID: getConnectionID,\n insertEdgeAfter: insertEdgeAfter,\n insertEdgeBefore: insertEdgeBefore,\n update: update\n};","'use strict';\n\nvar CONNECTION_CALLS = {\n after: true,\n before: true,\n find: true,\n first: true,\n last: true,\n surrounds: true\n};\nvar config = {\n CURSOR: 'cursor',\n EDGES: 'edges',\n END_CURSOR: 'endCursor',\n HAS_NEXT_PAGE: 'hasNextPage',\n HAS_PREV_PAGE: 'hasPreviousPage',\n NODE: 'node',\n PAGE_INFO_TYPE: 'PageInfo',\n PAGE_INFO: 'pageInfo',\n START_CURSOR: 'startCursor'\n};\nvar ConnectionInterface = {\n inject: function inject(newConfig) {\n config = newConfig;\n },\n get: function get() {\n return config;\n },\n isConnectionCall: function isConnectionCall(call) {\n return CONNECTION_CALLS.hasOwnProperty(call.name);\n }\n};\nmodule.exports = ConnectionInterface;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _createForOfIteratorHelper2 = _interopRequireDefault(require(\"@babel/runtime/helpers/createForOfIteratorHelper\"));\nvar ConnectionHandler = require('./ConnectionHandler');\nvar ConnectionInterface = require('./ConnectionInterface');\nvar invariant = require('invariant');\nvar warning = require(\"fbjs/lib/warning\");\nvar DeleteRecordHandler = {\n update: function update(store, payload) {\n var record = store.get(payload.dataID);\n if (record != null) {\n var idOrIds = record.getValue(payload.fieldKey);\n if (typeof idOrIds === 'string') {\n store[\"delete\"](idOrIds);\n } else if (Array.isArray(idOrIds)) {\n idOrIds.forEach(function (id) {\n if (typeof id === 'string') {\n store[\"delete\"](id);\n }\n });\n }\n }\n }\n};\nvar DeleteEdgeHandler = {\n update: function update(store, payload) {\n var record = store.get(payload.dataID);\n if (record == null) {\n return;\n }\n var connections = payload.handleArgs.connections;\n !(connections != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'MutationHandlers: Expected connection IDs to be specified.') : invariant(false) : void 0;\n var idOrIds = record.getValue(payload.fieldKey);\n var idList = Array.isArray(idOrIds) ? idOrIds : [idOrIds];\n idList.forEach(function (id) {\n if (typeof id === 'string') {\n var _iterator = (0, _createForOfIteratorHelper2[\"default\"])(connections),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var connectionID = _step.value;\n var connection = store.get(connectionID);\n if (connection == null) {\n process.env.NODE_ENV !== \"production\" ? warning(false, \"[Relay] The connection with id `%s` doesn't exist.\", connectionID) : void 0;\n continue;\n }\n ConnectionHandler.deleteNode(connection, id);\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n }\n });\n }\n};\nvar AppendEdgeHandler = {\n update: edgeUpdater(ConnectionHandler.insertEdgeAfter)\n};\nvar PrependEdgeHandler = {\n update: edgeUpdater(ConnectionHandler.insertEdgeBefore)\n};\nvar AppendNodeHandler = {\n update: nodeUpdater(ConnectionHandler.insertEdgeAfter)\n};\nvar PrependNodeHandler = {\n update: nodeUpdater(ConnectionHandler.insertEdgeBefore)\n};\nfunction edgeUpdater(insertFn) {\n return function (store, payload) {\n var _serverEdges;\n var record = store.get(payload.dataID);\n if (record == null) {\n return;\n }\n var connections = payload.handleArgs.connections;\n !(connections != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'MutationHandlers: Expected connection IDs to be specified.') : invariant(false) : void 0;\n var singleServerEdge, serverEdges;\n try {\n singleServerEdge = record.getLinkedRecord(payload.fieldKey);\n } catch (_unused) {}\n if (!singleServerEdge) {\n try {\n serverEdges = record.getLinkedRecords(payload.fieldKey);\n } catch (_unused2) {}\n }\n if (singleServerEdge == null && serverEdges == null) {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'MutationHandlers: Expected the server edge to be non-null.') : void 0;\n return;\n }\n var _ConnectionInterface$ = ConnectionInterface.get(),\n NODE = _ConnectionInterface$.NODE,\n EDGES = _ConnectionInterface$.EDGES;\n var serverEdgeList = (_serverEdges = serverEdges) !== null && _serverEdges !== void 0 ? _serverEdges : [singleServerEdge];\n var _iterator2 = (0, _createForOfIteratorHelper2[\"default\"])(serverEdgeList),\n _step2;\n try {\n var _loop = function _loop() {\n var serverEdge = _step2.value;\n if (serverEdge == null) {\n return \"continue\";\n }\n var serverNode = serverEdge.getLinkedRecord('node');\n if (!serverNode) {\n return \"continue\";\n }\n var serverNodeId = serverNode.getDataID();\n var _iterator3 = (0, _createForOfIteratorHelper2[\"default\"])(connections),\n _step3;\n try {\n for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {\n var connectionID = _step3.value;\n var connection = store.get(connectionID);\n if (connection == null) {\n process.env.NODE_ENV !== \"production\" ? warning(false, \"[Relay] The connection with id `%s` doesn't exist.\", connectionID) : void 0;\n continue;\n }\n var nodeAlreadyExistsInConnection = (_connection$getLinked = connection.getLinkedRecords(EDGES)) === null || _connection$getLinked === void 0 ? void 0 : _connection$getLinked.some(function (edge) {\n var _edge$getLinkedRecord;\n return (edge === null || edge === void 0 ? void 0 : (_edge$getLinkedRecord = edge.getLinkedRecord(NODE)) === null || _edge$getLinkedRecord === void 0 ? void 0 : _edge$getLinkedRecord.getDataID()) === serverNodeId;\n });\n if (nodeAlreadyExistsInConnection) {\n continue;\n }\n var clientEdge = ConnectionHandler.buildConnectionEdge(store, connection, serverEdge);\n !(clientEdge != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'MutationHandlers: Failed to build the edge.') : invariant(false) : void 0;\n insertFn(connection, clientEdge);\n }\n } catch (err) {\n _iterator3.e(err);\n } finally {\n _iterator3.f();\n }\n };\n for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n var _connection$getLinked;\n var _ret = _loop();\n if (_ret === \"continue\") continue;\n }\n } catch (err) {\n _iterator2.e(err);\n } finally {\n _iterator2.f();\n }\n };\n}\nfunction nodeUpdater(insertFn) {\n return function (store, payload) {\n var _serverNodes;\n var record = store.get(payload.dataID);\n if (record == null) {\n return;\n }\n var _payload$handleArgs = payload.handleArgs,\n connections = _payload$handleArgs.connections,\n edgeTypeName = _payload$handleArgs.edgeTypeName;\n !(connections != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'MutationHandlers: Expected connection IDs to be specified.') : invariant(false) : void 0;\n !(edgeTypeName != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'MutationHandlers: Expected edge typename to be specified.') : invariant(false) : void 0;\n var singleServerNode;\n var serverNodes;\n try {\n singleServerNode = record.getLinkedRecord(payload.fieldKey);\n } catch (_unused3) {}\n if (!singleServerNode) {\n try {\n serverNodes = record.getLinkedRecords(payload.fieldKey);\n } catch (_unused4) {}\n }\n if (singleServerNode == null && serverNodes == null) {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'MutationHandlers: Expected target node to exist.') : void 0;\n return;\n }\n var _ConnectionInterface$2 = ConnectionInterface.get(),\n NODE = _ConnectionInterface$2.NODE,\n EDGES = _ConnectionInterface$2.EDGES;\n var serverNodeList = (_serverNodes = serverNodes) !== null && _serverNodes !== void 0 ? _serverNodes : [singleServerNode];\n var _iterator4 = (0, _createForOfIteratorHelper2[\"default\"])(serverNodeList),\n _step4;\n try {\n var _loop2 = function _loop2() {\n var serverNode = _step4.value;\n if (serverNode == null) {\n return \"continue\";\n }\n var serverNodeId = serverNode.getDataID();\n var _iterator5 = (0, _createForOfIteratorHelper2[\"default\"])(connections),\n _step5;\n try {\n for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {\n var connectionID = _step5.value;\n var connection = store.get(connectionID);\n if (connection == null) {\n process.env.NODE_ENV !== \"production\" ? warning(false, \"[Relay] The connection with id `%s` doesn't exist.\", connectionID) : void 0;\n continue;\n }\n var nodeAlreadyExistsInConnection = (_connection$getLinked2 = connection.getLinkedRecords(EDGES)) === null || _connection$getLinked2 === void 0 ? void 0 : _connection$getLinked2.some(function (edge) {\n var _edge$getLinkedRecord2;\n return (edge === null || edge === void 0 ? void 0 : (_edge$getLinkedRecord2 = edge.getLinkedRecord(NODE)) === null || _edge$getLinkedRecord2 === void 0 ? void 0 : _edge$getLinkedRecord2.getDataID()) === serverNodeId;\n });\n if (nodeAlreadyExistsInConnection) {\n continue;\n }\n var clientEdge = ConnectionHandler.createEdge(store, connection, serverNode, edgeTypeName);\n !(clientEdge != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'MutationHandlers: Failed to build the edge.') : invariant(false) : void 0;\n insertFn(connection, clientEdge);\n }\n } catch (err) {\n _iterator5.e(err);\n } finally {\n _iterator5.f();\n }\n };\n for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {\n var _connection$getLinked2;\n var _ret2 = _loop2();\n if (_ret2 === \"continue\") continue;\n }\n } catch (err) {\n _iterator4.e(err);\n } finally {\n _iterator4.f();\n }\n };\n}\nmodule.exports = {\n AppendEdgeHandler: AppendEdgeHandler,\n DeleteRecordHandler: DeleteRecordHandler,\n PrependEdgeHandler: PrependEdgeHandler,\n AppendNodeHandler: AppendNodeHandler,\n PrependNodeHandler: PrependNodeHandler,\n DeleteEdgeHandler: DeleteEdgeHandler\n};","'use strict';\n\nvar ConnectionHandler = require('./handlers/connection/ConnectionHandler');\nvar ConnectionInterface = require('./handlers/connection/ConnectionInterface');\nvar MutationHandlers = require('./handlers/connection/MutationHandlers');\nvar RelayDefaultHandlerProvider = require('./handlers/RelayDefaultHandlerProvider');\nvar applyOptimisticMutation = require('./mutations/applyOptimisticMutation');\nvar commitLocalUpdate = require('./mutations/commitLocalUpdate');\nvar commitMutation = require('./mutations/commitMutation');\nvar RelayDeclarativeMutationConfig = require('./mutations/RelayDeclarativeMutationConfig');\nvar RelayNetwork = require('./network/RelayNetwork');\nvar RelayObservable = require('./network/RelayObservable');\nvar RelayQueryResponseCache = require('./network/RelayQueryResponseCache');\nvar fetchQuery = require('./query/fetchQuery');\nvar fetchQuery_DEPRECATED = require('./query/fetchQuery_DEPRECATED');\nvar fetchQueryInternal = require('./query/fetchQueryInternal');\nvar GraphQLTag = require('./query/GraphQLTag');\nvar PreloadableQueryRegistry = require('./query/PreloadableQueryRegistry');\nvar _require = require('./store/ClientID'),\n generateClientID = _require.generateClientID,\n generateUniqueClientID = _require.generateUniqueClientID,\n isClientID = _require.isClientID;\nvar createFragmentSpecResolver = require('./store/createFragmentSpecResolver');\nvar createRelayContext = require('./store/createRelayContext');\nvar _require2 = require('./store/experimental-live-resolvers/LiveResolverSuspenseSentinel'),\n isSuspenseSentinel = _require2.isSuspenseSentinel,\n suspenseSentinel = _require2.suspenseSentinel;\nvar isRelayModernEnvironment = require('./store/isRelayModernEnvironment');\nvar normalizeResponse = require('./store/normalizeResponse');\nvar readInlineData = require('./store/readInlineData');\nvar RelayConcreteVariables = require('./store/RelayConcreteVariables');\nvar RelayModernEnvironment = require('./store/RelayModernEnvironment');\nvar RelayModernOperationDescriptor = require('./store/RelayModernOperationDescriptor');\nvar RelayModernRecord = require('./store/RelayModernRecord');\nvar RelayModernSelector = require('./store/RelayModernSelector');\nvar RelayModernStore = require('./store/RelayModernStore');\nvar RelayOperationTracker = require('./store/RelayOperationTracker');\nvar RelayRecordSource = require('./store/RelayRecordSource');\nvar RelayStoreUtils = require('./store/RelayStoreUtils');\nvar ResolverFragments = require('./store/ResolverFragments');\nvar ViewerPattern = require('./store/ViewerPattern');\nvar requestSubscription = require('./subscription/requestSubscription');\nvar createPayloadFor3DField = require('./util/createPayloadFor3DField');\nvar deepFreeze = require('./util/deepFreeze');\nvar getFragmentIdentifier = require('./util/getFragmentIdentifier');\nvar getPaginationMetadata = require('./util/getPaginationMetadata');\nvar getPaginationVariables = require('./util/getPaginationVariables');\nvar getPendingOperationsForFragment = require('./util/getPendingOperationsForFragment');\nvar getRefetchMetadata = require('./util/getRefetchMetadata');\nvar getRelayHandleKey = require('./util/getRelayHandleKey');\nvar getRequestIdentifier = require('./util/getRequestIdentifier');\nvar getValueAtPath = require('./util/getValueAtPath');\nvar handlePotentialSnapshotErrors = require('./util/handlePotentialSnapshotErrors');\nvar isPromise = require('./util/isPromise');\nvar isScalarAndEqual = require('./util/isScalarAndEqual');\nvar recycleNodesInto = require('./util/recycleNodesInto');\nvar RelayConcreteNode = require('./util/RelayConcreteNode');\nvar RelayDefaultHandleKey = require('./util/RelayDefaultHandleKey');\nvar RelayError = require('./util/RelayError');\nvar RelayFeatureFlags = require('./util/RelayFeatureFlags');\nvar RelayProfiler = require('./util/RelayProfiler');\nvar RelayReplaySubject = require('./util/RelayReplaySubject');\nvar stableCopy = require('./util/stableCopy');\nvar withProvidedVariables = require('./util/withProvidedVariables');\nif (process.env.NODE_ENV !== \"production\") {\n var mapStr = typeof Map !== 'function' ? 'Map' : null;\n var setStr = typeof Set !== 'function' ? 'Set' : null;\n var promiseStr = typeof Promise !== 'function' ? 'Promise' : null;\n var objStr = typeof Object.assign !== 'function' ? 'Object.assign' : null;\n if (mapStr || setStr || promiseStr || objStr) {\n throw new Error(\"relay-runtime requires \".concat([mapStr, setStr, promiseStr, objStr].filter(Boolean).join(', and '), \" to exist. \") + 'Use a polyfill to provide these for older browsers.');\n }\n}\nmodule.exports = {\n Environment: RelayModernEnvironment,\n Network: RelayNetwork,\n Observable: RelayObservable,\n QueryResponseCache: RelayQueryResponseCache,\n RecordSource: RelayRecordSource,\n Record: RelayModernRecord,\n ReplaySubject: RelayReplaySubject,\n Store: RelayModernStore,\n areEqualSelectors: RelayModernSelector.areEqualSelectors,\n createFragmentSpecResolver: createFragmentSpecResolver,\n createNormalizationSelector: RelayModernSelector.createNormalizationSelector,\n createOperationDescriptor: RelayModernOperationDescriptor.createOperationDescriptor,\n createReaderSelector: RelayModernSelector.createReaderSelector,\n createRequestDescriptor: RelayModernOperationDescriptor.createRequestDescriptor,\n getArgumentValues: RelayStoreUtils.getArgumentValues,\n getDataIDsFromFragment: RelayModernSelector.getDataIDsFromFragment,\n getDataIDsFromObject: RelayModernSelector.getDataIDsFromObject,\n getNode: GraphQLTag.getNode,\n getFragment: GraphQLTag.getFragment,\n getInlineDataFragment: GraphQLTag.getInlineDataFragment,\n getModuleComponentKey: RelayStoreUtils.getModuleComponentKey,\n getModuleOperationKey: RelayStoreUtils.getModuleOperationKey,\n getPaginationFragment: GraphQLTag.getPaginationFragment,\n getPluralSelector: RelayModernSelector.getPluralSelector,\n getRefetchableFragment: GraphQLTag.getRefetchableFragment,\n getRequest: GraphQLTag.getRequest,\n getRequestIdentifier: getRequestIdentifier,\n getSelector: RelayModernSelector.getSelector,\n getSelectorsFromObject: RelayModernSelector.getSelectorsFromObject,\n getSingularSelector: RelayModernSelector.getSingularSelector,\n getStorageKey: RelayStoreUtils.getStorageKey,\n getVariablesFromFragment: RelayModernSelector.getVariablesFromFragment,\n getVariablesFromObject: RelayModernSelector.getVariablesFromObject,\n getVariablesFromPluralFragment: RelayModernSelector.getVariablesFromPluralFragment,\n getVariablesFromSingularFragment: RelayModernSelector.getVariablesFromSingularFragment,\n handlePotentialSnapshotErrors: handlePotentialSnapshotErrors,\n graphql: GraphQLTag.graphql,\n isFragment: GraphQLTag.isFragment,\n isInlineDataFragment: GraphQLTag.isInlineDataFragment,\n isSuspenseSentinel: isSuspenseSentinel,\n suspenseSentinel: suspenseSentinel,\n isRequest: GraphQLTag.isRequest,\n readInlineData: readInlineData,\n MutationTypes: RelayDeclarativeMutationConfig.MutationTypes,\n RangeOperations: RelayDeclarativeMutationConfig.RangeOperations,\n DefaultHandlerProvider: RelayDefaultHandlerProvider,\n ConnectionHandler: ConnectionHandler,\n MutationHandlers: MutationHandlers,\n VIEWER_ID: ViewerPattern.VIEWER_ID,\n VIEWER_TYPE: ViewerPattern.VIEWER_TYPE,\n applyOptimisticMutation: applyOptimisticMutation,\n commitLocalUpdate: commitLocalUpdate,\n commitMutation: commitMutation,\n fetchQuery: fetchQuery,\n fetchQuery_DEPRECATED: fetchQuery_DEPRECATED,\n isRelayModernEnvironment: isRelayModernEnvironment,\n requestSubscription: requestSubscription,\n ConnectionInterface: ConnectionInterface,\n PreloadableQueryRegistry: PreloadableQueryRegistry,\n RelayProfiler: RelayProfiler,\n createPayloadFor3DField: createPayloadFor3DField,\n RelayConcreteNode: RelayConcreteNode,\n RelayError: RelayError,\n RelayFeatureFlags: RelayFeatureFlags,\n DEFAULT_HANDLE_KEY: RelayDefaultHandleKey.DEFAULT_HANDLE_KEY,\n FRAGMENTS_KEY: RelayStoreUtils.FRAGMENTS_KEY,\n FRAGMENT_OWNER_KEY: RelayStoreUtils.FRAGMENT_OWNER_KEY,\n ID_KEY: RelayStoreUtils.ID_KEY,\n REF_KEY: RelayStoreUtils.REF_KEY,\n REFS_KEY: RelayStoreUtils.REFS_KEY,\n ROOT_ID: RelayStoreUtils.ROOT_ID,\n ROOT_TYPE: RelayStoreUtils.ROOT_TYPE,\n TYPENAME_KEY: RelayStoreUtils.TYPENAME_KEY,\n deepFreeze: deepFreeze,\n generateClientID: generateClientID,\n generateUniqueClientID: generateUniqueClientID,\n getRelayHandleKey: getRelayHandleKey,\n isClientID: isClientID,\n isPromise: isPromise,\n isScalarAndEqual: isScalarAndEqual,\n recycleNodesInto: recycleNodesInto,\n stableCopy: stableCopy,\n getFragmentIdentifier: getFragmentIdentifier,\n getRefetchMetadata: getRefetchMetadata,\n getPaginationMetadata: getPaginationMetadata,\n getPaginationVariables: getPaginationVariables,\n getPendingOperationsForFragment: getPendingOperationsForFragment,\n getValueAtPath: getValueAtPath,\n __internal: {\n ResolverFragments: ResolverFragments,\n OperationTracker: RelayOperationTracker,\n createRelayContext: createRelayContext,\n getOperationVariables: RelayConcreteVariables.getOperationVariables,\n getLocalVariables: RelayConcreteVariables.getLocalVariables,\n fetchQuery: fetchQueryInternal.fetchQuery,\n fetchQueryDeduped: fetchQueryInternal.fetchQueryDeduped,\n getPromiseForActiveRequest: fetchQueryInternal.getPromiseForActiveRequest,\n getObservableForActiveRequest: fetchQueryInternal.getObservableForActiveRequest,\n normalizeResponse: normalizeResponse,\n withProvidedVariables: withProvidedVariables\n }\n};","'use strict';\n\nvar invariant = require('invariant');\nvar INTERNAL_ACTOR_IDENTIFIER_DO_NOT_USE = 'INTERNAL_ACTOR_IDENTIFIER_DO_NOT_USE';\nfunction assertInternalActorIdentifier(actorIdentifier) {\n !(actorIdentifier === INTERNAL_ACTOR_IDENTIFIER_DO_NOT_USE) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Expected to use only internal version of the `actorIdentifier`. \"%s\" was provided.', actorIdentifier) : invariant(false) : void 0;\n}\nmodule.exports = {\n assertInternalActorIdentifier: assertInternalActorIdentifier,\n getActorIdentifier: function getActorIdentifier(actorID) {\n return actorID;\n },\n getDefaultActorIdentifier: function getDefaultActorIdentifier() {\n throw new Error('Not Implemented');\n },\n INTERNAL_ACTOR_IDENTIFIER_DO_NOT_USE: INTERNAL_ACTOR_IDENTIFIER_DO_NOT_USE\n};","'use strict';\n\nvar ACTOR_IDENTIFIER_FIELD_NAME = 'actor_key';\nvar _require = require('./ActorIdentifier'),\n getActorIdentifier = _require.getActorIdentifier;\nfunction getActorIdentifierFromPayload(payload) {\n if (payload != null && typeof payload === 'object' && typeof payload[ACTOR_IDENTIFIER_FIELD_NAME] === 'string') {\n return getActorIdentifier(payload[ACTOR_IDENTIFIER_FIELD_NAME]);\n }\n}\nmodule.exports = {\n ACTOR_IDENTIFIER_FIELD_NAME: ACTOR_IDENTIFIER_FIELD_NAME,\n getActorIdentifierFromPayload: getActorIdentifierFromPayload\n};","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _createForOfIteratorHelper2 = _interopRequireDefault(require(\"@babel/runtime/helpers/createForOfIteratorHelper\"));\nvar ConnectionHandler = require('../handlers/connection/ConnectionHandler');\nvar warning = require(\"fbjs/lib/warning\");\nvar MutationTypes = Object.freeze({\n RANGE_ADD: 'RANGE_ADD',\n RANGE_DELETE: 'RANGE_DELETE',\n NODE_DELETE: 'NODE_DELETE'\n});\nvar RangeOperations = Object.freeze({\n APPEND: 'append',\n PREPEND: 'prepend'\n});\nfunction convert(configs, request, optimisticUpdater, updater) {\n var configOptimisticUpdates = optimisticUpdater ? [optimisticUpdater] : [];\n var configUpdates = updater ? [updater] : [];\n configs.forEach(function (config) {\n switch (config.type) {\n case 'NODE_DELETE':\n var nodeDeleteResult = nodeDelete(config, request);\n if (nodeDeleteResult) {\n configOptimisticUpdates.push(nodeDeleteResult);\n configUpdates.push(nodeDeleteResult);\n }\n break;\n case 'RANGE_ADD':\n var rangeAddResult = rangeAdd(config, request);\n if (rangeAddResult) {\n configOptimisticUpdates.push(rangeAddResult);\n configUpdates.push(rangeAddResult);\n }\n break;\n case 'RANGE_DELETE':\n var rangeDeleteResult = rangeDelete(config, request);\n if (rangeDeleteResult) {\n configOptimisticUpdates.push(rangeDeleteResult);\n configUpdates.push(rangeDeleteResult);\n }\n break;\n }\n });\n return {\n optimisticUpdater: function optimisticUpdater(store, data) {\n configOptimisticUpdates.forEach(function (eachOptimisticUpdater) {\n eachOptimisticUpdater(store, data);\n });\n },\n updater: function updater(store, data) {\n configUpdates.forEach(function (eachUpdater) {\n eachUpdater(store, data);\n });\n }\n };\n}\nfunction nodeDelete(config, request) {\n var deletedIDFieldName = config.deletedIDFieldName;\n var rootField = getRootField(request);\n if (!rootField) {\n return null;\n }\n return function (store, data) {\n var payload = store.getRootField(rootField);\n if (!payload) {\n return;\n }\n var deleteID = payload.getValue(deletedIDFieldName);\n var deleteIDs = Array.isArray(deleteID) ? deleteID : [deleteID];\n deleteIDs.forEach(function (id) {\n if (id && typeof id === 'string') {\n store[\"delete\"](id);\n }\n });\n };\n}\nfunction rangeAdd(config, request) {\n var parentID = config.parentID,\n connectionInfo = config.connectionInfo,\n edgeName = config.edgeName;\n if (!parentID) {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'RelayDeclarativeMutationConfig: For mutation config RANGE_ADD ' + 'to work you must include a parentID') : void 0;\n return null;\n }\n var rootField = getRootField(request);\n if (!connectionInfo || !rootField) {\n return null;\n }\n return function (store, data) {\n var parent = store.get(parentID);\n if (!parent) {\n return;\n }\n var payload = store.getRootField(rootField);\n if (!payload) {\n return;\n }\n var serverEdge = payload.getLinkedRecord(edgeName);\n var _iterator = (0, _createForOfIteratorHelper2[\"default\"])(connectionInfo),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var info = _step.value;\n if (!serverEdge) {\n continue;\n }\n var connection = ConnectionHandler.getConnection(parent, info.key, info.filters);\n if (!connection) {\n continue;\n }\n var clientEdge = ConnectionHandler.buildConnectionEdge(store, connection, serverEdge);\n if (!clientEdge) {\n continue;\n }\n switch (info.rangeBehavior) {\n case 'append':\n ConnectionHandler.insertEdgeAfter(connection, clientEdge);\n break;\n case 'prepend':\n ConnectionHandler.insertEdgeBefore(connection, clientEdge);\n break;\n default:\n process.env.NODE_ENV !== \"production\" ? warning(false, 'RelayDeclarativeMutationConfig: RANGE_ADD range behavior `%s` ' + 'will not work as expected in RelayModern, supported range ' + \"behaviors are 'append', 'prepend'.\", info.rangeBehavior) : void 0;\n break;\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n };\n}\nfunction rangeDelete(config, request) {\n var parentID = config.parentID,\n connectionKeys = config.connectionKeys,\n pathToConnection = config.pathToConnection,\n deletedIDFieldName = config.deletedIDFieldName;\n if (!parentID) {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'RelayDeclarativeMutationConfig: For mutation config RANGE_DELETE ' + 'to work you must include a parentID') : void 0;\n return null;\n }\n var rootField = getRootField(request);\n if (!rootField) {\n return null;\n }\n return function (store, data) {\n if (!data) {\n return;\n }\n var deleteIDs = [];\n var deletedIDField = data[rootField];\n if (deletedIDField && Array.isArray(deletedIDFieldName)) {\n var _iterator2 = (0, _createForOfIteratorHelper2[\"default\"])(deletedIDFieldName),\n _step2;\n try {\n for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n var eachField = _step2.value;\n if (deletedIDField && typeof deletedIDField === 'object') {\n deletedIDField = deletedIDField[eachField];\n }\n }\n } catch (err) {\n _iterator2.e(err);\n } finally {\n _iterator2.f();\n }\n if (Array.isArray(deletedIDField)) {\n deletedIDField.forEach(function (idObject) {\n if (idObject && idObject.id && typeof idObject === 'object' && typeof idObject.id === 'string') {\n deleteIDs.push(idObject.id);\n }\n });\n } else if (deletedIDField && deletedIDField.id && typeof deletedIDField.id === 'string') {\n deleteIDs.push(deletedIDField.id);\n }\n } else if (deletedIDField && typeof deletedIDFieldName === 'string' && typeof deletedIDField === 'object') {\n deletedIDField = deletedIDField[deletedIDFieldName];\n if (typeof deletedIDField === 'string') {\n deleteIDs.push(deletedIDField);\n } else if (Array.isArray(deletedIDField)) {\n deletedIDField.forEach(function (id) {\n if (typeof id === 'string') {\n deleteIDs.push(id);\n }\n });\n }\n }\n deleteNode(parentID, connectionKeys, pathToConnection, store, deleteIDs);\n };\n}\nfunction deleteNode(parentID, connectionKeys, pathToConnection, store, deleteIDs) {\n process.env.NODE_ENV !== \"production\" ? warning(connectionKeys != null, 'RelayDeclarativeMutationConfig: RANGE_DELETE must provide a ' + 'connectionKeys') : void 0;\n var parent = store.get(parentID);\n if (!parent) {\n return;\n }\n if (pathToConnection.length < 2) {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'RelayDeclarativeMutationConfig: RANGE_DELETE ' + 'pathToConnection must include at least parent and connection') : void 0;\n return;\n }\n var recordProxy = parent;\n for (var i = 1; i < pathToConnection.length - 1; i++) {\n if (recordProxy) {\n recordProxy = recordProxy.getLinkedRecord(pathToConnection[i]);\n }\n }\n if (!connectionKeys || !recordProxy) {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'RelayDeclarativeMutationConfig: RANGE_DELETE ' + 'pathToConnection is incorrect. Unable to find connection with ' + 'parentID: %s and path: %s', parentID, pathToConnection.toString()) : void 0;\n return;\n }\n var _iterator3 = (0, _createForOfIteratorHelper2[\"default\"])(connectionKeys),\n _step3;\n try {\n var _loop = function _loop() {\n var key = _step3.value;\n var connection = ConnectionHandler.getConnection(recordProxy, key.key, key.filters);\n if (connection) {\n deleteIDs.forEach(function (deleteID) {\n ConnectionHandler.deleteNode(connection, deleteID);\n });\n }\n };\n for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {\n _loop();\n }\n } catch (err) {\n _iterator3.e(err);\n } finally {\n _iterator3.f();\n }\n}\nfunction getRootField(request) {\n if (request.fragment.selections && request.fragment.selections.length > 0 && request.fragment.selections[0].kind === 'LinkedField') {\n return request.fragment.selections[0].name;\n }\n return null;\n}\nmodule.exports = {\n MutationTypes: MutationTypes,\n RangeOperations: RangeOperations,\n convert: convert\n};","'use strict';\n\nvar _require = require('../store/ClientID'),\n generateClientID = _require.generateClientID;\nvar _require2 = require('../store/RelayStoreUtils'),\n getStableStorageKey = _require2.getStableStorageKey;\nvar invariant = require('invariant');\nvar RelayRecordProxy = /*#__PURE__*/function () {\n function RelayRecordProxy(source, mutator, dataID) {\n this._dataID = dataID;\n this._mutator = mutator;\n this._source = source;\n }\n var _proto = RelayRecordProxy.prototype;\n _proto.copyFieldsFrom = function copyFieldsFrom(source) {\n this._mutator.copyFields(source.getDataID(), this._dataID);\n };\n _proto.getDataID = function getDataID() {\n return this._dataID;\n };\n _proto.getType = function getType() {\n var type = this._mutator.getType(this._dataID);\n !(type != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayRecordProxy: Cannot get the type of deleted record `%s`.', this._dataID) : invariant(false) : void 0;\n return type;\n };\n _proto.getValue = function getValue(name, args) {\n var storageKey = getStableStorageKey(name, args);\n return this._mutator.getValue(this._dataID, storageKey);\n };\n _proto.setValue = function setValue(value, name, args) {\n !isValidLeafValue(value) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayRecordProxy#setValue(): Expected a scalar or array of scalars, ' + 'got `%s`.', JSON.stringify(value)) : invariant(false) : void 0;\n return this.setValue__UNSAFE(value, name, args);\n };\n _proto.setValue__UNSAFE = function setValue__UNSAFE(value, name, args) {\n var storageKey = getStableStorageKey(name, args);\n this._mutator.setValue(this._dataID, storageKey, value);\n return this;\n };\n _proto.getLinkedRecord = function getLinkedRecord(name, args) {\n var storageKey = getStableStorageKey(name, args);\n var linkedID = this._mutator.getLinkedRecordID(this._dataID, storageKey);\n return linkedID != null ? this._source.get(linkedID) : linkedID;\n };\n _proto.setLinkedRecord = function setLinkedRecord(record, name, args) {\n !(record instanceof RelayRecordProxy) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayRecordProxy#setLinkedRecord(): Expected a record, got `%s`.', record) : invariant(false) : void 0;\n var storageKey = getStableStorageKey(name, args);\n var linkedID = record.getDataID();\n this._mutator.setLinkedRecordID(this._dataID, storageKey, linkedID);\n return this;\n };\n _proto.getOrCreateLinkedRecord = function getOrCreateLinkedRecord(name, typeName, args) {\n var linkedRecord = this.getLinkedRecord(name, args);\n if (!linkedRecord) {\n var _this$_source$get;\n var storageKey = getStableStorageKey(name, args);\n var clientID = generateClientID(this.getDataID(), storageKey);\n linkedRecord = (_this$_source$get = this._source.get(clientID)) !== null && _this$_source$get !== void 0 ? _this$_source$get : this._source.create(clientID, typeName);\n this.setLinkedRecord(linkedRecord, name, args);\n }\n return linkedRecord;\n };\n _proto.getLinkedRecords = function getLinkedRecords(name, args) {\n var _this = this;\n var storageKey = getStableStorageKey(name, args);\n var linkedIDs = this._mutator.getLinkedRecordIDs(this._dataID, storageKey);\n if (linkedIDs == null) {\n return linkedIDs;\n }\n return linkedIDs.map(function (linkedID) {\n return linkedID != null ? _this._source.get(linkedID) : linkedID;\n });\n };\n _proto.setLinkedRecords = function setLinkedRecords(records, name, args) {\n !Array.isArray(records) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayRecordProxy#setLinkedRecords(): Expected records to be an array, got `%s`.', records) : invariant(false) : void 0;\n var storageKey = getStableStorageKey(name, args);\n var linkedIDs = records.map(function (record) {\n return record && record.getDataID();\n });\n this._mutator.setLinkedRecordIDs(this._dataID, storageKey, linkedIDs);\n return this;\n };\n _proto.invalidateRecord = function invalidateRecord() {\n this._source.markIDForInvalidation(this._dataID);\n };\n return RelayRecordProxy;\n}();\nfunction isValidLeafValue(value) {\n return value == null || typeof value !== 'object' || Array.isArray(value) && value.every(isValidLeafValue);\n}\nmodule.exports = RelayRecordProxy;","'use strict';\n\nvar RelayModernRecord = require('../store/RelayModernRecord');\nvar _require = require('../store/RelayRecordState'),\n EXISTENT = _require.EXISTENT;\nvar invariant = require('invariant');\nvar RelayRecordSourceMutator = /*#__PURE__*/function () {\n function RelayRecordSourceMutator(base, sink) {\n this.__sources = [sink, base];\n this._base = base;\n this._sink = sink;\n }\n var _proto = RelayRecordSourceMutator.prototype;\n _proto.unstable_getRawRecordWithChanges = function unstable_getRawRecordWithChanges(dataID) {\n var baseRecord = this._base.get(dataID);\n var sinkRecord = this._sink.get(dataID);\n if (sinkRecord === undefined) {\n if (baseRecord == null) {\n return baseRecord;\n }\n var nextRecord = RelayModernRecord.clone(baseRecord);\n if (process.env.NODE_ENV !== \"production\") {\n RelayModernRecord.freeze(nextRecord);\n }\n return nextRecord;\n } else if (sinkRecord === null) {\n return null;\n } else if (baseRecord != null) {\n var _nextRecord = RelayModernRecord.update(baseRecord, sinkRecord);\n if (process.env.NODE_ENV !== \"production\") {\n if (_nextRecord !== baseRecord) {\n RelayModernRecord.freeze(_nextRecord);\n }\n }\n return _nextRecord;\n } else {\n var _nextRecord2 = RelayModernRecord.clone(sinkRecord);\n if (process.env.NODE_ENV !== \"production\") {\n RelayModernRecord.freeze(_nextRecord2);\n }\n return _nextRecord2;\n }\n };\n _proto._getSinkRecord = function _getSinkRecord(dataID) {\n var sinkRecord = this._sink.get(dataID);\n if (!sinkRecord) {\n var baseRecord = this._base.get(dataID);\n !baseRecord ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayRecordSourceMutator: Cannot modify non-existent record `%s`.', dataID) : invariant(false) : void 0;\n sinkRecord = RelayModernRecord.create(dataID, RelayModernRecord.getType(baseRecord));\n this._sink.set(dataID, sinkRecord);\n }\n return sinkRecord;\n };\n _proto.copyFields = function copyFields(sourceID, sinkID) {\n var sinkSource = this._sink.get(sourceID);\n var baseSource = this._base.get(sourceID);\n !(sinkSource || baseSource) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayRecordSourceMutator#copyFields(): Cannot copy fields from ' + 'non-existent record `%s`.', sourceID) : invariant(false) : void 0;\n var sink = this._getSinkRecord(sinkID);\n if (baseSource) {\n RelayModernRecord.copyFields(baseSource, sink);\n }\n if (sinkSource) {\n RelayModernRecord.copyFields(sinkSource, sink);\n }\n };\n _proto.copyFieldsFromRecord = function copyFieldsFromRecord(record, sinkID) {\n var sink = this._getSinkRecord(sinkID);\n RelayModernRecord.copyFields(record, sink);\n };\n _proto.create = function create(dataID, typeName) {\n !(this._base.getStatus(dataID) !== EXISTENT && this._sink.getStatus(dataID) !== EXISTENT) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayRecordSourceMutator#create(): Cannot create a record with id ' + '`%s`, this record already exists.', dataID) : invariant(false) : void 0;\n var record = RelayModernRecord.create(dataID, typeName);\n this._sink.set(dataID, record);\n };\n _proto[\"delete\"] = function _delete(dataID) {\n this._sink[\"delete\"](dataID);\n };\n _proto.getStatus = function getStatus(dataID) {\n return this._sink.has(dataID) ? this._sink.getStatus(dataID) : this._base.getStatus(dataID);\n };\n _proto.getType = function getType(dataID) {\n for (var ii = 0; ii < this.__sources.length; ii++) {\n var record = this.__sources[ii].get(dataID);\n if (record) {\n return RelayModernRecord.getType(record);\n } else if (record === null) {\n return null;\n }\n }\n };\n _proto.getValue = function getValue(dataID, storageKey) {\n for (var ii = 0; ii < this.__sources.length; ii++) {\n var record = this.__sources[ii].get(dataID);\n if (record) {\n var value = RelayModernRecord.getValue(record, storageKey);\n if (value !== undefined) {\n return value;\n }\n } else if (record === null) {\n return null;\n }\n }\n };\n _proto.setValue = function setValue(dataID, storageKey, value) {\n var sinkRecord = this._getSinkRecord(dataID);\n RelayModernRecord.setValue(sinkRecord, storageKey, value);\n };\n _proto.getLinkedRecordID = function getLinkedRecordID(dataID, storageKey) {\n for (var ii = 0; ii < this.__sources.length; ii++) {\n var record = this.__sources[ii].get(dataID);\n if (record) {\n var linkedID = RelayModernRecord.getLinkedRecordID(record, storageKey);\n if (linkedID !== undefined) {\n return linkedID;\n }\n } else if (record === null) {\n return null;\n }\n }\n };\n _proto.setLinkedRecordID = function setLinkedRecordID(dataID, storageKey, linkedID) {\n var sinkRecord = this._getSinkRecord(dataID);\n RelayModernRecord.setLinkedRecordID(sinkRecord, storageKey, linkedID);\n };\n _proto.getLinkedRecordIDs = function getLinkedRecordIDs(dataID, storageKey) {\n for (var ii = 0; ii < this.__sources.length; ii++) {\n var record = this.__sources[ii].get(dataID);\n if (record) {\n var linkedIDs = RelayModernRecord.getLinkedRecordIDs(record, storageKey);\n if (linkedIDs !== undefined) {\n return linkedIDs;\n }\n } else if (record === null) {\n return null;\n }\n }\n };\n _proto.setLinkedRecordIDs = function setLinkedRecordIDs(dataID, storageKey, linkedIDs) {\n var sinkRecord = this._getSinkRecord(dataID);\n RelayModernRecord.setLinkedRecordIDs(sinkRecord, storageKey, linkedIDs);\n };\n return RelayRecordSourceMutator;\n}();\nmodule.exports = RelayRecordSourceMutator;","'use strict';\n\nvar RelayModernRecord = require('../store/RelayModernRecord');\nvar _require = require('../store/RelayRecordState'),\n EXISTENT = _require.EXISTENT,\n NONEXISTENT = _require.NONEXISTENT;\nvar _require2 = require('../store/RelayStoreUtils'),\n ROOT_ID = _require2.ROOT_ID,\n ROOT_TYPE = _require2.ROOT_TYPE;\nvar _require3 = require('./readUpdatableFragment'),\n _readUpdatableFragment = _require3.readUpdatableFragment;\nvar _require4 = require('./readUpdatableQuery'),\n _readUpdatableQuery = _require4.readUpdatableQuery;\nvar RelayRecordProxy = require('./RelayRecordProxy');\nvar invariant = require('invariant');\nvar RelayRecordSourceProxy = /*#__PURE__*/function () {\n function RelayRecordSourceProxy(mutator, getDataID, handlerProvider, missingFieldHandlers) {\n this.__mutator = mutator;\n this._handlerProvider = handlerProvider || null;\n this._proxies = {};\n this._getDataID = getDataID;\n this._invalidatedStore = false;\n this._idsMarkedForInvalidation = new Set();\n this._missingFieldHandlers = missingFieldHandlers;\n }\n var _proto = RelayRecordSourceProxy.prototype;\n _proto.publishSource = function publishSource(source, fieldPayloads) {\n var _this = this;\n var dataIDs = source.getRecordIDs();\n dataIDs.forEach(function (dataID) {\n var status = source.getStatus(dataID);\n if (status === EXISTENT) {\n var sourceRecord = source.get(dataID);\n if (sourceRecord) {\n if (_this.__mutator.getStatus(dataID) !== EXISTENT) {\n _this.create(dataID, RelayModernRecord.getType(sourceRecord));\n }\n _this.__mutator.copyFieldsFromRecord(sourceRecord, dataID);\n }\n } else if (status === NONEXISTENT) {\n _this[\"delete\"](dataID);\n }\n });\n if (fieldPayloads && fieldPayloads.length) {\n fieldPayloads.forEach(function (fieldPayload) {\n var handler = _this._handlerProvider && _this._handlerProvider(fieldPayload.handle);\n !handler ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayModernEnvironment: Expected a handler to be provided for handle `%s`.', fieldPayload.handle) : invariant(false) : void 0;\n handler.update(_this, fieldPayload);\n });\n }\n };\n _proto.create = function create(dataID, typeName) {\n this.__mutator.create(dataID, typeName);\n delete this._proxies[dataID];\n var record = this.get(dataID);\n !record ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayRecordSourceProxy#create(): Expected the created record to exist.') : invariant(false) : void 0;\n return record;\n };\n _proto[\"delete\"] = function _delete(dataID) {\n !(dataID !== ROOT_ID) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayRecordSourceProxy#delete(): Cannot delete the root record.') : invariant(false) : void 0;\n delete this._proxies[dataID];\n this.__mutator[\"delete\"](dataID);\n };\n _proto.get = function get(dataID) {\n if (!this._proxies.hasOwnProperty(dataID)) {\n var status = this.__mutator.getStatus(dataID);\n if (status === EXISTENT) {\n this._proxies[dataID] = new RelayRecordProxy(this, this.__mutator, dataID);\n } else {\n this._proxies[dataID] = status === NONEXISTENT ? null : undefined;\n }\n }\n return this._proxies[dataID];\n };\n _proto.getRoot = function getRoot() {\n var root = this.get(ROOT_ID);\n if (!root) {\n root = this.create(ROOT_ID, ROOT_TYPE);\n }\n !(root && root.getType() === ROOT_TYPE) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayRecordSourceProxy#getRoot(): Expected the source to contain a ' + 'root record, %s.', root == null ? 'no root record found' : \"found a root record of type `\".concat(root.getType(), \"`\")) : invariant(false) : void 0;\n return root;\n };\n _proto.invalidateStore = function invalidateStore() {\n this._invalidatedStore = true;\n };\n _proto.isStoreMarkedForInvalidation = function isStoreMarkedForInvalidation() {\n return this._invalidatedStore;\n };\n _proto.markIDForInvalidation = function markIDForInvalidation(dataID) {\n this._idsMarkedForInvalidation.add(dataID);\n };\n _proto.getIDsMarkedForInvalidation = function getIDsMarkedForInvalidation() {\n return this._idsMarkedForInvalidation;\n };\n _proto.readUpdatableQuery = function readUpdatableQuery(query, variables) {\n return _readUpdatableQuery(query, variables, this, this._missingFieldHandlers);\n };\n _proto.readUpdatableFragment = function readUpdatableFragment(fragment, fragmentReference) {\n return _readUpdatableFragment(fragment, fragmentReference, this, this._missingFieldHandlers);\n };\n return RelayRecordSourceProxy;\n}();\nmodule.exports = RelayRecordSourceProxy;","'use strict';\n\nvar _require = require('../store/RelayStoreUtils'),\n ROOT_TYPE = _require.ROOT_TYPE,\n getStorageKey = _require.getStorageKey;\nvar _require2 = require('./readUpdatableFragment'),\n _readUpdatableFragment = _require2.readUpdatableFragment;\nvar _require3 = require('./readUpdatableQuery'),\n _readUpdatableQuery = _require3.readUpdatableQuery;\nvar invariant = require('invariant');\nvar RelayRecordSourceSelectorProxy = /*#__PURE__*/function () {\n function RelayRecordSourceSelectorProxy(mutator, recordSource, readSelector, missingFieldHandlers) {\n this.__mutator = mutator;\n this.__recordSource = recordSource;\n this._readSelector = readSelector;\n this._missingFieldHandlers = missingFieldHandlers;\n }\n var _proto = RelayRecordSourceSelectorProxy.prototype;\n _proto.create = function create(dataID, typeName) {\n return this.__recordSource.create(dataID, typeName);\n };\n _proto[\"delete\"] = function _delete(dataID) {\n this.__recordSource[\"delete\"](dataID);\n };\n _proto.get = function get(dataID) {\n return this.__recordSource.get(dataID);\n };\n _proto.getRoot = function getRoot() {\n return this.__recordSource.getRoot();\n };\n _proto.getOperationRoot = function getOperationRoot() {\n var root = this.__recordSource.get(this._readSelector.dataID);\n if (!root) {\n root = this.__recordSource.create(this._readSelector.dataID, ROOT_TYPE);\n }\n return root;\n };\n _proto._getRootField = function _getRootField(selector, fieldName, plural) {\n var field = selector.node.selections.find(function (selection) {\n return selection.kind === 'LinkedField' && selection.name === fieldName || selection.kind === 'RequiredField' && selection.field.name === fieldName;\n });\n if (field && field.kind === 'RequiredField') {\n field = field.field;\n }\n !(field && field.kind === 'LinkedField') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayRecordSourceSelectorProxy#getRootField(): Cannot find root ' + 'field `%s`, no such field is defined on GraphQL document `%s`.', fieldName, selector.node.name) : invariant(false) : void 0;\n !(field.plural === plural) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayRecordSourceSelectorProxy#getRootField(): Expected root field ' + '`%s` to be %s.', fieldName, plural ? 'plural' : 'singular') : invariant(false) : void 0;\n return field;\n };\n _proto.getRootField = function getRootField(fieldName) {\n var field = this._getRootField(this._readSelector, fieldName, false);\n var storageKey = getStorageKey(field, this._readSelector.variables);\n return this.getOperationRoot().getLinkedRecord(storageKey);\n };\n _proto.getPluralRootField = function getPluralRootField(fieldName) {\n var field = this._getRootField(this._readSelector, fieldName, true);\n var storageKey = getStorageKey(field, this._readSelector.variables);\n return this.getOperationRoot().getLinkedRecords(storageKey);\n };\n _proto.invalidateStore = function invalidateStore() {\n this.__recordSource.invalidateStore();\n };\n _proto.readUpdatableQuery = function readUpdatableQuery(query, variables) {\n return _readUpdatableQuery(query, variables, this, this._missingFieldHandlers);\n };\n _proto.readUpdatableFragment = function readUpdatableFragment(fragment, fragmentReference) {\n return _readUpdatableFragment(fragment, fragmentReference, this, this._missingFieldHandlers);\n };\n return RelayRecordSourceSelectorProxy;\n}();\nmodule.exports = RelayRecordSourceSelectorProxy;","'use strict';\n\nvar _require = require('../query/GraphQLTag'),\n getRequest = _require.getRequest;\nvar isRelayModernEnvironment = require('../store/isRelayModernEnvironment');\nvar _require2 = require('../store/RelayModernOperationDescriptor'),\n createOperationDescriptor = _require2.createOperationDescriptor;\nvar RelayDeclarativeMutationConfig = require('./RelayDeclarativeMutationConfig');\nvar invariant = require('invariant');\nfunction applyOptimisticMutation(environment, config) {\n !isRelayModernEnvironment(environment) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'commitMutation: expected `environment` to be an instance of ' + '`RelayModernEnvironment`.') : invariant(false) : void 0;\n var mutation = getRequest(config.mutation);\n if (mutation.params.operationKind !== 'mutation') {\n throw new Error('commitMutation: Expected mutation operation');\n }\n var optimisticUpdater = config.optimisticUpdater;\n var configs = config.configs,\n optimisticResponse = config.optimisticResponse,\n variables = config.variables;\n var operation = createOperationDescriptor(mutation, variables);\n if (configs) {\n var _RelayDeclarativeMuta = RelayDeclarativeMutationConfig.convert(configs, mutation, optimisticUpdater);\n optimisticUpdater = _RelayDeclarativeMuta.optimisticUpdater;\n }\n return environment.applyMutation({\n operation: operation,\n response: optimisticResponse,\n updater: optimisticUpdater\n });\n}\nmodule.exports = applyOptimisticMutation;","'use strict';\n\nfunction commitLocalUpdate(environment, updater) {\n environment.commitUpdate(updater);\n}\nmodule.exports = commitLocalUpdate;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _toConsumableArray2 = _interopRequireDefault(require(\"@babel/runtime/helpers/toConsumableArray\"));\nvar _require = require('../query/GraphQLTag'),\n getRequest = _require.getRequest;\nvar _require2 = require('../store/ClientID'),\n generateUniqueClientID = _require2.generateUniqueClientID;\nvar isRelayModernEnvironment = require('../store/isRelayModernEnvironment');\nvar _require3 = require('../store/RelayModernOperationDescriptor'),\n createOperationDescriptor = _require3.createOperationDescriptor;\nvar RelayDeclarativeMutationConfig = require('./RelayDeclarativeMutationConfig');\nvar validateMutation = require('./validateMutation');\nvar invariant = require('invariant');\nvar warning = require(\"fbjs/lib/warning\");\nfunction commitMutation(environment, config) {\n !isRelayModernEnvironment(environment) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'commitMutation: expected `environment` to be an instance of ' + '`RelayModernEnvironment`.') : invariant(false) : void 0;\n var mutation = getRequest(config.mutation);\n if (mutation.params.operationKind !== 'mutation') {\n throw new Error('commitMutation: Expected mutation operation');\n }\n if (mutation.kind !== 'Request') {\n throw new Error('commitMutation: Expected mutation to be of type request');\n }\n var optimisticResponse = config.optimisticResponse,\n optimisticUpdater = config.optimisticUpdater,\n updater = config.updater;\n var configs = config.configs,\n cacheConfig = config.cacheConfig,\n onError = config.onError,\n onUnsubscribe = config.onUnsubscribe,\n variables = config.variables,\n uploadables = config.uploadables;\n var operation = createOperationDescriptor(mutation, variables, cacheConfig, generateUniqueClientID());\n if (typeof optimisticResponse === 'function') {\n optimisticResponse = optimisticResponse();\n process.env.NODE_ENV !== \"production\" ? warning(false, 'commitMutation: Expected `optimisticResponse` to be an object, ' + 'received a function.') : void 0;\n }\n if (process.env.NODE_ENV !== \"production\") {\n if (optimisticResponse instanceof Object) {\n validateMutation(optimisticResponse, mutation, variables);\n }\n }\n if (configs) {\n var _RelayDeclarativeMuta = RelayDeclarativeMutationConfig.convert(configs, mutation, optimisticUpdater, updater);\n optimisticUpdater = _RelayDeclarativeMuta.optimisticUpdater;\n updater = _RelayDeclarativeMuta.updater;\n }\n var errors = [];\n var subscription = environment.executeMutation({\n operation: operation,\n optimisticResponse: optimisticResponse,\n optimisticUpdater: optimisticUpdater,\n updater: updater,\n uploadables: uploadables\n }).subscribe({\n next: function next(payload) {\n var _config$onNext;\n if (Array.isArray(payload)) {\n payload.forEach(function (item) {\n if (item.errors) {\n errors.push.apply(errors, (0, _toConsumableArray2[\"default\"])(item.errors));\n }\n });\n } else {\n if (payload.errors) {\n errors.push.apply(errors, (0, _toConsumableArray2[\"default\"])(payload.errors));\n }\n }\n (_config$onNext = config.onNext) === null || _config$onNext === void 0 ? void 0 : _config$onNext.call(config);\n },\n complete: function complete() {\n var onCompleted = config.onCompleted;\n if (onCompleted) {\n var snapshot = environment.lookup(operation.fragment);\n onCompleted(snapshot.data, errors.length !== 0 ? errors : null);\n }\n },\n error: onError,\n unsubscribe: onUnsubscribe\n });\n return {\n dispose: subscription.unsubscribe\n };\n}\nmodule.exports = commitMutation;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _createForOfIteratorHelper2 = _interopRequireDefault(require(\"@babel/runtime/helpers/createForOfIteratorHelper\"));\nvar _require = require('../store/RelayStoreUtils'),\n getArgumentValues = _require.getArgumentValues;\nvar _require2 = require('../util/RelayConcreteNode'),\n ACTOR_CHANGE = _require2.ACTOR_CHANGE,\n ALIASED_FRAGMENT_SPREAD = _require2.ALIASED_FRAGMENT_SPREAD,\n ALIASED_INLINE_FRAGMENT_SPREAD = _require2.ALIASED_INLINE_FRAGMENT_SPREAD,\n CLIENT_EDGE_TO_CLIENT_OBJECT = _require2.CLIENT_EDGE_TO_CLIENT_OBJECT,\n CLIENT_EDGE_TO_SERVER_OBJECT = _require2.CLIENT_EDGE_TO_SERVER_OBJECT,\n CLIENT_EXTENSION = _require2.CLIENT_EXTENSION,\n CONDITION = _require2.CONDITION,\n DEFER = _require2.DEFER,\n FRAGMENT_SPREAD = _require2.FRAGMENT_SPREAD,\n INLINE_DATA_FRAGMENT_SPREAD = _require2.INLINE_DATA_FRAGMENT_SPREAD,\n INLINE_FRAGMENT = _require2.INLINE_FRAGMENT,\n LINKED_FIELD = _require2.LINKED_FIELD,\n MODULE_IMPORT = _require2.MODULE_IMPORT,\n RELAY_LIVE_RESOLVER = _require2.RELAY_LIVE_RESOLVER,\n RELAY_RESOLVER = _require2.RELAY_RESOLVER,\n REQUIRED_FIELD = _require2.REQUIRED_FIELD,\n SCALAR_FIELD = _require2.SCALAR_FIELD,\n STREAM = _require2.STREAM;\nvar nonUpdatableKeys = ['id', '__id', '__typename', 'js'];\nfunction createUpdatableProxy(updatableProxyRootRecord, variables, selections, recordSourceProxy, missingFieldHandlers) {\n var mutableUpdatableProxy = {};\n updateProxyFromSelections(mutableUpdatableProxy, updatableProxyRootRecord, variables, selections, recordSourceProxy, missingFieldHandlers);\n if (process.env.NODE_ENV !== \"production\") {\n Object.freeze(mutableUpdatableProxy);\n }\n return mutableUpdatableProxy;\n}\nfunction updateProxyFromSelections(mutableUpdatableProxy, updatableProxyRootRecord, variables, selections, recordSourceProxy, missingFieldHandlers) {\n var _selection$alias3;\n var _iterator = (0, _createForOfIteratorHelper2[\"default\"])(selections),\n _step;\n try {\n var _loop = function _loop() {\n var selection = _step.value;\n switch (selection.kind) {\n case LINKED_FIELD:\n if (selection.plural) {\n Object.defineProperty(mutableUpdatableProxy, (_selection$alias = selection.alias) !== null && _selection$alias !== void 0 ? _selection$alias : selection.name, {\n get: createGetterForPluralLinkedField(selection, variables, updatableProxyRootRecord, recordSourceProxy, missingFieldHandlers),\n set: createSetterForPluralLinkedField(selection, variables, updatableProxyRootRecord, recordSourceProxy)\n });\n } else {\n Object.defineProperty(mutableUpdatableProxy, (_selection$alias2 = selection.alias) !== null && _selection$alias2 !== void 0 ? _selection$alias2 : selection.name, {\n get: createGetterForSingularLinkedField(selection, variables, updatableProxyRootRecord, recordSourceProxy, missingFieldHandlers),\n set: createSetterForSingularLinkedField(selection, variables, updatableProxyRootRecord, recordSourceProxy)\n });\n }\n break;\n case SCALAR_FIELD:\n var scalarFieldName = (_selection$alias3 = selection.alias) !== null && _selection$alias3 !== void 0 ? _selection$alias3 : selection.name;\n Object.defineProperty(mutableUpdatableProxy, scalarFieldName, {\n get: function get() {\n var _selection$args;\n var newVariables = getArgumentValues((_selection$args = selection.args) !== null && _selection$args !== void 0 ? _selection$args : [], variables);\n var value = updatableProxyRootRecord.getValue(selection.name, newVariables);\n if (value == null) {\n value = getScalarUsingMissingFieldHandlers(selection, newVariables, updatableProxyRootRecord, recordSourceProxy, missingFieldHandlers);\n }\n return value;\n },\n set: nonUpdatableKeys.includes(selection.name) ? undefined : function (newValue) {\n var _selection$args2;\n var newVariables = getArgumentValues((_selection$args2 = selection.args) !== null && _selection$args2 !== void 0 ? _selection$args2 : [], variables);\n updatableProxyRootRecord.setValue__UNSAFE(newValue, selection.name, newVariables);\n }\n });\n break;\n case INLINE_FRAGMENT:\n if (updatableProxyRootRecord.getType() === selection.type) {\n updateProxyFromSelections(mutableUpdatableProxy, updatableProxyRootRecord, variables, selection.selections, recordSourceProxy, missingFieldHandlers);\n }\n break;\n case CLIENT_EXTENSION:\n updateProxyFromSelections(mutableUpdatableProxy, updatableProxyRootRecord, variables, selection.selections, recordSourceProxy, missingFieldHandlers);\n break;\n case FRAGMENT_SPREAD:\n break;\n case CONDITION:\n case ACTOR_CHANGE:\n case ALIASED_FRAGMENT_SPREAD:\n case INLINE_DATA_FRAGMENT_SPREAD:\n case ALIASED_INLINE_FRAGMENT_SPREAD:\n case CLIENT_EDGE_TO_CLIENT_OBJECT:\n case CLIENT_EDGE_TO_SERVER_OBJECT:\n case DEFER:\n case MODULE_IMPORT:\n case RELAY_LIVE_RESOLVER:\n case REQUIRED_FIELD:\n case STREAM:\n case RELAY_RESOLVER:\n throw new Error('Encountered an unexpected ReaderSelection variant in RelayRecordSourceProxy. This indicates a bug in Relay.');\n default:\n selection.kind;\n throw new Error('Encountered an unexpected ReaderSelection variant in RelayRecordSourceProxy. This indicates a bug in Relay.');\n }\n };\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var _selection$alias;\n var _selection$alias2;\n _loop();\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n}\nfunction createSetterForPluralLinkedField(selection, variables, updatableProxyRootRecord, recordSourceProxy) {\n return function set(newValue) {\n var _selection$args3;\n var newVariables = getArgumentValues((_selection$args3 = selection.args) !== null && _selection$args3 !== void 0 ? _selection$args3 : [], variables);\n if (newValue == null) {\n throw new Error('Do not assign null to plural linked fields; assign an empty array instead.');\n } else {\n var recordProxies = newValue.map(function (item) {\n if (item == null) {\n throw new Error('When assigning an array of items, none of the items should be null or undefined.');\n }\n var __id = item.__id;\n if (__id == null) {\n throw new Error('The __id field must be present on each item passed to the setter. This indicates a bug in Relay.');\n }\n var newValueRecord = recordSourceProxy.get(__id);\n if (newValueRecord == null) {\n throw new Error(\"Did not find item with data id \".concat(__id, \" in the store.\"));\n }\n return newValueRecord;\n });\n updatableProxyRootRecord.setLinkedRecords(recordProxies, selection.name, newVariables);\n }\n };\n}\nfunction createSetterForSingularLinkedField(selection, variables, updatableProxyRootRecord, recordSourceProxy) {\n return function set(newValue) {\n var _selection$args4;\n var newVariables = getArgumentValues((_selection$args4 = selection.args) !== null && _selection$args4 !== void 0 ? _selection$args4 : [], variables);\n if (newValue == null) {\n updatableProxyRootRecord.setValue(newValue, selection.name, newVariables);\n } else {\n var __id = newValue.__id;\n if (__id == null) {\n throw new Error('The __id field must be present on the argument. This indicates a bug in Relay.');\n }\n var newValueRecord = recordSourceProxy.get(__id);\n if (newValueRecord == null) {\n throw new Error(\"Did not find item with data id \".concat(__id, \" in the store.\"));\n }\n updatableProxyRootRecord.setLinkedRecord(newValueRecord, selection.name, newVariables);\n }\n };\n}\nfunction createGetterForPluralLinkedField(selection, variables, updatableProxyRootRecord, recordSourceProxy, missingFieldHandlers) {\n return function () {\n var _selection$args5;\n var newVariables = getArgumentValues((_selection$args5 = selection.args) !== null && _selection$args5 !== void 0 ? _selection$args5 : [], variables);\n var linkedRecords = updatableProxyRootRecord.getLinkedRecords(selection.name, newVariables);\n if (linkedRecords === undefined) {\n linkedRecords = getPluralLinkedRecordUsingMissingFieldHandlers(selection, newVariables, updatableProxyRootRecord, recordSourceProxy, missingFieldHandlers);\n }\n if (linkedRecords != null) {\n return linkedRecords.map(function (linkedRecord) {\n if (linkedRecord != null) {\n var updatableProxy = {};\n updateProxyFromSelections(updatableProxy, linkedRecord, variables, selection.selections, recordSourceProxy, missingFieldHandlers);\n if (process.env.NODE_ENV !== \"production\") {\n Object.freeze(updatableProxy);\n }\n return updatableProxy;\n } else {\n return linkedRecord;\n }\n });\n } else {\n return linkedRecords;\n }\n };\n}\nfunction createGetterForSingularLinkedField(selection, variables, updatableProxyRootRecord, recordSourceProxy, missingFieldHandlers) {\n return function () {\n var _selection$args6;\n var newVariables = getArgumentValues((_selection$args6 = selection.args) !== null && _selection$args6 !== void 0 ? _selection$args6 : [], variables);\n var linkedRecord = updatableProxyRootRecord.getLinkedRecord(selection.name, newVariables);\n if (linkedRecord === undefined) {\n linkedRecord = getLinkedRecordUsingMissingFieldHandlers(selection, newVariables, updatableProxyRootRecord, recordSourceProxy, missingFieldHandlers);\n }\n if (linkedRecord != null) {\n var updatableProxy = {};\n updateProxyFromSelections(updatableProxy, linkedRecord, variables, selection.selections, recordSourceProxy, missingFieldHandlers);\n if (process.env.NODE_ENV !== \"production\") {\n Object.freeze(updatableProxy);\n }\n return updatableProxy;\n } else {\n return linkedRecord;\n }\n };\n}\nfunction getLinkedRecordUsingMissingFieldHandlers(selection, newVariables, updatableProxyRootRecord, recordSourceProxy, missingFieldHandlers) {\n var _iterator2 = (0, _createForOfIteratorHelper2[\"default\"])(missingFieldHandlers),\n _step2;\n try {\n for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n var handler = _step2.value;\n if (handler.kind === 'linked') {\n var newId = handler.handle(selection, updatableProxyRootRecord, newVariables, recordSourceProxy);\n if (newId != null) {\n return recordSourceProxy.get(newId);\n }\n }\n }\n } catch (err) {\n _iterator2.e(err);\n } finally {\n _iterator2.f();\n }\n}\nfunction getPluralLinkedRecordUsingMissingFieldHandlers(selection, newVariables, updatableProxyRootRecord, recordSourceProxy, missingFieldHandlers) {\n var _iterator3 = (0, _createForOfIteratorHelper2[\"default\"])(missingFieldHandlers),\n _step3;\n try {\n for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {\n var handler = _step3.value;\n if (handler.kind === 'pluralLinked') {\n var newIds = handler.handle(selection, updatableProxyRootRecord, newVariables, recordSourceProxy);\n if (newIds != null) {\n return newIds.map(function (newId) {\n if (newId != null) {\n return recordSourceProxy.get(newId);\n }\n });\n }\n }\n }\n } catch (err) {\n _iterator3.e(err);\n } finally {\n _iterator3.f();\n }\n}\nfunction getScalarUsingMissingFieldHandlers(selection, newVariables, updatableProxyRootRecord, recordSourceProxy, missingFieldHandlers) {\n var _iterator4 = (0, _createForOfIteratorHelper2[\"default\"])(missingFieldHandlers),\n _step4;\n try {\n for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {\n var handler = _step4.value;\n if (handler.kind === 'scalar') {\n var value = handler.handle(selection, updatableProxyRootRecord, newVariables, recordSourceProxy);\n if (value !== undefined) {\n return value;\n }\n }\n }\n } catch (err) {\n _iterator4.e(err);\n } finally {\n _iterator4.f();\n }\n}\nmodule.exports = {\n createUpdatableProxy: createUpdatableProxy\n};","'use strict';\n\nvar _require = require('../query/GraphQLTag'),\n getFragment = _require.getFragment;\nvar _require2 = require('../store/RelayModernSelector'),\n getVariablesFromFragment = _require2.getVariablesFromFragment;\nvar _require3 = require('../store/RelayStoreUtils'),\n ID_KEY = _require3.ID_KEY;\nvar _require4 = require('./createUpdatableProxy'),\n createUpdatableProxy = _require4.createUpdatableProxy;\nvar invariant = require('invariant');\nfunction readUpdatableFragment(fragment, fragmentReference, proxy, missingFieldHandlers) {\n var updatableFragment = getFragment(fragment);\n var fragmentVariables = getVariablesFromFragment(updatableFragment, fragmentReference);\n var id = fragmentReference[ID_KEY];\n var fragmentRoot = proxy.get(id);\n !(fragmentRoot != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, \"No record with \".concat(id, \" was found. This likely indicates a problem with Relay.\")) : invariant(false) : void 0;\n return {\n updatableData: createUpdatableProxy(fragmentRoot, fragmentVariables, updatableFragment.selections, proxy, missingFieldHandlers)\n };\n}\nmodule.exports = {\n readUpdatableFragment: readUpdatableFragment\n};","'use strict';\n\nvar _require = require('../query/GraphQLTag'),\n getUpdatableQuery = _require.getUpdatableQuery;\nvar _require2 = require('./createUpdatableProxy'),\n createUpdatableProxy = _require2.createUpdatableProxy;\nfunction readUpdatableQuery(query, variables, proxy, missingFieldHandlers) {\n var updatableQuery = getUpdatableQuery(query);\n return {\n updatableData: createUpdatableProxy(proxy.getRoot(), variables, updatableQuery.fragment.selections, proxy, missingFieldHandlers)\n };\n}\nmodule.exports = {\n readUpdatableQuery: readUpdatableQuery\n};","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _objectSpread2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar _require = require('../util/RelayConcreteNode'),\n ACTOR_CHANGE = _require.ACTOR_CHANGE,\n CLIENT_COMPONENT = _require.CLIENT_COMPONENT,\n CLIENT_EDGE_TO_CLIENT_OBJECT = _require.CLIENT_EDGE_TO_CLIENT_OBJECT,\n CLIENT_EXTENSION = _require.CLIENT_EXTENSION,\n CONDITION = _require.CONDITION,\n DEFER = _require.DEFER,\n FRAGMENT_SPREAD = _require.FRAGMENT_SPREAD,\n INLINE_FRAGMENT = _require.INLINE_FRAGMENT,\n LINKED_FIELD = _require.LINKED_FIELD,\n LINKED_HANDLE = _require.LINKED_HANDLE,\n MODULE_IMPORT = _require.MODULE_IMPORT,\n RELAY_LIVE_RESOLVER = _require.RELAY_LIVE_RESOLVER,\n RELAY_RESOLVER = _require.RELAY_RESOLVER,\n SCALAR_FIELD = _require.SCALAR_FIELD,\n SCALAR_HANDLE = _require.SCALAR_HANDLE,\n STREAM = _require.STREAM,\n TYPE_DISCRIMINATOR = _require.TYPE_DISCRIMINATOR;\nvar warning = require(\"fbjs/lib/warning\");\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar validateMutation = function validateMutation() {};\nif (process.env.NODE_ENV !== \"production\") {\n var addFieldToDiff = function addFieldToDiff(path, diff, isScalar) {\n var deepLoc = diff;\n path.split('.').forEach(function (key, index, arr) {\n if (deepLoc[key] == null) {\n deepLoc[key] = {};\n }\n if (isScalar && index === arr.length - 1) {\n deepLoc[key] = '';\n }\n deepLoc = deepLoc[key];\n });\n };\n validateMutation = function validateMutation(optimisticResponse, mutation, variables) {\n var operationName = mutation.operation.name;\n var context = {\n path: 'ROOT',\n visitedPaths: new Set(),\n variables: variables || {},\n missingDiff: {},\n extraDiff: {},\n moduleImportPaths: new Set()\n };\n validateSelections(optimisticResponse, mutation.operation.selections, context);\n validateOptimisticResponse(optimisticResponse, context);\n process.env.NODE_ENV !== \"production\" ? warning(context.missingDiff.ROOT == null, 'Expected `optimisticResponse` to match structure of server response for mutation `%s`, please define fields for all of\\n%s', operationName, JSON.stringify(context.missingDiff.ROOT, null, 2)) : void 0;\n process.env.NODE_ENV !== \"production\" ? warning(context.extraDiff.ROOT == null, 'Expected `optimisticResponse` to match structure of server response for mutation `%s`, please remove all fields of\\n%s', operationName, JSON.stringify(context.extraDiff.ROOT, null, 2)) : void 0;\n };\n var validateSelections = function validateSelections(optimisticResponse, selections, context) {\n selections.forEach(function (selection) {\n return validateSelection(optimisticResponse, selection, context);\n });\n };\n var validateSelection = function validateSelection(optimisticResponse, selection, context) {\n switch (selection.kind) {\n case CONDITION:\n validateSelections(optimisticResponse, selection.selections, context);\n return;\n case CLIENT_COMPONENT:\n case FRAGMENT_SPREAD:\n validateSelections(optimisticResponse, selection.fragment.selections, context);\n return;\n case SCALAR_FIELD:\n case LINKED_FIELD:\n return validateField(optimisticResponse, selection, context);\n case ACTOR_CHANGE:\n return validateField(optimisticResponse, selection.linkedField, context);\n case INLINE_FRAGMENT:\n var type = selection.type;\n var isConcreteType = selection.abstractKey == null;\n validateAbstractKey(context, selection.abstractKey);\n selection.selections.forEach(function (subselection) {\n if (isConcreteType && optimisticResponse.__typename !== type) {\n return;\n }\n validateSelection(optimisticResponse, subselection, context);\n });\n return;\n case CLIENT_EXTENSION:\n selection.selections.forEach(function (subselection) {\n validateSelection(optimisticResponse, subselection, context);\n });\n return;\n case MODULE_IMPORT:\n return validateModuleImport(context);\n case TYPE_DISCRIMINATOR:\n return validateAbstractKey(context, selection.abstractKey);\n case RELAY_RESOLVER:\n case RELAY_LIVE_RESOLVER:\n case CLIENT_EDGE_TO_CLIENT_OBJECT:\n case LINKED_HANDLE:\n case SCALAR_HANDLE:\n case DEFER:\n case STREAM:\n {\n return;\n }\n default:\n selection;\n return;\n }\n };\n var validateModuleImport = function validateModuleImport(context) {\n context.moduleImportPaths.add(context.path);\n };\n var validateAbstractKey = function validateAbstractKey(context, abstractKey) {\n if (abstractKey != null) {\n var path = \"\".concat(context.path, \".\").concat(abstractKey);\n context.visitedPaths.add(path);\n }\n };\n var validateField = function validateField(optimisticResponse, field, context) {\n var fieldName = field.alias || field.name;\n var path = \"\".concat(context.path, \".\").concat(fieldName);\n context.visitedPaths.add(path);\n switch (field.kind) {\n case SCALAR_FIELD:\n if (hasOwnProperty.call(optimisticResponse, fieldName) === false) {\n addFieldToDiff(path, context.missingDiff, true);\n }\n return;\n case LINKED_FIELD:\n var selections = field.selections;\n if (optimisticResponse[fieldName] === null || hasOwnProperty.call(optimisticResponse, fieldName) && optimisticResponse[fieldName] === undefined) {\n return;\n }\n if (field.plural) {\n if (Array.isArray(optimisticResponse[fieldName])) {\n optimisticResponse[fieldName].forEach(function (r) {\n if (r !== null) {\n validateSelections(r, selections, (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, context), {}, {\n path: path\n }));\n }\n });\n return;\n } else {\n addFieldToDiff(path, context.missingDiff);\n return;\n }\n } else {\n if (optimisticResponse[fieldName] instanceof Object) {\n validateSelections(optimisticResponse[fieldName], selections, (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, context), {}, {\n path: path\n }));\n return;\n } else {\n addFieldToDiff(path, context.missingDiff);\n return;\n }\n }\n }\n };\n var validateOptimisticResponse = function validateOptimisticResponse(optimisticResponse, context) {\n if (Array.isArray(optimisticResponse)) {\n optimisticResponse.forEach(function (r) {\n if (r instanceof Object) {\n validateOptimisticResponse(r, context);\n }\n });\n return;\n }\n Object.keys(optimisticResponse).forEach(function (key) {\n var value = optimisticResponse[key];\n var path = \"\".concat(context.path, \".\").concat(key);\n if (context.moduleImportPaths.has(path)) {\n return;\n }\n if (!context.visitedPaths.has(path)) {\n addFieldToDiff(path, context.extraDiff);\n return;\n }\n if (value instanceof Object) {\n validateOptimisticResponse(value, (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, context), {}, {\n path: path\n }));\n }\n });\n };\n}\nmodule.exports = validateMutation;","'use strict';\n\nvar RelayObservable = require('./RelayObservable');\nfunction convertFetch(fn) {\n return function fetch(request, variables, cacheConfig, uploadables, logRequestInfo) {\n var result = fn(request, variables, cacheConfig, uploadables, logRequestInfo);\n if (result instanceof Error) {\n return RelayObservable.create(function (sink) {\n return sink.error(result);\n });\n }\n return RelayObservable.from(result);\n };\n}\nmodule.exports = {\n convertFetch: convertFetch\n};","'use strict';\n\nvar withProvidedVariables = require('../util/withProvidedVariables');\nvar _require = require('./ConvertToExecuteFunction'),\n convertFetch = _require.convertFetch;\nvar invariant = require('invariant');\nfunction create(fetchFn, subscribe) {\n var observeFetch = convertFetch(fetchFn);\n function execute(request, variables, cacheConfig, uploadables, logRequestInfo) {\n var operationVariables = withProvidedVariables(variables, request.providedVariables);\n if (request.operationKind === 'subscription') {\n !subscribe ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayNetwork: This network layer does not support Subscriptions. ' + 'To use Subscriptions, provide a custom network layer.') : invariant(false) : void 0;\n !!uploadables ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayNetwork: Cannot provide uploadables while subscribing.') : invariant(false) : void 0;\n return subscribe(request, operationVariables, cacheConfig);\n }\n var pollInterval = cacheConfig.poll;\n if (pollInterval != null) {\n !!uploadables ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayNetwork: Cannot provide uploadables while polling.') : invariant(false) : void 0;\n return observeFetch(request, operationVariables, {\n force: true\n }).poll(pollInterval);\n }\n return observeFetch(request, operationVariables, cacheConfig, uploadables, logRequestInfo);\n }\n return {\n execute: execute\n };\n}\nmodule.exports = {\n create: create\n};","'use strict';\n\nvar isPromise = require('../util/isPromise');\nvar hostReportError = swallowError;\nvar RelayObservable = /*#__PURE__*/function () {\n RelayObservable.create = function create(source) {\n return new RelayObservable(source);\n };\n function RelayObservable(source) {\n if (process.env.NODE_ENV !== \"production\") {\n if (!source || typeof source !== 'function') {\n throw new Error('Source must be a Function: ' + String(source));\n }\n }\n this._source = source;\n }\n RelayObservable.onUnhandledError = function onUnhandledError(callback) {\n hostReportError = callback;\n };\n RelayObservable.from = function from(obj) {\n return isObservable(obj) ? fromObservable(obj) : isPromise(obj) ? fromPromise(obj) : fromValue(obj);\n };\n var _proto = RelayObservable.prototype;\n _proto[\"catch\"] = function _catch(fn) {\n var _this = this;\n return RelayObservable.create(function (sink) {\n var subscription;\n _this.subscribe({\n start: function start(sub) {\n subscription = sub;\n },\n next: sink.next,\n complete: sink.complete,\n error: function error(_error2) {\n try {\n fn(_error2).subscribe({\n start: function start(sub) {\n subscription = sub;\n },\n next: sink.next,\n complete: sink.complete,\n error: sink.error\n });\n } catch (error2) {\n sink.error(error2, true);\n }\n }\n });\n return function () {\n return subscription.unsubscribe();\n };\n });\n };\n _proto.concat = function concat(next) {\n var _this2 = this;\n return RelayObservable.create(function (sink) {\n var current;\n _this2.subscribe({\n start: function start(subscription) {\n current = subscription;\n },\n next: sink.next,\n error: sink.error,\n complete: function complete() {\n current = next.subscribe(sink);\n }\n });\n return function () {\n current && current.unsubscribe();\n };\n });\n };\n _proto[\"do\"] = function _do(observer) {\n var _this3 = this;\n return RelayObservable.create(function (sink) {\n var both = function both(action) {\n return function () {\n try {\n observer[action] && observer[action].apply(observer, arguments);\n } catch (error) {\n hostReportError(error, true);\n }\n sink[action] && sink[action].apply(sink, arguments);\n };\n };\n return _this3.subscribe({\n start: both('start'),\n next: both('next'),\n error: both('error'),\n complete: both('complete'),\n unsubscribe: both('unsubscribe')\n });\n });\n };\n _proto[\"finally\"] = function _finally(fn) {\n var _this4 = this;\n return RelayObservable.create(function (sink) {\n var subscription = _this4.subscribe(sink);\n return function () {\n subscription.unsubscribe();\n fn();\n };\n });\n };\n _proto.ifEmpty = function ifEmpty(alternate) {\n var _this5 = this;\n return RelayObservable.create(function (sink) {\n var hasValue = false;\n var current;\n current = _this5.subscribe({\n next: function next(value) {\n hasValue = true;\n sink.next(value);\n },\n error: sink.error,\n complete: function complete() {\n if (hasValue) {\n sink.complete();\n } else {\n current = alternate.subscribe(sink);\n }\n }\n });\n return function () {\n current && current.unsubscribe();\n };\n });\n };\n _proto.subscribe = function subscribe(observer) {\n if (process.env.NODE_ENV !== \"production\") {\n if (!observer || typeof observer !== 'object') {\n throw new Error('Observer must be an Object with callbacks: ' + String(observer));\n }\n }\n return _subscribe(this._source, observer);\n };\n _proto.map = function map(fn) {\n var _this6 = this;\n return RelayObservable.create(function (sink) {\n var subscription = _this6.subscribe({\n complete: sink.complete,\n error: sink.error,\n next: function next(value) {\n try {\n var mapValue = fn(value);\n sink.next(mapValue);\n } catch (error) {\n sink.error(error, true);\n }\n }\n });\n return function () {\n subscription.unsubscribe();\n };\n });\n };\n _proto.mergeMap = function mergeMap(fn) {\n var _this7 = this;\n return RelayObservable.create(function (sink) {\n var subscriptions = [];\n function start(subscription) {\n this._sub = subscription;\n subscriptions.push(subscription);\n }\n function complete() {\n subscriptions.splice(subscriptions.indexOf(this._sub), 1);\n if (subscriptions.length === 0) {\n sink.complete();\n }\n }\n _this7.subscribe({\n start: start,\n next: function next(value) {\n try {\n if (!sink.closed) {\n RelayObservable.from(fn(value)).subscribe({\n start: start,\n next: sink.next,\n error: sink.error,\n complete: complete\n });\n }\n } catch (error) {\n sink.error(error, true);\n }\n },\n error: sink.error,\n complete: complete\n });\n return function () {\n subscriptions.forEach(function (sub) {\n return sub.unsubscribe();\n });\n subscriptions.length = 0;\n };\n });\n };\n _proto.poll = function poll(pollInterval) {\n var _this8 = this;\n if (process.env.NODE_ENV !== \"production\") {\n if (typeof pollInterval !== 'number' || pollInterval <= 0) {\n throw new Error('RelayObservable: Expected pollInterval to be positive, got: ' + pollInterval);\n }\n }\n return RelayObservable.create(function (sink) {\n var subscription;\n var timeout;\n var poll = function poll() {\n subscription = _this8.subscribe({\n next: sink.next,\n error: sink.error,\n complete: function complete() {\n timeout = setTimeout(poll, pollInterval);\n }\n });\n };\n poll();\n return function () {\n clearTimeout(timeout);\n subscription.unsubscribe();\n };\n });\n };\n _proto.toPromise = function toPromise() {\n var _this9 = this;\n return new Promise(function (resolve, reject) {\n var resolved = false;\n _this9.subscribe({\n next: function next(val) {\n if (!resolved) {\n resolved = true;\n resolve(val);\n }\n },\n error: reject,\n complete: resolve\n });\n });\n };\n return RelayObservable;\n}();\nfunction isObservable(obj) {\n return typeof obj === 'object' && obj !== null && typeof obj.subscribe === 'function';\n}\nfunction fromObservable(obj) {\n return obj instanceof RelayObservable ? obj : RelayObservable.create(function (sink) {\n return obj.subscribe(sink);\n });\n}\nfunction fromPromise(promise) {\n return RelayObservable.create(function (sink) {\n promise.then(function (value) {\n sink.next(value);\n sink.complete();\n }, sink.error);\n });\n}\nfunction fromValue(value) {\n return RelayObservable.create(function (sink) {\n sink.next(value);\n sink.complete();\n });\n}\nfunction _subscribe(source, observer) {\n var closed = false;\n var cleanup;\n var withClosed = function withClosed(obj) {\n return Object.defineProperty(obj, 'closed', {\n get: function get() {\n return closed;\n }\n });\n };\n function doCleanup() {\n if (cleanup) {\n if (cleanup.unsubscribe) {\n cleanup.unsubscribe();\n } else {\n try {\n cleanup();\n } catch (error) {\n hostReportError(error, true);\n }\n }\n cleanup = undefined;\n }\n }\n var subscription = withClosed({\n unsubscribe: function unsubscribe() {\n if (!closed) {\n closed = true;\n try {\n observer.unsubscribe && observer.unsubscribe(subscription);\n } catch (error) {\n hostReportError(error, true);\n } finally {\n doCleanup();\n }\n }\n }\n });\n try {\n observer.start && observer.start(subscription);\n } catch (error) {\n hostReportError(error, true);\n }\n if (closed) {\n return subscription;\n }\n var sink = withClosed({\n next: function next(value) {\n if (!closed && observer.next) {\n try {\n observer.next(value);\n } catch (error) {\n hostReportError(error, true);\n }\n }\n },\n error: function error(_error3, isUncaughtThrownError) {\n if (closed || !observer.error) {\n closed = true;\n hostReportError(_error3, isUncaughtThrownError || false);\n doCleanup();\n } else {\n closed = true;\n try {\n observer.error(_error3);\n } catch (error2) {\n hostReportError(error2, true);\n } finally {\n doCleanup();\n }\n }\n },\n complete: function complete() {\n if (!closed) {\n closed = true;\n try {\n observer.complete && observer.complete();\n } catch (error) {\n hostReportError(error, true);\n } finally {\n doCleanup();\n }\n }\n }\n });\n try {\n cleanup = source(sink);\n } catch (error) {\n sink.error(error, true);\n }\n if (process.env.NODE_ENV !== \"production\") {\n if (cleanup !== undefined && typeof cleanup !== 'function' && (!cleanup || typeof cleanup.unsubscribe !== 'function')) {\n throw new Error('Returned cleanup function which cannot be called: ' + String(cleanup));\n }\n }\n if (closed) {\n doCleanup();\n }\n return subscription;\n}\nfunction swallowError(_error, _isUncaughtThrownError) {}\nif (process.env.NODE_ENV !== \"production\") {\n RelayObservable.onUnhandledError(function (error, isUncaughtThrownError) {\n if (typeof fail === 'function') {\n fail(String(error));\n } else if (isUncaughtThrownError) {\n setTimeout(function () {\n throw error;\n });\n } else if (typeof console !== 'undefined') {\n console.error('RelayObservable: Unhandled Error', error);\n }\n });\n}\nmodule.exports = RelayObservable;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _objectSpread2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar stableCopy = require('../util/stableCopy');\nvar invariant = require('invariant');\nvar RelayQueryResponseCache = /*#__PURE__*/function () {\n function RelayQueryResponseCache(_ref) {\n var size = _ref.size,\n ttl = _ref.ttl;\n !(size > 0) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayQueryResponseCache: Expected the max cache size to be > 0, got ' + '`%s`.', size) : invariant(false) : void 0;\n !(ttl > 0) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayQueryResponseCache: Expected the max ttl to be > 0, got `%s`.', ttl) : invariant(false) : void 0;\n this._responses = new Map();\n this._size = size;\n this._ttl = ttl;\n }\n var _proto = RelayQueryResponseCache.prototype;\n _proto.clear = function clear() {\n this._responses.clear();\n };\n _proto.get = function get(queryID, variables) {\n var _this = this;\n var cacheKey = getCacheKey(queryID, variables);\n this._responses.forEach(function (response, key) {\n if (!isCurrent(response.fetchTime, _this._ttl)) {\n _this._responses[\"delete\"](key);\n }\n });\n var response = this._responses.get(cacheKey);\n if (response == null) {\n return null;\n }\n if (Array.isArray(response.payload)) {\n return response.payload.map(function (payload) {\n return (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, payload), {}, {\n extensions: (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, payload.extensions), {}, {\n cacheTimestamp: response.fetchTime\n })\n });\n });\n }\n return (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, response.payload), {}, {\n extensions: (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, response.payload.extensions), {}, {\n cacheTimestamp: response.fetchTime\n })\n });\n };\n _proto.set = function set(queryID, variables, payload) {\n var fetchTime = Date.now();\n var cacheKey = getCacheKey(queryID, variables);\n this._responses[\"delete\"](cacheKey);\n this._responses.set(cacheKey, {\n fetchTime: fetchTime,\n payload: payload\n });\n if (this._responses.size > this._size) {\n var firstKey = this._responses.keys().next();\n if (!firstKey.done) {\n this._responses[\"delete\"](firstKey.value);\n }\n }\n };\n return RelayQueryResponseCache;\n}();\nfunction getCacheKey(queryID, variables) {\n return JSON.stringify(stableCopy({\n queryID: queryID,\n variables: variables\n }));\n}\nfunction isCurrent(fetchTime, ttl) {\n return fetchTime + ttl >= Date.now();\n}\nmodule.exports = RelayQueryResponseCache;","'use strict';\n\nvar generateID = require('../util/generateID');\nfunction wrapNetworkWithLogObserver(env, network) {\n return {\n execute: function execute(params, variables, cacheConfig, uploadables) {\n var networkRequestId = generateID();\n var logObserver = {\n start: function start(subscription) {\n env.__log({\n name: 'network.start',\n networkRequestId: networkRequestId,\n params: params,\n variables: variables,\n cacheConfig: cacheConfig\n });\n },\n next: function next(response) {\n env.__log({\n name: 'network.next',\n networkRequestId: networkRequestId,\n response: response\n });\n },\n error: function error(_error) {\n env.__log({\n name: 'network.error',\n networkRequestId: networkRequestId,\n error: _error\n });\n },\n complete: function complete() {\n env.__log({\n name: 'network.complete',\n networkRequestId: networkRequestId\n });\n },\n unsubscribe: function unsubscribe() {\n env.__log({\n name: 'network.unsubscribe',\n networkRequestId: networkRequestId\n });\n }\n };\n var logRequestInfo = function logRequestInfo(info) {\n env.__log({\n name: 'network.info',\n networkRequestId: networkRequestId,\n info: info\n });\n };\n return network.execute(params, variables, cacheConfig, uploadables, logRequestInfo)[\"do\"](logObserver);\n }\n };\n}\nmodule.exports = wrapNetworkWithLogObserver;","'use strict';\n\nvar RelayConcreteNode = require('../util/RelayConcreteNode');\nvar invariant = require('invariant');\nvar warning = require(\"fbjs/lib/warning\");\nfunction graphql(strings) {\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'graphql: Unexpected invocation at runtime. Either the Babel transform ' + 'was not set up, or it failed to identify this call site. Make sure it ' + 'is being used verbatim as `graphql`. Note also that there cannot be ' + 'a space between graphql and the backtick that follows.') : invariant(false) : void 0;\n}\nfunction getNode(taggedNode) {\n var node = taggedNode;\n if (typeof node === 'function') {\n node = node();\n process.env.NODE_ENV !== \"production\" ? warning(false, 'RelayGraphQLTag: node `%s` unexpectedly wrapped in a function.', node.kind === 'Fragment' ? node.name : node.operation.name) : void 0;\n } else if (node[\"default\"]) {\n node = node[\"default\"];\n }\n return node;\n}\nfunction isFragment(node) {\n var fragment = getNode(node);\n return typeof fragment === 'object' && fragment !== null && fragment.kind === RelayConcreteNode.FRAGMENT;\n}\nfunction isRequest(node) {\n var request = getNode(node);\n return typeof request === 'object' && request !== null && request.kind === RelayConcreteNode.REQUEST;\n}\nfunction isUpdatableQuery(node) {\n var updatableQuery = getNode(node);\n return typeof updatableQuery === 'object' && updatableQuery !== null && updatableQuery.kind === RelayConcreteNode.UPDATABLE_QUERY;\n}\nfunction isInlineDataFragment(node) {\n var fragment = getNode(node);\n return typeof fragment === 'object' && fragment !== null && fragment.kind === RelayConcreteNode.INLINE_DATA_FRAGMENT;\n}\nfunction getFragment(taggedNode) {\n var fragment = getNode(taggedNode);\n !isFragment(fragment) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'GraphQLTag: Expected a fragment, got `%s`.', JSON.stringify(fragment)) : invariant(false) : void 0;\n return fragment;\n}\nfunction getPaginationFragment(taggedNode) {\n var _fragment$metadata;\n var fragment = getFragment(taggedNode);\n var refetch = (_fragment$metadata = fragment.metadata) === null || _fragment$metadata === void 0 ? void 0 : _fragment$metadata.refetch;\n var connection = refetch === null || refetch === void 0 ? void 0 : refetch.connection;\n if (refetch === null || typeof refetch !== 'object' || connection === null || typeof connection !== 'object') {\n return null;\n }\n return fragment;\n}\nfunction getRefetchableFragment(taggedNode) {\n var _fragment$metadata2;\n var fragment = getFragment(taggedNode);\n var refetch = (_fragment$metadata2 = fragment.metadata) === null || _fragment$metadata2 === void 0 ? void 0 : _fragment$metadata2.refetch;\n if (refetch === null || typeof refetch !== 'object') {\n return null;\n }\n return fragment;\n}\nfunction getRequest(taggedNode) {\n var request = getNode(taggedNode);\n !isRequest(request) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'GraphQLTag: Expected a request, got `%s`.', JSON.stringify(request)) : invariant(false) : void 0;\n return request;\n}\nfunction getUpdatableQuery(taggedNode) {\n var updatableQuery = getNode(taggedNode);\n !isUpdatableQuery(updatableQuery) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'GraphQLTag: Expected a request, got `%s`.', JSON.stringify(updatableQuery)) : invariant(false) : void 0;\n return updatableQuery;\n}\nfunction getInlineDataFragment(taggedNode) {\n var fragment = getNode(taggedNode);\n !isInlineDataFragment(fragment) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'GraphQLTag: Expected an inline data fragment, got `%s`.', JSON.stringify(fragment)) : invariant(false) : void 0;\n return fragment;\n}\nmodule.exports = {\n getFragment: getFragment,\n getNode: getNode,\n getPaginationFragment: getPaginationFragment,\n getRefetchableFragment: getRefetchableFragment,\n getRequest: getRequest,\n getUpdatableQuery: getUpdatableQuery,\n getInlineDataFragment: getInlineDataFragment,\n graphql: graphql,\n isFragment: isFragment,\n isRequest: isRequest,\n isUpdatableQuery: isUpdatableQuery,\n isInlineDataFragment: isInlineDataFragment\n};","'use strict';\n\nvar PreloadableQueryRegistry = /*#__PURE__*/function () {\n function PreloadableQueryRegistry() {\n this._preloadableQueries = new Map();\n this._callbacks = new Map();\n }\n var _proto = PreloadableQueryRegistry.prototype;\n _proto.set = function set(key, value) {\n this._preloadableQueries.set(key, value);\n var callbacks = this._callbacks.get(key);\n if (callbacks != null) {\n callbacks.forEach(function (cb) {\n try {\n cb(value);\n } catch (e) {\n setTimeout(function () {\n throw e;\n }, 0);\n }\n });\n }\n };\n _proto.get = function get(key) {\n return this._preloadableQueries.get(key);\n };\n _proto.onLoad = function onLoad(key, callback) {\n var _this$_callbacks$get;\n var callbacks = (_this$_callbacks$get = this._callbacks.get(key)) !== null && _this$_callbacks$get !== void 0 ? _this$_callbacks$get : new Set();\n callbacks.add(callback);\n var dispose = function dispose() {\n callbacks[\"delete\"](callback);\n };\n this._callbacks.set(key, callbacks);\n return {\n dispose: dispose\n };\n };\n _proto.clear = function clear() {\n this._preloadableQueries.clear();\n };\n return PreloadableQueryRegistry;\n}();\nvar preloadableQueryRegistry = new PreloadableQueryRegistry();\nmodule.exports = preloadableQueryRegistry;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _objectSpread2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar RelayObservable = require('../network/RelayObservable');\nvar _require = require('../store/RelayModernOperationDescriptor'),\n createOperationDescriptor = _require.createOperationDescriptor;\nvar handlePotentialSnapshotErrors = require('../util/handlePotentialSnapshotErrors');\nvar fetchQueryInternal = require('./fetchQueryInternal');\nvar _require2 = require('./GraphQLTag'),\n getRequest = _require2.getRequest;\nvar invariant = require('invariant');\nfunction fetchQuery(environment, query, variables, options) {\n var _options$fetchPolicy;\n var queryNode = getRequest(query);\n !(queryNode.params.operationKind === 'query') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'fetchQuery: Expected query operation') : invariant(false) : void 0;\n var networkCacheConfig = (0, _objectSpread2[\"default\"])({\n force: true\n }, options === null || options === void 0 ? void 0 : options.networkCacheConfig);\n var operation = createOperationDescriptor(queryNode, variables, networkCacheConfig);\n var fetchPolicy = (_options$fetchPolicy = options === null || options === void 0 ? void 0 : options.fetchPolicy) !== null && _options$fetchPolicy !== void 0 ? _options$fetchPolicy : 'network-only';\n function readData(snapshot) {\n handlePotentialSnapshotErrors(environment, snapshot.missingRequiredFields, snapshot.relayResolverErrors, snapshot.errorResponseFields);\n return snapshot.data;\n }\n switch (fetchPolicy) {\n case 'network-only':\n {\n return getNetworkObservable(environment, operation).map(readData);\n }\n case 'store-or-network':\n {\n if (environment.check(operation).status === 'available') {\n return RelayObservable.from(environment.lookup(operation.fragment)).map(readData);\n }\n return getNetworkObservable(environment, operation).map(readData);\n }\n default:\n fetchPolicy;\n throw new Error('fetchQuery: Invalid fetchPolicy ' + fetchPolicy);\n }\n}\nfunction getNetworkObservable(environment, operation) {\n return fetchQueryInternal.fetchQuery(environment, operation).map(function () {\n return environment.lookup(operation.fragment);\n });\n}\nmodule.exports = fetchQuery;","'use strict';\n\nvar Observable = require('../network/RelayObservable');\nvar RelayReplaySubject = require('../util/RelayReplaySubject');\nvar invariant = require('invariant');\nvar WEAKMAP_SUPPORTED = typeof WeakMap === 'function';\nvar requestCachesByEnvironment = WEAKMAP_SUPPORTED ? new WeakMap() : new Map();\nfunction fetchQuery(environment, operation) {\n return fetchQueryDeduped(environment, operation.request.identifier, function () {\n return environment.execute({\n operation: operation\n });\n });\n}\nfunction fetchQueryDeduped(environment, identifier, fetchFn) {\n return Observable.create(function (sink) {\n var requestCache = getRequestCache(environment);\n var cachedRequest = requestCache.get(identifier);\n if (!cachedRequest) {\n fetchFn()[\"finally\"](function () {\n return requestCache[\"delete\"](identifier);\n }).subscribe({\n start: function start(subscription) {\n cachedRequest = {\n identifier: identifier,\n subject: new RelayReplaySubject(),\n subjectForInFlightStatus: new RelayReplaySubject(),\n subscription: subscription,\n promise: null\n };\n requestCache.set(identifier, cachedRequest);\n },\n next: function next(response) {\n var cachedReq = getCachedRequest(requestCache, identifier);\n cachedReq.subject.next(response);\n cachedReq.subjectForInFlightStatus.next(response);\n },\n error: function error(_error) {\n var cachedReq = getCachedRequest(requestCache, identifier);\n cachedReq.subject.error(_error);\n cachedReq.subjectForInFlightStatus.error(_error);\n },\n complete: function complete() {\n var cachedReq = getCachedRequest(requestCache, identifier);\n cachedReq.subject.complete();\n cachedReq.subjectForInFlightStatus.complete();\n },\n unsubscribe: function unsubscribe(subscription) {\n var cachedReq = getCachedRequest(requestCache, identifier);\n cachedReq.subject.unsubscribe();\n cachedReq.subjectForInFlightStatus.unsubscribe();\n }\n });\n }\n !(cachedRequest != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, '[fetchQueryInternal] fetchQueryDeduped: Expected `start` to be ' + 'called synchronously') : invariant(false) : void 0;\n return getObservableForCachedRequest(requestCache, cachedRequest).subscribe(sink);\n });\n}\nfunction getObservableForCachedRequest(requestCache, cachedRequest) {\n return Observable.create(function (sink) {\n var subscription = cachedRequest.subject.subscribe(sink);\n return function () {\n subscription.unsubscribe();\n var cachedRequestInstance = requestCache.get(cachedRequest.identifier);\n if (cachedRequestInstance) {\n var requestSubscription = cachedRequestInstance.subscription;\n if (requestSubscription != null && cachedRequestInstance.subject.getObserverCount() === 0) {\n requestSubscription.unsubscribe();\n requestCache[\"delete\"](cachedRequest.identifier);\n }\n }\n };\n });\n}\nfunction getActiveStatusObservableForCachedRequest(environment, requestCache, cachedRequest) {\n return Observable.create(function (sink) {\n var subscription = cachedRequest.subjectForInFlightStatus.subscribe({\n error: sink.error,\n next: function next(response) {\n if (!environment.isRequestActive(cachedRequest.identifier)) {\n sink.complete();\n return;\n }\n sink.next();\n },\n complete: sink.complete,\n unsubscribe: sink.complete\n });\n return function () {\n subscription.unsubscribe();\n };\n });\n}\nfunction getPromiseForActiveRequest(environment, request) {\n var requestCache = getRequestCache(environment);\n var cachedRequest = requestCache.get(request.identifier);\n if (!cachedRequest) {\n return null;\n }\n if (!environment.isRequestActive(cachedRequest.identifier)) {\n return null;\n }\n var promise = new Promise(function (resolve, reject) {\n var resolveOnNext = false;\n getActiveStatusObservableForCachedRequest(environment, requestCache, cachedRequest).subscribe({\n complete: resolve,\n error: reject,\n next: function next(response) {\n if (resolveOnNext) {\n resolve(response);\n }\n }\n });\n resolveOnNext = true;\n });\n return promise;\n}\nfunction getObservableForActiveRequest(environment, request) {\n var requestCache = getRequestCache(environment);\n var cachedRequest = requestCache.get(request.identifier);\n if (!cachedRequest) {\n return null;\n }\n if (!environment.isRequestActive(cachedRequest.identifier)) {\n return null;\n }\n return getActiveStatusObservableForCachedRequest(environment, requestCache, cachedRequest);\n}\nfunction getRequestCache(environment) {\n var cached = requestCachesByEnvironment.get(environment);\n if (cached != null) {\n return cached;\n }\n var requestCache = new Map();\n requestCachesByEnvironment.set(environment, requestCache);\n return requestCache;\n}\nfunction getCachedRequest(requestCache, identifier) {\n var cached = requestCache.get(identifier);\n !(cached != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, '[fetchQueryInternal] getCachedRequest: Expected request to be cached') : invariant(false) : void 0;\n return cached;\n}\nmodule.exports = {\n fetchQuery: fetchQuery,\n fetchQueryDeduped: fetchQueryDeduped,\n getPromiseForActiveRequest: getPromiseForActiveRequest,\n getObservableForActiveRequest: getObservableForActiveRequest\n};","'use strict';\n\nvar _require = require('../store/RelayModernOperationDescriptor'),\n createOperationDescriptor = _require.createOperationDescriptor;\nvar _require2 = require('./GraphQLTag'),\n getRequest = _require2.getRequest;\nfunction fetchQuery_DEPRECATED(environment, taggedNode, variables, cacheConfig) {\n var query = getRequest(taggedNode);\n if (query.params.operationKind !== 'query') {\n throw new Error('fetchQuery: Expected query operation');\n }\n var operation = createOperationDescriptor(query, variables, cacheConfig);\n return environment.execute({\n operation: operation\n }).map(function () {\n return environment.lookup(operation.fragment).data;\n }).toPromise();\n}\nmodule.exports = fetchQuery_DEPRECATED;","'use strict';\n\nvar RelayFeatureFlags = require('../util/RelayFeatureFlags');\nvar _require = require('../util/StringInterner'),\n intern = _require.intern;\nvar PREFIX = 'client:';\nfunction generateClientID(id, storageKey, index) {\n var internedId = RelayFeatureFlags.STRING_INTERN_LEVEL <= 0 ? id : intern(id, RelayFeatureFlags.MAX_DATA_ID_LENGTH);\n var key = internedId + ':' + storageKey;\n if (index != null) {\n key += ':' + index;\n }\n if (key.indexOf(PREFIX) !== 0) {\n key = PREFIX + key;\n }\n return key;\n}\nfunction isClientID(id) {\n return id.indexOf(PREFIX) === 0;\n}\nvar localID = 0;\nfunction generateUniqueClientID() {\n return \"\".concat(PREFIX, \"local:\").concat(localID++);\n}\nfunction generateClientObjectClientID(typename, localId, index) {\n var key = \"\".concat(PREFIX).concat(typename, \":\").concat(localId);\n if (index != null) {\n key += ':' + index;\n }\n return key;\n}\nmodule.exports = {\n generateClientID: generateClientID,\n generateClientObjectClientID: generateClientObjectClientID,\n generateUniqueClientID: generateUniqueClientID,\n isClientID: isClientID\n};","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _createForOfIteratorHelper2 = _interopRequireDefault(require(\"@babel/runtime/helpers/createForOfIteratorHelper\"));\nvar RelayRecordSourceMutator = require('../mutations/RelayRecordSourceMutator');\nvar RelayRecordSourceProxy = require('../mutations/RelayRecordSourceProxy');\nvar getOperation = require('../util/getOperation');\nvar RelayConcreteNode = require('../util/RelayConcreteNode');\nvar _require = require('./ClientID'),\n isClientID = _require.isClientID;\nvar cloneRelayHandleSourceField = require('./cloneRelayHandleSourceField');\nvar cloneRelayScalarHandleSourceField = require('./cloneRelayScalarHandleSourceField');\nvar _require2 = require('./RelayConcreteVariables'),\n getLocalVariables = _require2.getLocalVariables;\nvar RelayModernRecord = require('./RelayModernRecord');\nvar _require3 = require('./RelayRecordState'),\n EXISTENT = _require3.EXISTENT,\n UNKNOWN = _require3.UNKNOWN;\nvar RelayStoreUtils = require('./RelayStoreUtils');\nvar _require4 = require('./TypeID'),\n TYPE_SCHEMA_TYPE = _require4.TYPE_SCHEMA_TYPE,\n generateTypeID = _require4.generateTypeID;\nvar invariant = require('invariant');\nvar ACTOR_CHANGE = RelayConcreteNode.ACTOR_CHANGE,\n CONDITION = RelayConcreteNode.CONDITION,\n CLIENT_COMPONENT = RelayConcreteNode.CLIENT_COMPONENT,\n CLIENT_EXTENSION = RelayConcreteNode.CLIENT_EXTENSION,\n CLIENT_EDGE_TO_CLIENT_OBJECT = RelayConcreteNode.CLIENT_EDGE_TO_CLIENT_OBJECT,\n DEFER = RelayConcreteNode.DEFER,\n FRAGMENT_SPREAD = RelayConcreteNode.FRAGMENT_SPREAD,\n INLINE_FRAGMENT = RelayConcreteNode.INLINE_FRAGMENT,\n LINKED_FIELD = RelayConcreteNode.LINKED_FIELD,\n LINKED_HANDLE = RelayConcreteNode.LINKED_HANDLE,\n MODULE_IMPORT = RelayConcreteNode.MODULE_IMPORT,\n RELAY_RESOLVER = RelayConcreteNode.RELAY_RESOLVER,\n RELAY_LIVE_RESOLVER = RelayConcreteNode.RELAY_LIVE_RESOLVER,\n SCALAR_FIELD = RelayConcreteNode.SCALAR_FIELD,\n SCALAR_HANDLE = RelayConcreteNode.SCALAR_HANDLE,\n STREAM = RelayConcreteNode.STREAM,\n TYPE_DISCRIMINATOR = RelayConcreteNode.TYPE_DISCRIMINATOR;\nvar getModuleOperationKey = RelayStoreUtils.getModuleOperationKey,\n getStorageKey = RelayStoreUtils.getStorageKey,\n getArgumentValues = RelayStoreUtils.getArgumentValues;\nfunction check(getSourceForActor, getTargetForActor, defaultActorIdentifier, selector, handlers, operationLoader, getDataID, shouldProcessClientComponents) {\n var dataID = selector.dataID,\n node = selector.node,\n variables = selector.variables;\n var checker = new DataChecker(getSourceForActor, getTargetForActor, defaultActorIdentifier, variables, handlers, operationLoader, getDataID, shouldProcessClientComponents);\n return checker.check(node, dataID);\n}\nvar DataChecker = /*#__PURE__*/function () {\n function DataChecker(getSourceForActor, getTargetForActor, defaultActorIdentifier, variables, handlers, operationLoader, getDataID, shouldProcessClientComponents) {\n this._getSourceForActor = getSourceForActor;\n this._getTargetForActor = getTargetForActor;\n this._getDataID = getDataID;\n this._source = getSourceForActor(defaultActorIdentifier);\n this._mutatorRecordSourceProxyCache = new Map();\n var _this$_getMutatorAndR = this._getMutatorAndRecordProxyForActor(defaultActorIdentifier),\n mutator = _this$_getMutatorAndR[0],\n recordSourceProxy = _this$_getMutatorAndR[1];\n this._mostRecentlyInvalidatedAt = null;\n this._handlers = handlers;\n this._mutator = mutator;\n this._operationLoader = operationLoader !== null && operationLoader !== void 0 ? operationLoader : null;\n this._recordSourceProxy = recordSourceProxy;\n this._recordWasMissing = false;\n this._variables = variables;\n this._shouldProcessClientComponents = shouldProcessClientComponents;\n }\n var _proto = DataChecker.prototype;\n _proto._getMutatorAndRecordProxyForActor = function _getMutatorAndRecordProxyForActor(actorIdentifier) {\n var tuple = this._mutatorRecordSourceProxyCache.get(actorIdentifier);\n if (tuple == null) {\n var target = this._getTargetForActor(actorIdentifier);\n var mutator = new RelayRecordSourceMutator(this._getSourceForActor(actorIdentifier), target);\n var recordSourceProxy = new RelayRecordSourceProxy(mutator, this._getDataID, undefined, this._handlers);\n tuple = [mutator, recordSourceProxy];\n this._mutatorRecordSourceProxyCache.set(actorIdentifier, tuple);\n }\n return tuple;\n };\n _proto.check = function check(node, dataID) {\n this._assignClientAbstractTypes(node);\n this._traverse(node, dataID);\n return this._recordWasMissing === true ? {\n status: 'missing',\n mostRecentlyInvalidatedAt: this._mostRecentlyInvalidatedAt\n } : {\n status: 'available',\n mostRecentlyInvalidatedAt: this._mostRecentlyInvalidatedAt\n };\n };\n _proto._getVariableValue = function _getVariableValue(name) {\n !this._variables.hasOwnProperty(name) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayAsyncLoader(): Undefined variable `%s`.', name) : invariant(false) : void 0;\n return this._variables[name];\n };\n _proto._handleMissing = function _handleMissing() {\n this._recordWasMissing = true;\n };\n _proto._handleMissingScalarField = function _handleMissingScalarField(field, dataID) {\n if (field.name === 'id' && field.alias == null && isClientID(dataID)) {\n return undefined;\n }\n var args = field.args != undefined ? getArgumentValues(field.args, this._variables) : {};\n var _iterator = (0, _createForOfIteratorHelper2[\"default\"])(this._handlers),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var handler = _step.value;\n if (handler.kind === 'scalar') {\n var newValue = handler.handle(field, this._recordSourceProxy.get(dataID), args, this._recordSourceProxy);\n if (newValue !== undefined) {\n return newValue;\n }\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n this._handleMissing();\n };\n _proto._handleMissingLinkField = function _handleMissingLinkField(field, dataID) {\n var args = field.args != undefined ? getArgumentValues(field.args, this._variables) : {};\n var _iterator2 = (0, _createForOfIteratorHelper2[\"default\"])(this._handlers),\n _step2;\n try {\n for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n var handler = _step2.value;\n if (handler.kind === 'linked') {\n var newValue = handler.handle(field, this._recordSourceProxy.get(dataID), args, this._recordSourceProxy);\n if (newValue !== undefined && (newValue === null || this._mutator.getStatus(newValue) === EXISTENT)) {\n return newValue;\n }\n }\n }\n } catch (err) {\n _iterator2.e(err);\n } finally {\n _iterator2.f();\n }\n this._handleMissing();\n };\n _proto._handleMissingPluralLinkField = function _handleMissingPluralLinkField(field, dataID) {\n var _this = this;\n var args = field.args != undefined ? getArgumentValues(field.args, this._variables) : {};\n var _iterator3 = (0, _createForOfIteratorHelper2[\"default\"])(this._handlers),\n _step3;\n try {\n for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {\n var handler = _step3.value;\n if (handler.kind === 'pluralLinked') {\n var newValue = handler.handle(field, this._recordSourceProxy.get(dataID), args, this._recordSourceProxy);\n if (newValue != null) {\n var allItemsKnown = newValue.every(function (linkedID) {\n return linkedID != null && _this._mutator.getStatus(linkedID) === EXISTENT;\n });\n if (allItemsKnown) {\n return newValue;\n }\n } else if (newValue === null) {\n return null;\n }\n }\n }\n } catch (err) {\n _iterator3.e(err);\n } finally {\n _iterator3.f();\n }\n this._handleMissing();\n };\n _proto._traverse = function _traverse(node, dataID) {\n var status = this._mutator.getStatus(dataID);\n if (status === UNKNOWN) {\n this._handleMissing();\n }\n if (status === EXISTENT) {\n var record = this._source.get(dataID);\n var invalidatedAt = RelayModernRecord.getInvalidationEpoch(record);\n if (invalidatedAt != null) {\n this._mostRecentlyInvalidatedAt = this._mostRecentlyInvalidatedAt != null ? Math.max(this._mostRecentlyInvalidatedAt, invalidatedAt) : invalidatedAt;\n }\n this._traverseSelections(node.selections, dataID);\n }\n };\n _proto._traverseSelections = function _traverseSelections(selections, dataID) {\n var _this2 = this;\n selections.forEach(function (selection) {\n switch (selection.kind) {\n case SCALAR_FIELD:\n _this2._checkScalar(selection, dataID);\n break;\n case LINKED_FIELD:\n if (selection.plural) {\n _this2._checkPluralLink(selection, dataID);\n } else {\n _this2._checkLink(selection, dataID);\n }\n break;\n case ACTOR_CHANGE:\n _this2._checkActorChange(selection.linkedField, dataID);\n break;\n case CONDITION:\n var conditionValue = Boolean(_this2._getVariableValue(selection.condition));\n if (conditionValue === selection.passingValue) {\n _this2._traverseSelections(selection.selections, dataID);\n }\n break;\n case INLINE_FRAGMENT:\n {\n var _abstractKey = selection.abstractKey;\n if (_abstractKey == null) {\n var typeName = _this2._mutator.getType(dataID);\n if (typeName === selection.type) {\n _this2._traverseSelections(selection.selections, dataID);\n }\n } else {\n var _recordType = _this2._mutator.getType(dataID);\n !(_recordType != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'DataChecker: Expected record `%s` to have a known type', dataID) : invariant(false) : void 0;\n var _typeID = generateTypeID(_recordType);\n var _implementsInterface = _this2._mutator.getValue(_typeID, _abstractKey);\n if (_implementsInterface === true) {\n _this2._traverseSelections(selection.selections, dataID);\n } else if (_implementsInterface == null) {\n _this2._handleMissing();\n }\n }\n break;\n }\n case LINKED_HANDLE:\n {\n var handleField = cloneRelayHandleSourceField(selection, selections, _this2._variables);\n if (handleField.plural) {\n _this2._checkPluralLink(handleField, dataID);\n } else {\n _this2._checkLink(handleField, dataID);\n }\n break;\n }\n case SCALAR_HANDLE:\n {\n var _handleField = cloneRelayScalarHandleSourceField(selection, selections, _this2._variables);\n _this2._checkScalar(_handleField, dataID);\n break;\n }\n case MODULE_IMPORT:\n _this2._checkModuleImport(selection, dataID);\n break;\n case DEFER:\n case STREAM:\n _this2._traverseSelections(selection.selections, dataID);\n break;\n case FRAGMENT_SPREAD:\n var prevVariables = _this2._variables;\n _this2._variables = getLocalVariables(_this2._variables, selection.fragment.argumentDefinitions, selection.args);\n _this2._traverseSelections(selection.fragment.selections, dataID);\n _this2._variables = prevVariables;\n break;\n case CLIENT_EXTENSION:\n var recordWasMissing = _this2._recordWasMissing;\n _this2._traverseSelections(selection.selections, dataID);\n _this2._recordWasMissing = recordWasMissing;\n break;\n case TYPE_DISCRIMINATOR:\n var abstractKey = selection.abstractKey;\n var recordType = _this2._mutator.getType(dataID);\n !(recordType != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'DataChecker: Expected record `%s` to have a known type', dataID) : invariant(false) : void 0;\n var typeID = generateTypeID(recordType);\n var implementsInterface = _this2._mutator.getValue(typeID, abstractKey);\n if (implementsInterface == null) {\n _this2._handleMissing();\n }\n break;\n case CLIENT_COMPONENT:\n if (_this2._shouldProcessClientComponents === false) {\n break;\n }\n _this2._traverseSelections(selection.fragment.selections, dataID);\n break;\n case RELAY_RESOLVER:\n _this2._checkResolver(selection, dataID);\n break;\n case RELAY_LIVE_RESOLVER:\n _this2._checkResolver(selection, dataID);\n break;\n case CLIENT_EDGE_TO_CLIENT_OBJECT:\n _this2._checkResolver(selection.backingField, dataID);\n break;\n default:\n selection;\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayAsyncLoader(): Unexpected ast kind `%s`.', selection.kind) : invariant(false) : void 0;\n }\n });\n };\n _proto._checkResolver = function _checkResolver(resolver, dataID) {\n if (resolver.fragment) {\n this._traverseSelections([resolver.fragment], dataID);\n }\n };\n _proto._checkModuleImport = function _checkModuleImport(moduleImport, dataID) {\n var operationLoader = this._operationLoader;\n !(operationLoader !== null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'DataChecker: Expected an operationLoader to be configured when using `@module`.') : invariant(false) : void 0;\n var operationKey = getModuleOperationKey(moduleImport.documentName);\n var operationReference = this._mutator.getValue(dataID, operationKey);\n if (operationReference == null) {\n if (operationReference === undefined) {\n this._handleMissing();\n }\n return;\n }\n var normalizationRootNode = operationLoader.get(operationReference);\n if (normalizationRootNode != null) {\n var operation = getOperation(normalizationRootNode);\n var prevVariables = this._variables;\n this._variables = getLocalVariables(this._variables, operation.argumentDefinitions, moduleImport.args);\n this._traverse(operation, dataID);\n this._variables = prevVariables;\n } else {\n this._handleMissing();\n }\n };\n _proto._checkScalar = function _checkScalar(field, dataID) {\n var storageKey = getStorageKey(field, this._variables);\n var fieldValue = this._mutator.getValue(dataID, storageKey);\n if (fieldValue === undefined) {\n fieldValue = this._handleMissingScalarField(field, dataID);\n if (fieldValue !== undefined) {\n this._mutator.setValue(dataID, storageKey, fieldValue);\n }\n }\n };\n _proto._checkLink = function _checkLink(field, dataID) {\n var storageKey = getStorageKey(field, this._variables);\n var linkedID = this._mutator.getLinkedRecordID(dataID, storageKey);\n if (linkedID === undefined) {\n linkedID = this._handleMissingLinkField(field, dataID);\n if (linkedID != null) {\n this._mutator.setLinkedRecordID(dataID, storageKey, linkedID);\n } else if (linkedID === null) {\n this._mutator.setValue(dataID, storageKey, null);\n }\n }\n if (linkedID != null) {\n this._traverse(field, linkedID);\n }\n };\n _proto._checkPluralLink = function _checkPluralLink(field, dataID) {\n var _this3 = this;\n var storageKey = getStorageKey(field, this._variables);\n var linkedIDs = this._mutator.getLinkedRecordIDs(dataID, storageKey);\n if (linkedIDs === undefined) {\n linkedIDs = this._handleMissingPluralLinkField(field, dataID);\n if (linkedIDs != null) {\n this._mutator.setLinkedRecordIDs(dataID, storageKey, linkedIDs);\n } else if (linkedIDs === null) {\n this._mutator.setValue(dataID, storageKey, null);\n }\n }\n if (linkedIDs) {\n linkedIDs.forEach(function (linkedID) {\n if (linkedID != null) {\n _this3._traverse(field, linkedID);\n }\n });\n }\n };\n _proto._checkActorChange = function _checkActorChange(field, dataID) {\n var storageKey = getStorageKey(field, this._variables);\n var record = this._source.get(dataID);\n var tuple = record != null ? RelayModernRecord.getActorLinkedRecordID(record, storageKey) : record;\n if (tuple == null) {\n if (tuple === undefined) {\n this._handleMissing();\n }\n } else {\n var actorIdentifier = tuple[0],\n linkedID = tuple[1];\n var prevSource = this._source;\n var prevMutator = this._mutator;\n var prevRecordSourceProxy = this._recordSourceProxy;\n var _this$_getMutatorAndR2 = this._getMutatorAndRecordProxyForActor(actorIdentifier),\n mutator = _this$_getMutatorAndR2[0],\n recordSourceProxy = _this$_getMutatorAndR2[1];\n this._source = this._getSourceForActor(actorIdentifier);\n this._mutator = mutator;\n this._recordSourceProxy = recordSourceProxy;\n this._assignClientAbstractTypes(field);\n this._traverse(field, linkedID);\n this._source = prevSource;\n this._mutator = prevMutator;\n this._recordSourceProxy = prevRecordSourceProxy;\n }\n };\n _proto._assignClientAbstractTypes = function _assignClientAbstractTypes(node) {\n var clientAbstractTypes = node.clientAbstractTypes;\n if (clientAbstractTypes != null) {\n for (var _i = 0, _Object$keys = Object.keys(clientAbstractTypes); _i < _Object$keys.length; _i++) {\n var abstractType = _Object$keys[_i];\n var _iterator4 = (0, _createForOfIteratorHelper2[\"default\"])(clientAbstractTypes[abstractType]),\n _step4;\n try {\n for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {\n var concreteType = _step4.value;\n var typeID = generateTypeID(concreteType);\n if (this._source.get(typeID) == null) {\n this._mutator.create(typeID, TYPE_SCHEMA_TYPE);\n }\n if (this._mutator.getValue(typeID, abstractType) == null) {\n this._mutator.setValue(typeID, abstractType, true);\n }\n }\n } catch (err) {\n _iterator4.e(err);\n } finally {\n _iterator4.f();\n }\n }\n }\n };\n return DataChecker;\n}();\nmodule.exports = {\n check: check\n};","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _createForOfIteratorHelper2 = _interopRequireDefault(require(\"@babel/runtime/helpers/createForOfIteratorHelper\"));\nvar _toConsumableArray2 = _interopRequireDefault(require(\"@babel/runtime/helpers/toConsumableArray\"));\nvar RelayObservable = require('../network/RelayObservable');\nvar generateID = require('../util/generateID');\nvar getOperation = require('../util/getOperation');\nvar RelayError = require('../util/RelayError');\nvar RelayFeatureFlags = require('../util/RelayFeatureFlags');\nvar stableCopy = require('../util/stableCopy');\nvar withDuration = require('../util/withDuration');\nvar _require = require('./ClientID'),\n generateClientID = _require.generateClientID,\n generateUniqueClientID = _require.generateUniqueClientID;\nvar _require2 = require('./RelayConcreteVariables'),\n getLocalVariables = _require2.getLocalVariables;\nvar RelayModernRecord = require('./RelayModernRecord');\nvar _require3 = require('./RelayModernSelector'),\n createNormalizationSelector = _require3.createNormalizationSelector,\n createReaderSelector = _require3.createReaderSelector;\nvar RelayRecordSource = require('./RelayRecordSource');\nvar _require4 = require('./RelayStoreUtils'),\n ROOT_TYPE = _require4.ROOT_TYPE,\n TYPENAME_KEY = _require4.TYPENAME_KEY,\n getStorageKey = _require4.getStorageKey;\nvar invariant = require('invariant');\nvar warning = require(\"fbjs/lib/warning\");\nfunction execute(config) {\n return new Executor(config);\n}\nvar Executor = /*#__PURE__*/function () {\n function Executor(_ref2) {\n var _this = this;\n var actorIdentifier = _ref2.actorIdentifier,\n getDataID = _ref2.getDataID,\n getPublishQueue = _ref2.getPublishQueue,\n getStore = _ref2.getStore,\n isClientPayload = _ref2.isClientPayload,\n operation = _ref2.operation,\n operationExecutions = _ref2.operationExecutions,\n operationLoader = _ref2.operationLoader,\n operationTracker = _ref2.operationTracker,\n optimisticConfig = _ref2.optimisticConfig,\n scheduler = _ref2.scheduler,\n shouldProcessClientComponents = _ref2.shouldProcessClientComponents,\n sink = _ref2.sink,\n source = _ref2.source,\n treatMissingFieldsAsNull = _ref2.treatMissingFieldsAsNull,\n updater = _ref2.updater,\n log = _ref2.log,\n normalizeResponse = _ref2.normalizeResponse;\n this._actorIdentifier = actorIdentifier;\n this._getDataID = getDataID;\n this._treatMissingFieldsAsNull = treatMissingFieldsAsNull;\n this._incrementalPayloadsPending = false;\n this._incrementalResults = new Map();\n this._log = log;\n this._executeId = generateID();\n this._nextSubscriptionId = 0;\n this._operation = operation;\n this._operationExecutions = operationExecutions;\n this._operationLoader = operationLoader;\n this._operationTracker = operationTracker;\n this._operationUpdateEpochs = new Map();\n this._optimisticUpdates = null;\n this._pendingModulePayloadsCount = 0;\n this._getPublishQueue = getPublishQueue;\n this._scheduler = scheduler;\n this._sink = sink;\n this._source = new Map();\n this._state = 'started';\n this._getStore = getStore;\n this._subscriptions = new Map();\n this._updater = updater;\n this._isClientPayload = isClientPayload === true;\n this._isSubscriptionOperation = this._operation.request.node.params.operationKind === 'subscription';\n this._shouldProcessClientComponents = shouldProcessClientComponents;\n this._retainDisposables = new Map();\n this._seenActors = new Set();\n this._completeFns = [];\n this._normalizeResponse = normalizeResponse;\n var id = this._nextSubscriptionId++;\n source.subscribe({\n complete: function complete() {\n return _this._complete(id);\n },\n error: function error(_error2) {\n return _this._error(_error2);\n },\n next: function next(response) {\n try {\n _this._next(id, response);\n } catch (error) {\n sink.error(error);\n }\n },\n start: function start(subscription) {\n var _this$_operation$requ;\n _this._start(id, subscription);\n _this._log({\n name: 'execute.start',\n executeId: _this._executeId,\n params: _this._operation.request.node.params,\n variables: _this._operation.request.variables,\n cacheConfig: (_this$_operation$requ = _this._operation.request.cacheConfig) !== null && _this$_operation$requ !== void 0 ? _this$_operation$requ : {}\n });\n }\n });\n if (optimisticConfig != null) {\n this._processOptimisticResponse(optimisticConfig.response != null ? {\n data: optimisticConfig.response\n } : null, optimisticConfig.updater, false);\n }\n }\n var _proto = Executor.prototype;\n _proto.cancel = function cancel() {\n var _this2 = this;\n if (this._state === 'completed') {\n return;\n }\n this._state = 'completed';\n this._operationExecutions[\"delete\"](this._operation.request.identifier);\n if (this._subscriptions.size !== 0) {\n this._subscriptions.forEach(function (sub) {\n return sub.unsubscribe();\n });\n this._subscriptions.clear();\n }\n var optimisticUpdates = this._optimisticUpdates;\n if (optimisticUpdates !== null) {\n this._optimisticUpdates = null;\n optimisticUpdates.forEach(function (update) {\n return _this2._getPublishQueueAndSaveActor().revertUpdate(update);\n });\n this._runPublishQueue();\n }\n this._incrementalResults.clear();\n if (this._asyncStoreUpdateDisposable != null) {\n this._asyncStoreUpdateDisposable.dispose();\n this._asyncStoreUpdateDisposable = null;\n }\n this._completeFns = [];\n this._completeOperationTracker();\n this._disposeRetainedData();\n };\n _proto._updateActiveState = function _updateActiveState() {\n var activeState;\n switch (this._state) {\n case 'started':\n {\n activeState = 'active';\n break;\n }\n case 'loading_incremental':\n {\n activeState = 'active';\n break;\n }\n case 'completed':\n {\n activeState = 'inactive';\n break;\n }\n case 'loading_final':\n {\n activeState = this._pendingModulePayloadsCount > 0 ? 'active' : 'inactive';\n break;\n }\n default:\n this._state;\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'OperationExecutor: invalid executor state.') : invariant(false) : void 0;\n }\n this._operationExecutions.set(this._operation.request.identifier, activeState);\n };\n _proto._schedule = function _schedule(task) {\n var _this3 = this;\n var scheduler = this._scheduler;\n if (scheduler != null) {\n var id = this._nextSubscriptionId++;\n RelayObservable.create(function (sink) {\n var cancellationToken = scheduler.schedule(function () {\n try {\n task();\n sink.complete();\n } catch (error) {\n sink.error(error);\n }\n });\n return function () {\n return scheduler.cancel(cancellationToken);\n };\n }).subscribe({\n complete: function complete() {\n return _this3._complete(id);\n },\n error: function error(_error3) {\n return _this3._error(_error3);\n },\n start: function start(subscription) {\n return _this3._start(id, subscription);\n }\n });\n } else {\n task();\n }\n };\n _proto._complete = function _complete(id) {\n this._subscriptions[\"delete\"](id);\n if (this._subscriptions.size === 0) {\n this.cancel();\n this._sink.complete();\n this._log({\n name: 'execute.complete',\n executeId: this._executeId\n });\n }\n };\n _proto._error = function _error(error) {\n this.cancel();\n this._sink.error(error);\n this._log({\n name: 'execute.error',\n executeId: this._executeId,\n error: error\n });\n };\n _proto._start = function _start(id, subscription) {\n this._subscriptions.set(id, subscription);\n this._updateActiveState();\n };\n _proto._next = function _next(_id, response) {\n var _this4 = this;\n this._schedule(function () {\n var _withDuration = withDuration(function () {\n _this4._handleNext(response);\n _this4._maybeCompleteSubscriptionOperationTracking();\n }),\n duration = _withDuration[0];\n _this4._log({\n name: 'execute.next',\n executeId: _this4._executeId,\n response: response,\n duration: duration\n });\n });\n };\n _proto._handleErrorResponse = function _handleErrorResponse(responses) {\n var _this5 = this;\n var results = [];\n responses.forEach(function (response) {\n if (response.data === null && response.extensions != null && !response.hasOwnProperty('errors')) {\n return;\n } else if (response.data == null) {\n var errors = response.hasOwnProperty('errors') && response.errors != null ? response.errors : null;\n var messages = errors ? errors.map(function (_ref3) {\n var message = _ref3.message;\n return message;\n }).join('\\n') : '(No errors)';\n var error = RelayError.create('RelayNetwork', 'No data returned for operation `' + _this5._operation.request.node.params.name + '`, got error(s):\\n' + messages + '\\n\\nSee the error `source` property for more information.');\n error.source = {\n errors: errors,\n operation: _this5._operation.request.node,\n variables: _this5._operation.request.variables\n };\n error.stack;\n throw error;\n } else {\n var responseWithData = response;\n results.push(responseWithData);\n }\n });\n return results;\n };\n _proto._handleOptimisticResponses = function _handleOptimisticResponses(responses) {\n var _response$extensions;\n if (responses.length > 1) {\n if (responses.some(function (responsePart) {\n var _responsePart$extensi;\n return ((_responsePart$extensi = responsePart.extensions) === null || _responsePart$extensi === void 0 ? void 0 : _responsePart$extensi.isOptimistic) === true;\n })) {\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'OperationExecutor: Optimistic responses cannot be batched.') : invariant(false) : void 0;\n }\n return false;\n }\n var response = responses[0];\n var isOptimistic = ((_response$extensions = response.extensions) === null || _response$extensions === void 0 ? void 0 : _response$extensions.isOptimistic) === true;\n if (isOptimistic && this._state !== 'started') {\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'OperationExecutor: optimistic payload received after server payload.') : invariant(false) : void 0;\n }\n if (isOptimistic) {\n this._processOptimisticResponse(response, null, this._treatMissingFieldsAsNull);\n this._sink.next(response);\n return true;\n }\n return false;\n };\n _proto._handleNext = function _handleNext(response) {\n if (this._state === 'completed') {\n return;\n }\n this._seenActors.clear();\n var responses = Array.isArray(response) ? response : [response];\n var responsesWithData = this._handleErrorResponse(responses);\n if (responsesWithData.length === 0) {\n var isFinal = responses.some(function (x) {\n var _x$extensions;\n return ((_x$extensions = x.extensions) === null || _x$extensions === void 0 ? void 0 : _x$extensions.is_final) === true;\n });\n if (isFinal) {\n this._state = 'loading_final';\n this._updateActiveState();\n this._incrementalPayloadsPending = false;\n }\n this._sink.next(response);\n return;\n }\n var isOptimistic = this._handleOptimisticResponses(responsesWithData);\n if (isOptimistic) {\n return;\n }\n var _partitionGraphQLResp = partitionGraphQLResponses(responsesWithData),\n nonIncrementalResponses = _partitionGraphQLResp[0],\n incrementalResponses = _partitionGraphQLResp[1];\n var hasNonIncrementalResponses = nonIncrementalResponses.length > 0;\n if (hasNonIncrementalResponses) {\n if (this._isSubscriptionOperation) {\n var nextID = generateUniqueClientID();\n this._operation = {\n request: this._operation.request,\n fragment: createReaderSelector(this._operation.fragment.node, nextID, this._operation.fragment.variables, this._operation.fragment.owner),\n root: createNormalizationSelector(this._operation.root.node, nextID, this._operation.root.variables)\n };\n }\n var payloadFollowups = this._processResponses(nonIncrementalResponses);\n this._processPayloadFollowups(payloadFollowups);\n }\n if (incrementalResponses.length > 0) {\n var _payloadFollowups = this._processIncrementalResponses(incrementalResponses);\n this._processPayloadFollowups(_payloadFollowups);\n }\n if (this._isSubscriptionOperation) {\n if (responsesWithData[0].extensions == null) {\n responsesWithData[0].extensions = {\n __relay_subscription_root_id: this._operation.fragment.dataID\n };\n } else {\n responsesWithData[0].extensions.__relay_subscription_root_id = this._operation.fragment.dataID;\n }\n }\n var updatedOwners = this._runPublishQueue(hasNonIncrementalResponses ? this._operation : undefined);\n if (hasNonIncrementalResponses) {\n if (this._incrementalPayloadsPending) {\n this._retainData();\n }\n }\n this._updateOperationTracker(updatedOwners);\n this._sink.next(response);\n };\n _proto._processOptimisticResponse = function _processOptimisticResponse(response, updater, treatMissingFieldsAsNull) {\n var _this6 = this;\n !(this._optimisticUpdates === null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'OperationExecutor: environment.execute: only support one optimistic response per ' + 'execute.') : invariant(false) : void 0;\n if (response == null && updater == null) {\n return;\n }\n var optimisticUpdates = [];\n if (response) {\n var payload = this._normalizeResponse(response, this._operation.root, ROOT_TYPE, {\n actorIdentifier: this._actorIdentifier,\n getDataID: this._getDataID,\n path: [],\n shouldProcessClientComponents: this._shouldProcessClientComponents,\n treatMissingFieldsAsNull: treatMissingFieldsAsNull\n });\n validateOptimisticResponsePayload(payload);\n optimisticUpdates.push({\n operation: this._operation,\n payload: payload,\n updater: updater\n });\n this._processOptimisticFollowups(payload, optimisticUpdates);\n } else if (updater) {\n optimisticUpdates.push({\n operation: this._operation,\n payload: {\n errors: null,\n fieldPayloads: null,\n incrementalPlaceholders: null,\n followupPayloads: null,\n source: RelayRecordSource.create(),\n isFinal: false\n },\n updater: updater\n });\n }\n this._optimisticUpdates = optimisticUpdates;\n optimisticUpdates.forEach(function (update) {\n return _this6._getPublishQueueAndSaveActor().applyUpdate(update);\n });\n var updatedOwners = this._runPublishQueue();\n if (RelayFeatureFlags.ENABLE_OPERATION_TRACKER_OPTIMISTIC_UPDATES) {\n this._updateOperationTracker(updatedOwners);\n }\n };\n _proto._processOptimisticFollowups = function _processOptimisticFollowups(payload, optimisticUpdates) {\n if (payload.followupPayloads && payload.followupPayloads.length) {\n var followupPayloads = payload.followupPayloads;\n var _iterator = (0, _createForOfIteratorHelper2[\"default\"])(followupPayloads),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var followupPayload = _step.value;\n switch (followupPayload.kind) {\n case 'ModuleImportPayload':\n var operationLoader = this._expectOperationLoader();\n var operation = operationLoader.get(followupPayload.operationReference);\n if (operation == null) {\n this._processAsyncOptimisticModuleImport(followupPayload);\n } else {\n var moduleImportOptimisticUpdates = this._processOptimisticModuleImport(operation, followupPayload);\n optimisticUpdates.push.apply(optimisticUpdates, (0, _toConsumableArray2[\"default\"])(moduleImportOptimisticUpdates));\n }\n break;\n case 'ActorPayload':\n process.env.NODE_ENV !== \"production\" ? warning(false, 'OperationExecutor: Unexpected optimistic ActorPayload. These updates are not supported.') : void 0;\n break;\n default:\n followupPayload;\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'OperationExecutor: Unexpected followup kind `%s`. when processing optimistic updates.', followupPayload.kind) : invariant(false) : void 0;\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n }\n };\n _proto._normalizeFollowupPayload = function _normalizeFollowupPayload(followupPayload, normalizationNode) {\n var variables;\n if (normalizationNode.kind === 'SplitOperation' && followupPayload.kind === 'ModuleImportPayload') {\n variables = getLocalVariables(followupPayload.variables, normalizationNode.argumentDefinitions, followupPayload.args);\n } else {\n variables = followupPayload.variables;\n }\n var selector = createNormalizationSelector(normalizationNode, followupPayload.dataID, variables);\n return this._normalizeResponse({\n data: followupPayload.data\n }, selector, followupPayload.typeName, {\n actorIdentifier: this._actorIdentifier,\n getDataID: this._getDataID,\n path: followupPayload.path,\n treatMissingFieldsAsNull: this._treatMissingFieldsAsNull,\n shouldProcessClientComponents: this._shouldProcessClientComponents\n });\n };\n _proto._processOptimisticModuleImport = function _processOptimisticModuleImport(normalizationRootNode, moduleImportPayload) {\n var operation = getOperation(normalizationRootNode);\n var optimisticUpdates = [];\n var modulePayload = this._normalizeFollowupPayload(moduleImportPayload, operation);\n validateOptimisticResponsePayload(modulePayload);\n optimisticUpdates.push({\n operation: this._operation,\n payload: modulePayload,\n updater: null\n });\n this._processOptimisticFollowups(modulePayload, optimisticUpdates);\n return optimisticUpdates;\n };\n _proto._processAsyncOptimisticModuleImport = function _processAsyncOptimisticModuleImport(moduleImportPayload) {\n var _this7 = this;\n this._expectOperationLoader().load(moduleImportPayload.operationReference).then(function (operation) {\n if (operation == null || _this7._state !== 'started') {\n return;\n }\n var moduleImportOptimisticUpdates = _this7._processOptimisticModuleImport(operation, moduleImportPayload);\n moduleImportOptimisticUpdates.forEach(function (update) {\n return _this7._getPublishQueueAndSaveActor().applyUpdate(update);\n });\n if (_this7._optimisticUpdates == null) {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'OperationExecutor: Unexpected ModuleImport optimistic ' + 'update in operation %s.' + _this7._operation.request.node.params.name) : void 0;\n } else {\n var _this$_optimisticUpda;\n (_this$_optimisticUpda = _this7._optimisticUpdates).push.apply(_this$_optimisticUpda, (0, _toConsumableArray2[\"default\"])(moduleImportOptimisticUpdates));\n _this7._runPublishQueue();\n }\n });\n };\n _proto._processResponses = function _processResponses(responses) {\n var _this8 = this;\n if (this._optimisticUpdates !== null) {\n this._optimisticUpdates.forEach(function (update) {\n _this8._getPublishQueueAndSaveActor().revertUpdate(update);\n });\n this._optimisticUpdates = null;\n }\n this._incrementalPayloadsPending = false;\n this._incrementalResults.clear();\n this._source.clear();\n return responses.map(function (payloadPart) {\n var relayPayload = _this8._normalizeResponse(payloadPart, _this8._operation.root, ROOT_TYPE, {\n actorIdentifier: _this8._actorIdentifier,\n getDataID: _this8._getDataID,\n path: [],\n treatMissingFieldsAsNull: _this8._treatMissingFieldsAsNull,\n shouldProcessClientComponents: _this8._shouldProcessClientComponents\n });\n _this8._getPublishQueueAndSaveActor().commitPayload(_this8._operation, relayPayload, _this8._updater);\n return relayPayload;\n });\n };\n _proto._processPayloadFollowups = function _processPayloadFollowups(payloads) {\n var _this9 = this;\n if (this._state === 'completed') {\n return;\n }\n payloads.forEach(function (payload) {\n var incrementalPlaceholders = payload.incrementalPlaceholders,\n followupPayloads = payload.followupPayloads,\n isFinal = payload.isFinal;\n _this9._state = isFinal ? 'loading_final' : 'loading_incremental';\n _this9._updateActiveState();\n if (isFinal) {\n _this9._incrementalPayloadsPending = false;\n }\n if (followupPayloads && followupPayloads.length !== 0) {\n followupPayloads.forEach(function (followupPayload) {\n var _followupPayload$acto;\n var prevActorIdentifier = _this9._actorIdentifier;\n _this9._actorIdentifier = (_followupPayload$acto = followupPayload.actorIdentifier) !== null && _followupPayload$acto !== void 0 ? _followupPayload$acto : _this9._actorIdentifier;\n _this9._processFollowupPayload(followupPayload);\n _this9._actorIdentifier = prevActorIdentifier;\n });\n }\n if (incrementalPlaceholders && incrementalPlaceholders.length !== 0) {\n _this9._incrementalPayloadsPending = _this9._state !== 'loading_final';\n incrementalPlaceholders.forEach(function (incrementalPlaceholder) {\n var _incrementalPlacehold;\n var prevActorIdentifier = _this9._actorIdentifier;\n _this9._actorIdentifier = (_incrementalPlacehold = incrementalPlaceholder.actorIdentifier) !== null && _incrementalPlacehold !== void 0 ? _incrementalPlacehold : _this9._actorIdentifier;\n _this9._processIncrementalPlaceholder(payload, incrementalPlaceholder);\n _this9._actorIdentifier = prevActorIdentifier;\n });\n if (_this9._isClientPayload || _this9._state === 'loading_final') {\n process.env.NODE_ENV !== \"production\" ? warning(_this9._isClientPayload, 'RelayModernEnvironment: Operation `%s` contains @defer/@stream ' + 'directives but was executed in non-streaming mode. See ' + 'https://fburl.com/relay-incremental-delivery-non-streaming-warning.', _this9._operation.request.node.params.name) : void 0;\n var relayPayloads = [];\n incrementalPlaceholders.forEach(function (placeholder) {\n if (placeholder.kind === 'defer') {\n relayPayloads.push(_this9._processDeferResponse(placeholder.label, placeholder.path, placeholder, {\n data: placeholder.data\n }));\n }\n });\n if (relayPayloads.length > 0) {\n _this9._processPayloadFollowups(relayPayloads);\n }\n }\n }\n });\n };\n _proto._maybeCompleteSubscriptionOperationTracking = function _maybeCompleteSubscriptionOperationTracking() {\n if (!this._isSubscriptionOperation) {\n return;\n }\n if (this._pendingModulePayloadsCount === 0 && this._incrementalPayloadsPending === false) {\n this._completeOperationTracker();\n }\n };\n _proto._processFollowupPayload = function _processFollowupPayload(followupPayload) {\n var _this10 = this;\n switch (followupPayload.kind) {\n case 'ModuleImportPayload':\n var operationLoader = this._expectOperationLoader();\n var node = operationLoader.get(followupPayload.operationReference);\n if (node != null) {\n this._processFollowupPayloadWithNormalizationNode(followupPayload, getOperation(node));\n } else {\n var id = this._nextSubscriptionId++;\n this._pendingModulePayloadsCount++;\n var decrementPendingCount = function decrementPendingCount() {\n _this10._pendingModulePayloadsCount--;\n _this10._maybeCompleteSubscriptionOperationTracking();\n };\n var networkObservable = RelayObservable.from(new Promise(function (resolve, reject) {\n operationLoader.load(followupPayload.operationReference).then(resolve, reject);\n }));\n RelayObservable.create(function (sink) {\n var cancellationToken;\n var subscription = networkObservable.subscribe({\n next: function next(loadedNode) {\n if (loadedNode != null) {\n var publishModuleImportPayload = function publishModuleImportPayload() {\n try {\n var operation = getOperation(loadedNode);\n var batchAsyncModuleUpdatesFN = RelayFeatureFlags.BATCH_ASYNC_MODULE_UPDATES_FN;\n var shouldScheduleAsyncStoreUpdate = batchAsyncModuleUpdatesFN != null && _this10._pendingModulePayloadsCount > 1;\n var _withDuration2 = withDuration(function () {\n _this10._handleFollowupPayload(followupPayload, operation);\n if (shouldScheduleAsyncStoreUpdate) {\n _this10._scheduleAsyncStoreUpdate(batchAsyncModuleUpdatesFN, sink.complete);\n } else {\n var updatedOwners = _this10._runPublishQueue();\n _this10._updateOperationTracker(updatedOwners);\n }\n }),\n duration = _withDuration2[0];\n _this10._log({\n name: 'execute.async.module',\n executeId: _this10._executeId,\n operationName: operation.name,\n duration: duration\n });\n if (!shouldScheduleAsyncStoreUpdate) {\n sink.complete();\n }\n } catch (error) {\n sink.error(error);\n }\n };\n var scheduler = _this10._scheduler;\n if (scheduler == null) {\n publishModuleImportPayload();\n } else {\n cancellationToken = scheduler.schedule(publishModuleImportPayload);\n }\n } else {\n sink.complete();\n }\n },\n error: sink.error\n });\n return function () {\n subscription.unsubscribe();\n if (_this10._scheduler != null && cancellationToken != null) {\n _this10._scheduler.cancel(cancellationToken);\n }\n };\n }).subscribe({\n complete: function complete() {\n _this10._complete(id);\n decrementPendingCount();\n },\n error: function error(_error4) {\n _this10._error(_error4);\n decrementPendingCount();\n },\n start: function start(subscription) {\n return _this10._start(id, subscription);\n }\n });\n }\n break;\n case 'ActorPayload':\n this._processFollowupPayloadWithNormalizationNode(followupPayload, followupPayload.node);\n break;\n default:\n followupPayload;\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'OperationExecutor: Unexpected followup kind `%s`.', followupPayload.kind) : invariant(false) : void 0;\n }\n };\n _proto._processFollowupPayloadWithNormalizationNode = function _processFollowupPayloadWithNormalizationNode(followupPayload, normalizationNode) {\n this._handleFollowupPayload(followupPayload, normalizationNode);\n this._maybeCompleteSubscriptionOperationTracking();\n };\n _proto._handleFollowupPayload = function _handleFollowupPayload(followupPayload, normalizationNode) {\n var relayPayload = this._normalizeFollowupPayload(followupPayload, normalizationNode);\n this._getPublishQueueAndSaveActor().commitPayload(this._operation, relayPayload);\n this._processPayloadFollowups([relayPayload]);\n };\n _proto._processIncrementalPlaceholder = function _processIncrementalPlaceholder(relayPayload, placeholder) {\n var _relayPayload$fieldPa;\n var label = placeholder.label,\n path = placeholder.path;\n var pathKey = path.map(String).join('.');\n var resultForLabel = this._incrementalResults.get(label);\n if (resultForLabel == null) {\n resultForLabel = new Map();\n this._incrementalResults.set(label, resultForLabel);\n }\n var resultForPath = resultForLabel.get(pathKey);\n var pendingResponses = resultForPath != null && resultForPath.kind === 'response' ? resultForPath.responses : null;\n resultForLabel.set(pathKey, {\n kind: 'placeholder',\n placeholder: placeholder\n });\n var parentID;\n if (placeholder.kind === 'stream') {\n parentID = placeholder.parentID;\n } else if (placeholder.kind === 'defer') {\n parentID = placeholder.selector.dataID;\n } else {\n placeholder;\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'OperationExecutor: Unsupported incremental placeholder kind `%s`.', placeholder.kind) : invariant(false) : void 0;\n }\n var parentRecord = relayPayload.source.get(parentID);\n var parentPayloads = ((_relayPayload$fieldPa = relayPayload.fieldPayloads) !== null && _relayPayload$fieldPa !== void 0 ? _relayPayload$fieldPa : []).filter(function (fieldPayload) {\n var fieldID = generateClientID(fieldPayload.dataID, fieldPayload.fieldKey);\n return fieldPayload.dataID === parentID || fieldID === parentID;\n });\n !(parentRecord != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'OperationExecutor: Expected record `%s` to exist.', parentID) : invariant(false) : void 0;\n var nextParentRecord;\n var nextParentPayloads;\n var previousParentEntry = this._source.get(parentID);\n if (previousParentEntry != null) {\n nextParentRecord = RelayModernRecord.update(previousParentEntry.record, parentRecord);\n var handlePayloads = new Map();\n var dedupePayload = function dedupePayload(payload) {\n var key = stableStringify(payload);\n handlePayloads.set(key, payload);\n };\n previousParentEntry.fieldPayloads.forEach(dedupePayload);\n parentPayloads.forEach(dedupePayload);\n nextParentPayloads = Array.from(handlePayloads.values());\n } else {\n nextParentRecord = parentRecord;\n nextParentPayloads = parentPayloads;\n }\n this._source.set(parentID, {\n record: nextParentRecord,\n fieldPayloads: nextParentPayloads\n });\n if (pendingResponses != null) {\n var payloadFollowups = this._processIncrementalResponses(pendingResponses);\n this._processPayloadFollowups(payloadFollowups);\n }\n };\n _proto._processIncrementalResponses = function _processIncrementalResponses(incrementalResponses) {\n var _this11 = this;\n var relayPayloads = [];\n incrementalResponses.forEach(function (incrementalResponse) {\n var label = incrementalResponse.label,\n path = incrementalResponse.path,\n response = incrementalResponse.response;\n var resultForLabel = _this11._incrementalResults.get(label);\n if (resultForLabel == null) {\n resultForLabel = new Map();\n _this11._incrementalResults.set(label, resultForLabel);\n }\n if (label.indexOf('$defer$') !== -1) {\n var pathKey = path.map(String).join('.');\n var resultForPath = resultForLabel.get(pathKey);\n if (resultForPath == null) {\n resultForPath = {\n kind: 'response',\n responses: [incrementalResponse]\n };\n resultForLabel.set(pathKey, resultForPath);\n return;\n } else if (resultForPath.kind === 'response') {\n resultForPath.responses.push(incrementalResponse);\n return;\n }\n var placeholder = resultForPath.placeholder;\n !(placeholder.kind === 'defer') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'OperationExecutor: Expected data for path `%s` for label `%s` ' + 'to be data for @defer, was `@%s`.', pathKey, label, placeholder.kind) : invariant(false) : void 0;\n relayPayloads.push(_this11._processDeferResponse(label, path, placeholder, response));\n } else {\n var _pathKey = path.slice(0, -2).map(String).join('.');\n var _resultForPath = resultForLabel.get(_pathKey);\n if (_resultForPath == null) {\n _resultForPath = {\n kind: 'response',\n responses: [incrementalResponse]\n };\n resultForLabel.set(_pathKey, _resultForPath);\n return;\n } else if (_resultForPath.kind === 'response') {\n _resultForPath.responses.push(incrementalResponse);\n return;\n }\n var _placeholder = _resultForPath.placeholder;\n !(_placeholder.kind === 'stream') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'OperationExecutor: Expected data for path `%s` for label `%s` ' + 'to be data for @stream, was `@%s`.', _pathKey, label, _placeholder.kind) : invariant(false) : void 0;\n relayPayloads.push(_this11._processStreamResponse(label, path, _placeholder, response));\n }\n });\n return relayPayloads;\n };\n _proto._processDeferResponse = function _processDeferResponse(label, path, placeholder, response) {\n var _placeholder$actorIde;\n var parentID = placeholder.selector.dataID;\n var prevActorIdentifier = this._actorIdentifier;\n this._actorIdentifier = (_placeholder$actorIde = placeholder.actorIdentifier) !== null && _placeholder$actorIde !== void 0 ? _placeholder$actorIde : this._actorIdentifier;\n var relayPayload = this._normalizeResponse(response, placeholder.selector, placeholder.typeName, {\n actorIdentifier: this._actorIdentifier,\n getDataID: this._getDataID,\n path: placeholder.path,\n treatMissingFieldsAsNull: this._treatMissingFieldsAsNull,\n shouldProcessClientComponents: this._shouldProcessClientComponents\n });\n this._getPublishQueueAndSaveActor().commitPayload(this._operation, relayPayload);\n var parentEntry = this._source.get(parentID);\n !(parentEntry != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'OperationExecutor: Expected the parent record `%s` for @defer ' + 'data to exist.', parentID) : invariant(false) : void 0;\n var fieldPayloads = parentEntry.fieldPayloads;\n if (fieldPayloads.length !== 0) {\n var _response$extensions2;\n var handleFieldsRelayPayload = {\n errors: null,\n fieldPayloads: fieldPayloads,\n incrementalPlaceholders: null,\n followupPayloads: null,\n source: RelayRecordSource.create(),\n isFinal: ((_response$extensions2 = response.extensions) === null || _response$extensions2 === void 0 ? void 0 : _response$extensions2.is_final) === true\n };\n this._getPublishQueueAndSaveActor().commitPayload(this._operation, handleFieldsRelayPayload);\n }\n this._actorIdentifier = prevActorIdentifier;\n return relayPayload;\n };\n _proto._processStreamResponse = function _processStreamResponse(label, path, placeholder, response) {\n var parentID = placeholder.parentID,\n node = placeholder.node,\n variables = placeholder.variables,\n actorIdentifier = placeholder.actorIdentifier;\n var prevActorIdentifier = this._actorIdentifier;\n this._actorIdentifier = actorIdentifier !== null && actorIdentifier !== void 0 ? actorIdentifier : this._actorIdentifier;\n var field = node.selections[0];\n !(field != null && field.kind === 'LinkedField' && field.plural === true) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'OperationExecutor: Expected @stream to be used on a plural field.') : invariant(false) : void 0;\n var _this$_normalizeStrea = this._normalizeStreamItem(response, parentID, field, variables, path, placeholder.path),\n fieldPayloads = _this$_normalizeStrea.fieldPayloads,\n itemID = _this$_normalizeStrea.itemID,\n itemIndex = _this$_normalizeStrea.itemIndex,\n prevIDs = _this$_normalizeStrea.prevIDs,\n relayPayload = _this$_normalizeStrea.relayPayload,\n storageKey = _this$_normalizeStrea.storageKey;\n this._getPublishQueueAndSaveActor().commitPayload(this._operation, relayPayload, function (store) {\n var currentParentRecord = store.get(parentID);\n if (currentParentRecord == null) {\n return;\n }\n var currentItems = currentParentRecord.getLinkedRecords(storageKey);\n if (currentItems == null) {\n return;\n }\n if (currentItems.length !== prevIDs.length || currentItems.some(function (currentItem, index) {\n return prevIDs[index] !== (currentItem && currentItem.getDataID());\n })) {\n return;\n }\n var nextItems = (0, _toConsumableArray2[\"default\"])(currentItems);\n nextItems[itemIndex] = store.get(itemID);\n currentParentRecord.setLinkedRecords(nextItems, storageKey);\n });\n if (fieldPayloads.length !== 0) {\n var handleFieldsRelayPayload = {\n errors: null,\n fieldPayloads: fieldPayloads,\n incrementalPlaceholders: null,\n followupPayloads: null,\n source: RelayRecordSource.create(),\n isFinal: false\n };\n this._getPublishQueueAndSaveActor().commitPayload(this._operation, handleFieldsRelayPayload);\n }\n this._actorIdentifier = prevActorIdentifier;\n return relayPayload;\n };\n _proto._normalizeStreamItem = function _normalizeStreamItem(response, parentID, field, variables, path, normalizationPath) {\n var _field$alias, _field$concreteType, _ref, _this$_getDataID;\n var data = response.data;\n !(typeof data === 'object') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'OperationExecutor: Expected the GraphQL @stream payload `data` ' + 'value to be an object.') : invariant(false) : void 0;\n var responseKey = (_field$alias = field.alias) !== null && _field$alias !== void 0 ? _field$alias : field.name;\n var storageKey = getStorageKey(field, variables);\n var parentEntry = this._source.get(parentID);\n !(parentEntry != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'OperationExecutor: Expected the parent record `%s` for @stream ' + 'data to exist.', parentID) : invariant(false) : void 0;\n var parentRecord = parentEntry.record,\n fieldPayloads = parentEntry.fieldPayloads;\n var prevIDs = RelayModernRecord.getLinkedRecordIDs(parentRecord, storageKey);\n !(prevIDs != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'OperationExecutor: Expected record `%s` to have fetched field ' + '`%s` with @stream.', parentID, field.name) : invariant(false) : void 0;\n var finalPathEntry = path[path.length - 1];\n var itemIndex = parseInt(finalPathEntry, 10);\n !(itemIndex === finalPathEntry && itemIndex >= 0) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'OperationExecutor: Expected path for @stream to end in a ' + 'positive integer index, got `%s`', finalPathEntry) : invariant(false) : void 0;\n var typeName = (_field$concreteType = field.concreteType) !== null && _field$concreteType !== void 0 ? _field$concreteType : data[TYPENAME_KEY];\n !(typeof typeName === 'string') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'OperationExecutor: Expected @stream field `%s` to have a ' + '__typename.', field.name) : invariant(false) : void 0;\n var itemID = (_ref = (_this$_getDataID = this._getDataID(data, typeName)) !== null && _this$_getDataID !== void 0 ? _this$_getDataID : prevIDs === null || prevIDs === void 0 ? void 0 : prevIDs[itemIndex]) !== null && _ref !== void 0 ? _ref : generateClientID(parentID, storageKey, itemIndex);\n !(typeof itemID === 'string') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'OperationExecutor: Expected id of elements of field `%s` to ' + 'be strings.', storageKey) : invariant(false) : void 0;\n var selector = createNormalizationSelector(field, itemID, variables);\n var nextParentRecord = RelayModernRecord.clone(parentRecord);\n var nextIDs = (0, _toConsumableArray2[\"default\"])(prevIDs);\n nextIDs[itemIndex] = itemID;\n RelayModernRecord.setLinkedRecordIDs(nextParentRecord, storageKey, nextIDs);\n this._source.set(parentID, {\n record: nextParentRecord,\n fieldPayloads: fieldPayloads\n });\n var relayPayload = this._normalizeResponse(response, selector, typeName, {\n actorIdentifier: this._actorIdentifier,\n getDataID: this._getDataID,\n path: [].concat((0, _toConsumableArray2[\"default\"])(normalizationPath), [responseKey, String(itemIndex)]),\n treatMissingFieldsAsNull: this._treatMissingFieldsAsNull,\n shouldProcessClientComponents: this._shouldProcessClientComponents\n });\n return {\n fieldPayloads: fieldPayloads,\n itemID: itemID,\n itemIndex: itemIndex,\n prevIDs: prevIDs,\n relayPayload: relayPayload,\n storageKey: storageKey\n };\n };\n _proto._scheduleAsyncStoreUpdate = function _scheduleAsyncStoreUpdate(scheduleFn, completeFn) {\n var _this12 = this;\n this._completeFns.push(completeFn);\n if (this._asyncStoreUpdateDisposable != null) {\n return;\n }\n this._asyncStoreUpdateDisposable = scheduleFn(function () {\n _this12._asyncStoreUpdateDisposable = null;\n var updatedOwners = _this12._runPublishQueue();\n _this12._updateOperationTracker(updatedOwners);\n var _iterator2 = (0, _createForOfIteratorHelper2[\"default\"])(_this12._completeFns),\n _step2;\n try {\n for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n var complete = _step2.value;\n complete();\n }\n } catch (err) {\n _iterator2.e(err);\n } finally {\n _iterator2.f();\n }\n _this12._completeFns = [];\n });\n };\n _proto._updateOperationTracker = function _updateOperationTracker(updatedOwners) {\n if (updatedOwners != null && updatedOwners.length > 0) {\n this._operationTracker.update(this._operation.request, new Set(updatedOwners));\n }\n };\n _proto._completeOperationTracker = function _completeOperationTracker() {\n this._operationTracker.complete(this._operation.request);\n };\n _proto._getPublishQueueAndSaveActor = function _getPublishQueueAndSaveActor() {\n this._seenActors.add(this._actorIdentifier);\n return this._getPublishQueue(this._actorIdentifier);\n };\n _proto._getActorsToVisit = function _getActorsToVisit() {\n if (this._seenActors.size === 0) {\n return new Set([this._actorIdentifier]);\n } else {\n return this._seenActors;\n }\n };\n _proto._runPublishQueue = function _runPublishQueue(operation) {\n var updatedOwners = new Set();\n var _iterator3 = (0, _createForOfIteratorHelper2[\"default\"])(this._getActorsToVisit()),\n _step3;\n try {\n for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {\n var actorIdentifier = _step3.value;\n var owners = this._getPublishQueue(actorIdentifier).run(operation);\n owners.forEach(function (owner) {\n return updatedOwners.add(owner);\n });\n }\n } catch (err) {\n _iterator3.e(err);\n } finally {\n _iterator3.f();\n }\n return Array.from(updatedOwners);\n };\n _proto._retainData = function _retainData() {\n var _iterator4 = (0, _createForOfIteratorHelper2[\"default\"])(this._getActorsToVisit()),\n _step4;\n try {\n for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {\n var actorIdentifier = _step4.value;\n if (!this._retainDisposables.has(actorIdentifier)) {\n this._retainDisposables.set(actorIdentifier, this._getStore(actorIdentifier).retain(this._operation));\n }\n }\n } catch (err) {\n _iterator4.e(err);\n } finally {\n _iterator4.f();\n }\n };\n _proto._disposeRetainedData = function _disposeRetainedData() {\n var _iterator5 = (0, _createForOfIteratorHelper2[\"default\"])(this._retainDisposables.values()),\n _step5;\n try {\n for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {\n var disposable = _step5.value;\n disposable.dispose();\n }\n } catch (err) {\n _iterator5.e(err);\n } finally {\n _iterator5.f();\n }\n this._retainDisposables.clear();\n };\n _proto._expectOperationLoader = function _expectOperationLoader() {\n var operationLoader = this._operationLoader;\n !operationLoader ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'OperationExecutor: Expected an operationLoader to be ' + 'configured when using `@match`.') : invariant(false) : void 0;\n return operationLoader;\n };\n return Executor;\n}();\nfunction partitionGraphQLResponses(responses) {\n var nonIncrementalResponses = [];\n var incrementalResponses = [];\n responses.forEach(function (response) {\n if (response.path != null || response.label != null) {\n var label = response.label,\n path = response.path;\n if (label == null || path == null) {\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'OperationExecutor: invalid incremental payload, expected ' + '`path` and `label` to either both be null/undefined, or ' + '`path` to be an `Array` and `label` to be a ' + '`string`.') : invariant(false) : void 0;\n }\n incrementalResponses.push({\n label: label,\n path: path,\n response: response\n });\n } else {\n nonIncrementalResponses.push(response);\n }\n });\n return [nonIncrementalResponses, incrementalResponses];\n}\nfunction stableStringify(value) {\n var _JSON$stringify;\n return (_JSON$stringify = JSON.stringify(stableCopy(value))) !== null && _JSON$stringify !== void 0 ? _JSON$stringify : '';\n}\nfunction validateOptimisticResponsePayload(payload) {\n var incrementalPlaceholders = payload.incrementalPlaceholders;\n if (incrementalPlaceholders != null && incrementalPlaceholders.length !== 0) {\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'OperationExecutor: optimistic responses cannot be returned ' + 'for operations that use incremental data delivery (@defer, ' + '@stream, and @stream_connection).') : invariant(false) : void 0;\n }\n}\nmodule.exports = {\n execute: execute\n};","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _objectSpread2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar _require = require('./RelayStoreUtils'),\n getArgumentValues = _require.getArgumentValues;\nvar invariant = require('invariant');\nfunction getFragmentVariables(fragment, rootVariables, argumentVariables) {\n if (fragment.argumentDefinitions == null) {\n return argumentVariables;\n }\n var variables;\n fragment.argumentDefinitions.forEach(function (definition) {\n if (argumentVariables.hasOwnProperty(definition.name)) {\n return;\n }\n variables = variables || (0, _objectSpread2[\"default\"])({}, argumentVariables);\n switch (definition.kind) {\n case 'LocalArgument':\n variables[definition.name] = definition.defaultValue;\n break;\n case 'RootArgument':\n if (!rootVariables.hasOwnProperty(definition.name)) {\n variables[definition.name] = undefined;\n break;\n }\n variables[definition.name] = rootVariables[definition.name];\n break;\n default:\n definition;\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayConcreteVariables: Unexpected node kind `%s` in fragment `%s`.', definition.kind, fragment.name) : invariant(false) : void 0;\n }\n });\n return variables || argumentVariables;\n}\nfunction getOperationVariables(operation, providedVariables, variables) {\n var operationVariables = {};\n operation.argumentDefinitions.forEach(function (def) {\n var value = def.defaultValue;\n if (variables[def.name] != null) {\n value = variables[def.name];\n }\n operationVariables[def.name] = value;\n });\n if (providedVariables != null) {\n Object.keys(providedVariables).forEach(function (varName) {\n operationVariables[varName] = providedVariables[varName].get();\n });\n }\n return operationVariables;\n}\nfunction getLocalVariables(currentVariables, argumentDefinitions, args) {\n if (argumentDefinitions == null) {\n return currentVariables;\n }\n var nextVariables = (0, _objectSpread2[\"default\"])({}, currentVariables);\n var nextArgs = args ? getArgumentValues(args, currentVariables) : {};\n argumentDefinitions.forEach(function (def) {\n var _nextArgs$def$name;\n var value = (_nextArgs$def$name = nextArgs[def.name]) !== null && _nextArgs$def$name !== void 0 ? _nextArgs$def$name : def.defaultValue;\n nextVariables[def.name] = value;\n });\n return nextVariables;\n}\nmodule.exports = {\n getLocalVariables: getLocalVariables,\n getFragmentVariables: getFragmentVariables,\n getOperationVariables: getOperationVariables\n};","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _objectSpread2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar _objectWithoutPropertiesLoose2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectWithoutPropertiesLoose\"));\nvar _createForOfIteratorHelper2 = _interopRequireDefault(require(\"@babel/runtime/helpers/createForOfIteratorHelper\"));\nvar _inheritsLoose2 = _interopRequireDefault(require(\"@babel/runtime/helpers/inheritsLoose\"));\nvar _wrapNativeSuper2 = _interopRequireDefault(require(\"@babel/runtime/helpers/wrapNativeSuper\"));\nvar _toConsumableArray2 = _interopRequireDefault(require(\"@babel/runtime/helpers/toConsumableArray\"));\nvar _excluded = [\"path\", \"locations\"];\nvar RelayFeatureFlags = require('../util/RelayFeatureFlags');\nvar SELF = Symbol('$SELF');\nvar RelayFieldError = /*#__PURE__*/function (_Error) {\n (0, _inheritsLoose2[\"default\"])(RelayFieldError, _Error);\n function RelayFieldError(message) {\n var _this;\n var errors = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];\n _this = _Error.call(this, message) || this;\n _this.name = 'RelayFieldError';\n _this.message = message;\n _this.errors = errors;\n return _this;\n }\n return RelayFieldError;\n}( /*#__PURE__*/(0, _wrapNativeSuper2[\"default\"])(Error));\nfunction buildErrorTrie(errors) {\n if (errors == null) {\n return null;\n }\n if (!RelayFeatureFlags.ENABLE_FIELD_ERROR_HANDLING) {\n return null;\n }\n var trie = new Map();\n var _iterator = (0, _createForOfIteratorHelper2[\"default\"])(errors),\n _step;\n try {\n ERRORS: for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var _step$value = _step.value,\n path = _step$value.path,\n _ = _step$value.locations,\n error = (0, _objectWithoutPropertiesLoose2[\"default\"])(_step$value, _excluded);\n if (path == null) {\n continue;\n }\n var length = path.length;\n if (length === 0) {\n continue;\n }\n var lastIndex = length - 1;\n var currentTrie = trie;\n for (var index = 0; index < lastIndex; index++) {\n var key = path[index];\n var existingValue = currentTrie.get(key);\n if (existingValue instanceof Map) {\n currentTrie = existingValue;\n continue;\n }\n var newValue = new Map();\n if (Array.isArray(existingValue)) {\n newValue.set(SELF, existingValue);\n }\n currentTrie.set(key, newValue);\n currentTrie = newValue;\n }\n var lastKey = path[lastIndex];\n var container = currentTrie.get(lastKey);\n if (container instanceof Map) {\n currentTrie = container;\n container = currentTrie.get(lastKey);\n lastKey = SELF;\n }\n if (Array.isArray(container)) {\n container.push(error);\n } else {\n currentTrie.set(lastKey, [error]);\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n return trie;\n}\nfunction getErrorsByKey(trie, key) {\n var value = trie.get(key);\n if (value == null) {\n return null;\n }\n if (Array.isArray(value)) {\n return value;\n }\n var errors = [];\n recursivelyCopyErrorsIntoArray(value, errors);\n return errors;\n}\nfunction recursivelyCopyErrorsIntoArray(trieOrSet, errors) {\n var _iterator2 = (0, _createForOfIteratorHelper2[\"default\"])(trieOrSet),\n _step2;\n try {\n for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n var _step2$value = _step2.value,\n childKey = _step2$value[0],\n value = _step2$value[1];\n var oldLength = errors.length;\n if (Array.isArray(value)) {\n errors.push.apply(errors, (0, _toConsumableArray2[\"default\"])(value));\n } else {\n recursivelyCopyErrorsIntoArray(value, errors);\n }\n if (childKey === SELF) {\n continue;\n }\n var newLength = errors.length;\n for (var index = oldLength; index < newLength; index++) {\n var error = errors[index];\n if (error.path == null) {\n errors[index] = (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, error), {}, {\n path: [childKey]\n });\n } else {\n error.path.unshift(childKey);\n }\n }\n }\n } catch (err) {\n _iterator2.e(err);\n } finally {\n _iterator2.f();\n }\n}\nfunction getNestedErrorTrieByKey(trie, key) {\n var value = trie.get(key);\n if (value instanceof Map) {\n return value;\n }\n return null;\n}\nmodule.exports = {\n SELF: SELF,\n buildErrorTrie: buildErrorTrie,\n getNestedErrorTrieByKey: getNestedErrorTrieByKey,\n getErrorsByKey: getErrorsByKey,\n RelayFieldError: RelayFieldError\n};","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _objectSpread2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar RelayDefaultHandlerProvider = require('../handlers/RelayDefaultHandlerProvider');\nvar _require = require('../multi-actor-environment/ActorIdentifier'),\n INTERNAL_ACTOR_IDENTIFIER_DO_NOT_USE = _require.INTERNAL_ACTOR_IDENTIFIER_DO_NOT_USE,\n assertInternalActorIdentifier = _require.assertInternalActorIdentifier;\nvar RelayObservable = require('../network/RelayObservable');\nvar wrapNetworkWithLogObserver = require('../network/wrapNetworkWithLogObserver');\nvar RelayOperationTracker = require('../store/RelayOperationTracker');\nvar registerEnvironmentWithDevTools = require('../util/registerEnvironmentWithDevTools');\nvar defaultGetDataID = require('./defaultGetDataID');\nvar defaultRelayFieldLogger = require('./defaultRelayFieldLogger');\nvar normalizeResponse = require('./normalizeResponse');\nvar OperationExecutor = require('./OperationExecutor');\nvar RelayPublishQueue = require('./RelayPublishQueue');\nvar RelayRecordSource = require('./RelayRecordSource');\nvar invariant = require('invariant');\nvar RelayModernEnvironment = /*#__PURE__*/function () {\n function RelayModernEnvironment(config) {\n var _this = this;\n var _config$log, _config$relayFieldLog, _config$UNSTABLE_defa, _config$getDataID, _config$missingFieldH, _config$handlerProvid, _config$scheduler, _config$isServer, _config$normalizeResp, _config$operationTrac;\n this.configName = config.configName;\n this._treatMissingFieldsAsNull = config.treatMissingFieldsAsNull === true;\n var operationLoader = config.operationLoader;\n if (process.env.NODE_ENV !== \"production\") {\n if (operationLoader != null) {\n !(typeof operationLoader === 'object' && typeof operationLoader.get === 'function' && typeof operationLoader.load === 'function') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayModernEnvironment: Expected `operationLoader` to be an object ' + 'with get() and load() functions, got `%s`.', operationLoader) : invariant(false) : void 0;\n }\n }\n this.__log = (_config$log = config.log) !== null && _config$log !== void 0 ? _config$log : emptyFunction;\n this.relayFieldLogger = (_config$relayFieldLog = config.relayFieldLogger) !== null && _config$relayFieldLog !== void 0 ? _config$relayFieldLog : defaultRelayFieldLogger;\n this._defaultRenderPolicy = (_config$UNSTABLE_defa = config.UNSTABLE_defaultRenderPolicy) !== null && _config$UNSTABLE_defa !== void 0 ? _config$UNSTABLE_defa : 'partial';\n this._operationLoader = operationLoader;\n this._operationExecutions = new Map();\n this._network = wrapNetworkWithLogObserver(this, config.network);\n this._getDataID = (_config$getDataID = config.getDataID) !== null && _config$getDataID !== void 0 ? _config$getDataID : defaultGetDataID;\n this._missingFieldHandlers = (_config$missingFieldH = config.missingFieldHandlers) !== null && _config$missingFieldH !== void 0 ? _config$missingFieldH : [];\n this._publishQueue = new RelayPublishQueue(config.store, (_config$handlerProvid = config.handlerProvider) !== null && _config$handlerProvid !== void 0 ? _config$handlerProvid : RelayDefaultHandlerProvider, this._getDataID, this._missingFieldHandlers);\n this._scheduler = (_config$scheduler = config.scheduler) !== null && _config$scheduler !== void 0 ? _config$scheduler : null;\n this._store = config.store;\n this.options = config.options;\n this._isServer = (_config$isServer = config.isServer) !== null && _config$isServer !== void 0 ? _config$isServer : false;\n this._normalizeResponse = (_config$normalizeResp = config.normalizeResponse) !== null && _config$normalizeResp !== void 0 ? _config$normalizeResp : normalizeResponse;\n this.__setNet = function (newNet) {\n return _this._network = wrapNetworkWithLogObserver(_this, newNet);\n };\n if (process.env.NODE_ENV !== \"production\") {\n var _require2 = require('./StoreInspector'),\n inspect = _require2.inspect;\n this.DEBUG_inspect = function (dataID) {\n return inspect(_this, dataID);\n };\n }\n this._operationTracker = (_config$operationTrac = config.operationTracker) !== null && _config$operationTrac !== void 0 ? _config$operationTrac : new RelayOperationTracker();\n this._shouldProcessClientComponents = config.shouldProcessClientComponents;\n registerEnvironmentWithDevTools(this);\n }\n var _proto = RelayModernEnvironment.prototype;\n _proto.getStore = function getStore() {\n return this._store;\n };\n _proto.getNetwork = function getNetwork() {\n return this._network;\n };\n _proto.getOperationTracker = function getOperationTracker() {\n return this._operationTracker;\n };\n _proto.getScheduler = function getScheduler() {\n return this._scheduler;\n };\n _proto.isRequestActive = function isRequestActive(requestIdentifier) {\n var activeState = this._operationExecutions.get(requestIdentifier);\n return activeState === 'active';\n };\n _proto.UNSTABLE_getDefaultRenderPolicy = function UNSTABLE_getDefaultRenderPolicy() {\n return this._defaultRenderPolicy;\n };\n _proto.applyUpdate = function applyUpdate(optimisticUpdate) {\n var _this2 = this;\n var dispose = function dispose() {\n _this2._scheduleUpdates(function () {\n _this2._publishQueue.revertUpdate(optimisticUpdate);\n _this2._publishQueue.run();\n });\n };\n this._scheduleUpdates(function () {\n _this2._publishQueue.applyUpdate(optimisticUpdate);\n _this2._publishQueue.run();\n });\n return {\n dispose: dispose\n };\n };\n _proto.revertUpdate = function revertUpdate(update) {\n var _this3 = this;\n this._scheduleUpdates(function () {\n _this3._publishQueue.revertUpdate(update);\n _this3._publishQueue.run();\n });\n };\n _proto.replaceUpdate = function replaceUpdate(update, newUpdate) {\n var _this4 = this;\n this._scheduleUpdates(function () {\n _this4._publishQueue.revertUpdate(update);\n _this4._publishQueue.applyUpdate(newUpdate);\n _this4._publishQueue.run();\n });\n };\n _proto.applyMutation = function applyMutation(optimisticConfig) {\n var subscription = this._execute({\n createSource: function createSource() {\n return RelayObservable.create(function (_sink) {});\n },\n isClientPayload: false,\n operation: optimisticConfig.operation,\n optimisticConfig: optimisticConfig,\n updater: null\n }).subscribe({});\n return {\n dispose: function dispose() {\n return subscription.unsubscribe();\n }\n };\n };\n _proto.check = function check(operation) {\n if (this._missingFieldHandlers.length === 0 && !operationHasClientAbstractTypes(operation)) {\n return this._store.check(operation);\n }\n return this._checkSelectorAndHandleMissingFields(operation, this._missingFieldHandlers);\n };\n _proto.commitPayload = function commitPayload(operation, payload) {\n this._execute({\n createSource: function createSource() {\n return RelayObservable.from({\n data: payload\n });\n },\n isClientPayload: true,\n operation: operation,\n optimisticConfig: null,\n updater: null\n }).subscribe({});\n };\n _proto.commitUpdate = function commitUpdate(updater) {\n var _this5 = this;\n this._scheduleUpdates(function () {\n _this5._publishQueue.commitUpdate(updater);\n _this5._publishQueue.run();\n });\n };\n _proto.lookup = function lookup(readSelector) {\n return this._store.lookup(readSelector);\n };\n _proto.subscribe = function subscribe(snapshot, callback) {\n return this._store.subscribe(snapshot, callback);\n };\n _proto.retain = function retain(operation) {\n return this._store.retain(operation);\n };\n _proto.isServer = function isServer() {\n return this._isServer;\n };\n _proto._checkSelectorAndHandleMissingFields = function _checkSelectorAndHandleMissingFields(operation, handlers) {\n var _this6 = this;\n var target = RelayRecordSource.create();\n var source = this._store.getSource();\n var result = this._store.check(operation, {\n handlers: handlers,\n defaultActorIdentifier: INTERNAL_ACTOR_IDENTIFIER_DO_NOT_USE,\n getSourceForActor: function getSourceForActor(actorIdentifier) {\n assertInternalActorIdentifier(actorIdentifier);\n return source;\n },\n getTargetForActor: function getTargetForActor(actorIdentifier) {\n assertInternalActorIdentifier(actorIdentifier);\n return target;\n }\n });\n if (target.size() > 0) {\n this._scheduleUpdates(function () {\n _this6._publishQueue.commitSource(target);\n _this6._publishQueue.run();\n });\n }\n return result;\n };\n _proto._scheduleUpdates = function _scheduleUpdates(task) {\n var scheduler = this._scheduler;\n if (scheduler != null) {\n scheduler.schedule(task);\n } else {\n task();\n }\n };\n _proto.execute = function execute(_ref) {\n var _this7 = this;\n var operation = _ref.operation;\n return this._execute({\n createSource: function createSource() {\n return _this7.getNetwork().execute(operation.request.node.params, operation.request.variables, operation.request.cacheConfig || {}, null);\n },\n isClientPayload: false,\n operation: operation,\n optimisticConfig: null,\n updater: null\n });\n };\n _proto.executeSubscription = function executeSubscription(_ref2) {\n var _this8 = this;\n var operation = _ref2.operation,\n updater = _ref2.updater;\n return this._execute({\n createSource: function createSource() {\n return _this8.getNetwork().execute(operation.request.node.params, operation.request.variables, operation.request.cacheConfig || {}, null);\n },\n isClientPayload: false,\n operation: operation,\n optimisticConfig: null,\n updater: updater\n });\n };\n _proto.executeMutation = function executeMutation(_ref3) {\n var _this9 = this;\n var operation = _ref3.operation,\n optimisticResponse = _ref3.optimisticResponse,\n optimisticUpdater = _ref3.optimisticUpdater,\n updater = _ref3.updater,\n uploadables = _ref3.uploadables;\n var optimisticConfig;\n if (optimisticResponse || optimisticUpdater) {\n optimisticConfig = {\n operation: operation,\n response: optimisticResponse,\n updater: optimisticUpdater\n };\n }\n return this._execute({\n createSource: function createSource() {\n return _this9.getNetwork().execute(operation.request.node.params, operation.request.variables, (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, operation.request.cacheConfig), {}, {\n force: true\n }), uploadables);\n },\n isClientPayload: false,\n operation: operation,\n optimisticConfig: optimisticConfig,\n updater: updater\n });\n };\n _proto.executeWithSource = function executeWithSource(_ref4) {\n var operation = _ref4.operation,\n source = _ref4.source;\n return this._execute({\n createSource: function createSource() {\n return source;\n },\n isClientPayload: false,\n operation: operation,\n optimisticConfig: null,\n updater: null\n });\n };\n _proto.toJSON = function toJSON() {\n var _this$configName;\n return \"RelayModernEnvironment(\".concat((_this$configName = this.configName) !== null && _this$configName !== void 0 ? _this$configName : '', \")\");\n };\n _proto._execute = function _execute(_ref5) {\n var _this10 = this;\n var createSource = _ref5.createSource,\n isClientPayload = _ref5.isClientPayload,\n operation = _ref5.operation,\n optimisticConfig = _ref5.optimisticConfig,\n updater = _ref5.updater;\n var publishQueue = this._publishQueue;\n var store = this._store;\n return RelayObservable.create(function (sink) {\n var executor = OperationExecutor.execute({\n actorIdentifier: INTERNAL_ACTOR_IDENTIFIER_DO_NOT_USE,\n getDataID: _this10._getDataID,\n isClientPayload: isClientPayload,\n log: _this10.__log,\n operation: operation,\n operationExecutions: _this10._operationExecutions,\n operationLoader: _this10._operationLoader,\n operationTracker: _this10._operationTracker,\n optimisticConfig: optimisticConfig,\n getPublishQueue: function getPublishQueue(actorIdentifier) {\n assertInternalActorIdentifier(actorIdentifier);\n return publishQueue;\n },\n scheduler: _this10._scheduler,\n shouldProcessClientComponents: _this10._shouldProcessClientComponents,\n sink: sink,\n source: createSource(),\n getStore: function getStore(actorIdentifier) {\n assertInternalActorIdentifier(actorIdentifier);\n return store;\n },\n treatMissingFieldsAsNull: _this10._treatMissingFieldsAsNull,\n updater: updater,\n normalizeResponse: _this10._normalizeResponse\n });\n return function () {\n return executor.cancel();\n };\n });\n };\n return RelayModernEnvironment;\n}();\nfunction operationHasClientAbstractTypes(operation) {\n return operation.root.node.kind === 'Operation' && operation.root.node.clientAbstractTypes != null;\n}\nRelayModernEnvironment.prototype['@@RelayModernEnvironment'] = true;\nfunction emptyFunction() {}\nmodule.exports = RelayModernEnvironment;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _objectSpread2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar _defineProperty2 = _interopRequireDefault(require(\"@babel/runtime/helpers/defineProperty\"));\nvar getPendingOperationsForFragment = require('../util/getPendingOperationsForFragment');\nvar handlePotentialSnapshotErrors = require('../util/handlePotentialSnapshotErrors');\nvar isScalarAndEqual = require('../util/isScalarAndEqual');\nvar recycleNodesInto = require('../util/recycleNodesInto');\nvar RelayFeatureFlags = require('../util/RelayFeatureFlags');\nvar _require = require('./RelayModernOperationDescriptor'),\n createRequestDescriptor = _require.createRequestDescriptor;\nvar _require2 = require('./RelayModernSelector'),\n areEqualSelectors = _require2.areEqualSelectors,\n createReaderSelector = _require2.createReaderSelector,\n getSelectorsFromObject = _require2.getSelectorsFromObject;\nvar areEqual = require(\"fbjs/lib/areEqual\");\nvar invariant = require('invariant');\nvar warning = require(\"fbjs/lib/warning\");\nvar RelayModernFragmentSpecResolver = /*#__PURE__*/function () {\n function RelayModernFragmentSpecResolver(context, fragments, props, callback, rootIsQueryRenderer) {\n var _this = this;\n (0, _defineProperty2[\"default\"])(this, \"_onChange\", function () {\n _this._stale = true;\n if (typeof _this._callback === 'function') {\n _this._callback();\n }\n });\n this._callback = callback;\n this._context = context;\n this._data = {};\n this._fragments = fragments;\n this._props = {};\n this._resolvers = {};\n this._stale = false;\n this._rootIsQueryRenderer = rootIsQueryRenderer;\n this.setProps(props);\n }\n var _proto = RelayModernFragmentSpecResolver.prototype;\n _proto.dispose = function dispose() {\n for (var key in this._resolvers) {\n if (this._resolvers.hasOwnProperty(key)) {\n disposeCallback(this._resolvers[key]);\n }\n }\n };\n _proto.resolve = function resolve() {\n if (this._stale) {\n var prevData = this._data;\n var nextData;\n for (var key in this._resolvers) {\n if (this._resolvers.hasOwnProperty(key)) {\n var resolver = this._resolvers[key];\n var prevItem = prevData[key];\n if (resolver) {\n var nextItem = resolver.resolve();\n if (nextData || nextItem !== prevItem) {\n nextData = nextData || (0, _objectSpread2[\"default\"])({}, prevData);\n nextData[key] = nextItem;\n }\n } else {\n var prop = this._props[key];\n var _nextItem = prop !== undefined ? prop : null;\n if (nextData || !isScalarAndEqual(_nextItem, prevItem)) {\n nextData = nextData || (0, _objectSpread2[\"default\"])({}, prevData);\n nextData[key] = _nextItem;\n }\n }\n }\n }\n this._data = nextData || prevData;\n this._stale = false;\n }\n return this._data;\n };\n _proto.setCallback = function setCallback(props, callback) {\n this._callback = callback;\n if (RelayFeatureFlags.ENABLE_CONTAINERS_SUBSCRIBE_ON_COMMIT === true) {\n this.setProps(props);\n }\n };\n _proto.setProps = function setProps(props) {\n this._props = {};\n var ownedSelectors = getSelectorsFromObject(this._fragments, props);\n for (var key in ownedSelectors) {\n if (ownedSelectors.hasOwnProperty(key)) {\n var ownedSelector = ownedSelectors[key];\n var resolver = this._resolvers[key];\n if (ownedSelector == null) {\n if (resolver != null) {\n resolver.dispose();\n }\n resolver = null;\n } else if (ownedSelector.kind === 'PluralReaderSelector') {\n if (resolver == null) {\n resolver = new SelectorListResolver(this._context.environment, this._rootIsQueryRenderer, ownedSelector, this._callback != null, this._onChange);\n } else {\n !(resolver instanceof SelectorListResolver) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayModernFragmentSpecResolver: Expected prop `%s` to always be an array.', key) : invariant(false) : void 0;\n resolver.setSelector(ownedSelector);\n }\n } else {\n if (resolver == null) {\n resolver = new SelectorResolver(this._context.environment, this._rootIsQueryRenderer, ownedSelector, this._callback != null, this._onChange);\n } else {\n !(resolver instanceof SelectorResolver) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayModernFragmentSpecResolver: Expected prop `%s` to always be an object.', key) : invariant(false) : void 0;\n resolver.setSelector(ownedSelector);\n }\n }\n this._props[key] = props[key];\n this._resolvers[key] = resolver;\n }\n }\n this._stale = true;\n };\n _proto.setVariables = function setVariables(variables, request) {\n for (var key in this._resolvers) {\n if (this._resolvers.hasOwnProperty(key)) {\n var resolver = this._resolvers[key];\n if (resolver) {\n resolver.setVariables(variables, request);\n }\n }\n }\n this._stale = true;\n };\n return RelayModernFragmentSpecResolver;\n}();\nvar SelectorResolver = /*#__PURE__*/function () {\n function SelectorResolver(environment, rootIsQueryRenderer, selector, subscribeOnConstruction, callback) {\n var _this2 = this;\n (0, _defineProperty2[\"default\"])(this, \"_onChange\", function (snapshot) {\n _this2._data = snapshot.data;\n _this2._isMissingData = snapshot.isMissingData;\n _this2._missingRequiredFields = snapshot.missingRequiredFields;\n _this2._errorResponseFields = snapshot.errorResponseFields;\n _this2._relayResolverErrors = snapshot.relayResolverErrors;\n _this2._callback();\n });\n var _snapshot = environment.lookup(selector);\n this._callback = callback;\n this._data = _snapshot.data;\n this._isMissingData = _snapshot.isMissingData;\n this._missingRequiredFields = _snapshot.missingRequiredFields;\n this._errorResponseFields = _snapshot.errorResponseFields;\n this._relayResolverErrors = _snapshot.relayResolverErrors;\n this._environment = environment;\n this._rootIsQueryRenderer = rootIsQueryRenderer;\n this._selector = selector;\n if (RelayFeatureFlags.ENABLE_CONTAINERS_SUBSCRIBE_ON_COMMIT === true) {\n if (subscribeOnConstruction) {\n this._subscription = environment.subscribe(_snapshot, this._onChange);\n }\n } else {\n this._subscription = environment.subscribe(_snapshot, this._onChange);\n }\n }\n var _proto2 = SelectorResolver.prototype;\n _proto2.dispose = function dispose() {\n if (this._subscription) {\n this._subscription.dispose();\n this._subscription = null;\n }\n };\n _proto2.resolve = function resolve() {\n if (this._isMissingData === true) {\n var pendingOperationsResult = getPendingOperationsForFragment(this._environment, this._selector.node, this._selector.owner);\n var promise = pendingOperationsResult === null || pendingOperationsResult === void 0 ? void 0 : pendingOperationsResult.promise;\n if (promise != null) {\n if (this._rootIsQueryRenderer) {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'Relay: Relay Container for fragment `%s` has missing data and ' + 'would suspend. When using features such as @defer or @module, ' + 'use `useFragment` instead of a Relay Container.', this._selector.node.name) : void 0;\n } else {\n var _pendingOperationsRes;\n var pendingOperations = (_pendingOperationsRes = pendingOperationsResult === null || pendingOperationsResult === void 0 ? void 0 : pendingOperationsResult.pendingOperations) !== null && _pendingOperationsRes !== void 0 ? _pendingOperationsRes : [];\n process.env.NODE_ENV !== \"production\" ? warning(false, 'Relay: Relay Container for fragment `%s` suspended. When using ' + 'features such as @defer or @module, use `useFragment` instead ' + 'of a Relay Container.', this._selector.node.name) : void 0;\n this._environment.__log({\n name: 'suspense.fragment',\n data: this._data,\n fragment: this._selector.node,\n isRelayHooks: false,\n isMissingData: this._isMissingData,\n isPromiseCached: false,\n pendingOperations: pendingOperations\n });\n throw promise;\n }\n }\n }\n handlePotentialSnapshotErrors(this._environment, this._missingRequiredFields, this._relayResolverErrors, this._errorResponseFields);\n return this._data;\n };\n _proto2.setSelector = function setSelector(selector) {\n if (this._subscription != null && areEqualSelectors(selector, this._selector)) {\n return;\n }\n this.dispose();\n var snapshot = this._environment.lookup(selector);\n this._data = recycleNodesInto(this._data, snapshot.data);\n this._isMissingData = snapshot.isMissingData;\n this._missingRequiredFields = snapshot.missingRequiredFields;\n this._errorResponseFields = snapshot.errorResponseFields;\n this._relayResolverErrors = snapshot.relayResolverErrors;\n this._selector = selector;\n this._subscription = this._environment.subscribe(snapshot, this._onChange);\n };\n _proto2.setVariables = function setVariables(variables, request) {\n if (areEqual(variables, this._selector.variables)) {\n return;\n }\n var requestDescriptor = createRequestDescriptor(request, variables);\n var selector = createReaderSelector(this._selector.node, this._selector.dataID, variables, requestDescriptor);\n this.setSelector(selector);\n };\n return SelectorResolver;\n}();\nvar SelectorListResolver = /*#__PURE__*/function () {\n function SelectorListResolver(environment, rootIsQueryRenderer, selector, subscribeOnConstruction, callback) {\n var _this3 = this;\n (0, _defineProperty2[\"default\"])(this, \"_onChange\", function (data) {\n _this3._stale = true;\n _this3._callback();\n });\n this._callback = callback;\n this._data = [];\n this._environment = environment;\n this._resolvers = [];\n this._stale = true;\n this._rootIsQueryRenderer = rootIsQueryRenderer;\n this._subscribeOnConstruction = subscribeOnConstruction;\n this.setSelector(selector);\n }\n var _proto3 = SelectorListResolver.prototype;\n _proto3.dispose = function dispose() {\n this._resolvers.forEach(disposeCallback);\n };\n _proto3.resolve = function resolve() {\n if (this._stale) {\n var prevData = this._data;\n var nextData;\n for (var ii = 0; ii < this._resolvers.length; ii++) {\n var prevItem = prevData[ii];\n var nextItem = this._resolvers[ii].resolve();\n if (nextData || nextItem !== prevItem) {\n nextData = nextData || prevData.slice(0, ii);\n nextData.push(nextItem);\n }\n }\n if (!nextData && this._resolvers.length !== prevData.length) {\n nextData = prevData.slice(0, this._resolvers.length);\n }\n this._data = nextData || prevData;\n this._stale = false;\n }\n return this._data;\n };\n _proto3.setSelector = function setSelector(selector) {\n var selectors = selector.selectors;\n while (this._resolvers.length > selectors.length) {\n var resolver = this._resolvers.pop();\n resolver.dispose();\n }\n for (var ii = 0; ii < selectors.length; ii++) {\n if (ii < this._resolvers.length) {\n this._resolvers[ii].setSelector(selectors[ii]);\n } else {\n this._resolvers[ii] = new SelectorResolver(this._environment, this._rootIsQueryRenderer, selectors[ii], this._subscribeOnConstruction, this._onChange);\n }\n }\n this._stale = true;\n };\n _proto3.setVariables = function setVariables(variables, request) {\n this._resolvers.forEach(function (resolver) {\n return resolver.setVariables(variables, request);\n });\n this._stale = true;\n };\n return SelectorListResolver;\n}();\nfunction disposeCallback(disposable) {\n disposable && disposable.dispose();\n}\nmodule.exports = RelayModernFragmentSpecResolver;","'use strict';\n\nvar deepFreeze = require('../util/deepFreeze');\nvar getRequestIdentifier = require('../util/getRequestIdentifier');\nvar _require = require('./RelayConcreteVariables'),\n getOperationVariables = _require.getOperationVariables;\nvar _require2 = require('./RelayModernSelector'),\n createNormalizationSelector = _require2.createNormalizationSelector,\n createReaderSelector = _require2.createReaderSelector;\nvar _require3 = require('./RelayStoreUtils'),\n ROOT_ID = _require3.ROOT_ID;\nfunction createOperationDescriptor(request, variables, cacheConfig) {\n var dataID = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ROOT_ID;\n var operation = request.operation;\n var operationVariables = getOperationVariables(operation, request.params.providedVariables, variables);\n var requestDescriptor = createRequestDescriptor(request, operationVariables, cacheConfig);\n var operationDescriptor = {\n fragment: createReaderSelector(request.fragment, dataID, operationVariables, requestDescriptor),\n request: requestDescriptor,\n root: createNormalizationSelector(operation, dataID, operationVariables)\n };\n if (process.env.NODE_ENV !== \"production\") {\n Object.freeze(operationDescriptor.fragment);\n Object.freeze(operationDescriptor.root);\n Object.freeze(operationDescriptor);\n }\n return operationDescriptor;\n}\nfunction createRequestDescriptor(request, variables, cacheConfig) {\n var requestDescriptor = {\n identifier: getRequestIdentifier(request.params, variables),\n node: request,\n variables: variables,\n cacheConfig: cacheConfig\n };\n if (process.env.NODE_ENV !== \"production\") {\n deepFreeze(variables);\n Object.freeze(request);\n Object.freeze(requestDescriptor);\n }\n return requestDescriptor;\n}\nmodule.exports = {\n createOperationDescriptor: createOperationDescriptor,\n createRequestDescriptor: createRequestDescriptor\n};","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _defineProperty2 = _interopRequireDefault(require(\"@babel/runtime/helpers/defineProperty\"));\nvar _objectWithoutPropertiesLoose2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectWithoutPropertiesLoose\"));\nvar _toPropertyKey2 = _interopRequireDefault(require(\"@babel/runtime/helpers/toPropertyKey\"));\nvar _objectSpread2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar deepFreeze = require('../util/deepFreeze');\nvar _require = require('./ClientID'),\n generateClientObjectClientID = _require.generateClientObjectClientID,\n isClientID = _require.isClientID;\nvar _require2 = require('./experimental-live-resolvers/LiveResolverSuspenseSentinel'),\n isSuspenseSentinel = _require2.isSuspenseSentinel;\nvar _require3 = require('./RelayStoreUtils'),\n ACTOR_IDENTIFIER_KEY = _require3.ACTOR_IDENTIFIER_KEY,\n ERRORS_KEY = _require3.ERRORS_KEY,\n ID_KEY = _require3.ID_KEY,\n INVALIDATED_AT_KEY = _require3.INVALIDATED_AT_KEY,\n REF_KEY = _require3.REF_KEY,\n REFS_KEY = _require3.REFS_KEY,\n RELAY_RESOLVER_VALUE_KEY = _require3.RELAY_RESOLVER_VALUE_KEY,\n ROOT_ID = _require3.ROOT_ID,\n TYPENAME_KEY = _require3.TYPENAME_KEY;\nvar areEqual = require(\"fbjs/lib/areEqual\");\nvar invariant = require('invariant');\nvar warning = require(\"fbjs/lib/warning\");\nfunction clone(record) {\n return (0, _objectSpread2[\"default\"])({}, record);\n}\nfunction copyFields(source, sink) {\n for (var key in source) {\n if (source.hasOwnProperty(key)) {\n if (key !== ID_KEY && key !== TYPENAME_KEY) {\n sink[key] = source[key];\n }\n }\n }\n}\nfunction create(dataID, typeName) {\n var record = {};\n record[ID_KEY] = dataID;\n record[TYPENAME_KEY] = typeName;\n return record;\n}\nfunction fromObject(json) {\n return json;\n}\nfunction getDataID(record) {\n return record[ID_KEY];\n}\nfunction getFields(record) {\n if (ERRORS_KEY in record) {\n return Object.keys(record).filter(function (field) {\n return field !== ERRORS_KEY;\n });\n }\n return Object.keys(record);\n}\nfunction getType(record) {\n return record[TYPENAME_KEY];\n}\nfunction getErrors(record, storageKey) {\n var _record$ERRORS_KEY;\n return (_record$ERRORS_KEY = record[ERRORS_KEY]) === null || _record$ERRORS_KEY === void 0 ? void 0 : _record$ERRORS_KEY[storageKey];\n}\nfunction getValue(record, storageKey) {\n var value = record[storageKey];\n if (value && typeof value === 'object') {\n !(!value.hasOwnProperty(REF_KEY) && !value.hasOwnProperty(REFS_KEY)) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayModernRecord.getValue(): Expected a scalar (non-link) value for `%s.%s` ' + 'but found %s.', record[ID_KEY], storageKey, value.hasOwnProperty(REF_KEY) ? 'a linked record' : 'plural linked records') : invariant(false) : void 0;\n }\n return value;\n}\nfunction hasValue(record, storageKey) {\n return storageKey in record;\n}\nfunction getLinkedRecordID(record, storageKey) {\n var maybeLink = record[storageKey];\n if (maybeLink == null) {\n return maybeLink;\n }\n var link = maybeLink;\n !(typeof link === 'object' && link && typeof link[REF_KEY] === 'string') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayModernRecord.getLinkedRecordID(): Expected `%s.%s` to be a linked ID, ' + 'was `%s`.%s', record[ID_KEY], storageKey, JSON.stringify(link), typeof link === 'object' && link[REFS_KEY] !== undefined ? ' It appears to be a plural linked record: did you mean to call ' + 'getLinkedRecords() instead of getLinkedRecord()?' : '') : invariant(false) : void 0;\n return link[REF_KEY];\n}\nfunction hasLinkedRecordID(record, storageKey) {\n var maybeLink = record[storageKey];\n if (maybeLink == null) {\n return false;\n }\n var link = maybeLink;\n return typeof link === 'object' && link && typeof link[REF_KEY] === 'string';\n}\nfunction getLinkedRecordIDs(record, storageKey) {\n var links = record[storageKey];\n if (links == null) {\n return links;\n }\n !(typeof links === 'object' && Array.isArray(links[REFS_KEY])) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayModernRecord.getLinkedRecordIDs(): Expected `%s.%s` to contain an array ' + 'of linked IDs, got `%s`.%s', record[ID_KEY], storageKey, JSON.stringify(links), typeof links === 'object' && links[REF_KEY] !== undefined ? ' It appears to be a singular linked record: did you mean to call ' + 'getLinkedRecord() instead of getLinkedRecords()?' : '') : invariant(false) : void 0;\n return links[REFS_KEY];\n}\nfunction hasLinkedRecordIDs(record, storageKey) {\n var links = record[storageKey];\n if (links == null) {\n return false;\n }\n return typeof links === 'object' && Array.isArray(links[REFS_KEY]) && links[REFS_KEY].every(function (link) {\n return typeof link === 'string';\n });\n}\nfunction getInvalidationEpoch(record) {\n if (record == null) {\n return null;\n }\n var invalidatedAt = record[INVALIDATED_AT_KEY];\n if (typeof invalidatedAt !== 'number') {\n return null;\n }\n return invalidatedAt;\n}\nfunction update(prevRecord, nextRecord) {\n var _updated2;\n if (process.env.NODE_ENV !== \"production\") {\n var _getType, _getType2;\n var prevID = getDataID(prevRecord);\n var nextID = getDataID(nextRecord);\n process.env.NODE_ENV !== \"production\" ? warning(prevID === nextID, 'RelayModernRecord: Invalid record update, expected both versions of ' + 'the record to have the same id, got `%s` and `%s`.', prevID, nextID) : void 0;\n var prevType = (_getType = getType(prevRecord)) !== null && _getType !== void 0 ? _getType : null;\n var nextType = (_getType2 = getType(nextRecord)) !== null && _getType2 !== void 0 ? _getType2 : null;\n process.env.NODE_ENV !== \"production\" ? warning(isClientID(nextID) && nextID !== ROOT_ID || prevType === nextType, 'RelayModernRecord: Invalid record update, expected both versions of ' + 'record `%s` to have the same `%s` but got conflicting types `%s` ' + 'and `%s`. The GraphQL server likely violated the globally unique ' + 'id requirement by returning the same id for different objects.', prevID, TYPENAME_KEY, prevType, nextType) : void 0;\n }\n var prevErrorsByKey = prevRecord[ERRORS_KEY];\n var nextErrorsByKey = nextRecord[ERRORS_KEY];\n var updated = null;\n if (prevErrorsByKey == null && nextErrorsByKey == null) {\n var _updated;\n for (var storageKey in nextRecord) {\n if (updated || !areEqual(prevRecord[storageKey], nextRecord[storageKey])) {\n updated = updated !== null ? updated : (0, _objectSpread2[\"default\"])({}, prevRecord);\n updated[storageKey] = nextRecord[storageKey];\n }\n }\n return (_updated = updated) !== null && _updated !== void 0 ? _updated : prevRecord;\n }\n for (var _storageKey2 in nextRecord) {\n if (_storageKey2 === ERRORS_KEY) {\n continue;\n }\n var nextValue = nextRecord[_storageKey2];\n var nextErrors = nextErrorsByKey === null || nextErrorsByKey === void 0 ? void 0 : nextErrorsByKey[_storageKey2];\n if (updated == null) {\n var prevValue = prevRecord[_storageKey2];\n var prevErrors = prevErrorsByKey === null || prevErrorsByKey === void 0 ? void 0 : prevErrorsByKey[_storageKey2];\n if (areEqual(prevValue, nextValue) && areEqual(prevErrors, nextErrors)) {\n continue;\n }\n updated = (0, _objectSpread2[\"default\"])({}, prevRecord);\n if (prevErrorsByKey != null) {\n updated[ERRORS_KEY] = (0, _objectSpread2[\"default\"])({}, prevErrorsByKey);\n }\n }\n setValue(updated, _storageKey2, nextValue);\n setErrors(updated, _storageKey2, nextErrors);\n }\n return (_updated2 = updated) !== null && _updated2 !== void 0 ? _updated2 : prevRecord;\n}\nfunction merge(record1, record2) {\n if (process.env.NODE_ENV !== \"production\") {\n var _getType3, _getType4;\n var prevID = getDataID(record1);\n var nextID = getDataID(record2);\n process.env.NODE_ENV !== \"production\" ? warning(prevID === nextID, 'RelayModernRecord: Invalid record merge, expected both versions of ' + 'the record to have the same id, got `%s` and `%s`.', prevID, nextID) : void 0;\n var prevType = (_getType3 = getType(record1)) !== null && _getType3 !== void 0 ? _getType3 : null;\n var nextType = (_getType4 = getType(record2)) !== null && _getType4 !== void 0 ? _getType4 : null;\n process.env.NODE_ENV !== \"production\" ? warning(isClientID(nextID) && nextID !== ROOT_ID || prevType === nextType, 'RelayModernRecord: Invalid record merge, expected both versions of ' + 'record `%s` to have the same `%s` but got conflicting types `%s` ' + 'and `%s`. The GraphQL server likely violated the globally unique ' + 'id requirement by returning the same id for different objects.', prevID, TYPENAME_KEY, prevType, nextType) : void 0;\n }\n if (ERRORS_KEY in record1 || ERRORS_KEY in record2) {\n var errors1 = record1[ERRORS_KEY],\n fields1 = (0, _objectWithoutPropertiesLoose2[\"default\"])(record1, [ERRORS_KEY].map(_toPropertyKey2[\"default\"]));\n var errors2 = record2[ERRORS_KEY],\n fields2 = (0, _objectWithoutPropertiesLoose2[\"default\"])(record2, [ERRORS_KEY].map(_toPropertyKey2[\"default\"]));\n var updated = (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, fields1), fields2);\n if (errors1 == null && errors2 == null) {\n return updated;\n }\n var updatedErrors = {};\n for (var storageKey in errors1) {\n if (fields2.hasOwnProperty(storageKey)) {\n continue;\n }\n updatedErrors[storageKey] = errors1[storageKey];\n }\n for (var _storageKey3 in errors2) {\n updatedErrors[_storageKey3] = errors2[_storageKey3];\n }\n for (var _storageKey in updatedErrors) {\n updated[ERRORS_KEY] = updatedErrors;\n break;\n }\n return updated;\n } else {\n return (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, record1), record2);\n }\n}\nfunction freeze(record) {\n deepFreeze(record);\n}\nfunction setErrors(record, storageKey, errors) {\n if (process.env.NODE_ENV !== \"production\") {\n process.env.NODE_ENV !== \"production\" ? warning(storageKey in record, 'RelayModernRecord: Invalid error update, `%s` should not be undefined.', storageKey) : void 0;\n }\n var errorsByStorageKey = record[ERRORS_KEY];\n if (errors != null && errors.length > 0) {\n if (errorsByStorageKey == null) {\n record[ERRORS_KEY] = (0, _defineProperty2[\"default\"])({}, storageKey, errors);\n } else {\n errorsByStorageKey[storageKey] = errors;\n }\n } else if (errorsByStorageKey != null) {\n if (delete errorsByStorageKey[storageKey]) {\n for (var otherStorageKey in errorsByStorageKey) {\n if (errorsByStorageKey.hasOwnProperty(otherStorageKey)) {\n return;\n }\n }\n delete record[ERRORS_KEY];\n }\n }\n}\nfunction setValue(record, storageKey, value) {\n if (process.env.NODE_ENV !== \"production\") {\n var prevID = getDataID(record);\n if (storageKey === ID_KEY) {\n process.env.NODE_ENV !== \"production\" ? warning(prevID === value, 'RelayModernRecord: Invalid field update, expected both versions of ' + 'the record to have the same id, got `%s` and `%s`.', prevID, value) : void 0;\n } else if (storageKey === TYPENAME_KEY) {\n var _getType5;\n var prevType = (_getType5 = getType(record)) !== null && _getType5 !== void 0 ? _getType5 : null;\n var nextType = value !== null && value !== void 0 ? value : null;\n process.env.NODE_ENV !== \"production\" ? warning(isClientID(getDataID(record)) && getDataID(record) !== ROOT_ID || prevType === nextType, 'RelayModernRecord: Invalid field update, expected both versions of ' + 'record `%s` to have the same `%s` but got conflicting types `%s` ' + 'and `%s`. The GraphQL server likely violated the globally unique ' + 'id requirement by returning the same id for different objects.', prevID, TYPENAME_KEY, prevType, nextType) : void 0;\n }\n }\n record[storageKey] = value;\n}\nfunction setLinkedRecordID(record, storageKey, linkedID) {\n var link = {};\n link[REF_KEY] = linkedID;\n record[storageKey] = link;\n}\nfunction setLinkedRecordIDs(record, storageKey, linkedIDs) {\n var links = {};\n links[REFS_KEY] = linkedIDs;\n record[storageKey] = links;\n}\nfunction setActorLinkedRecordID(record, storageKey, actorIdentifier, linkedID) {\n var link = {};\n link[REF_KEY] = linkedID;\n link[ACTOR_IDENTIFIER_KEY] = actorIdentifier;\n record[storageKey] = link;\n}\nfunction getActorLinkedRecordID(record, storageKey) {\n var link = record[storageKey];\n if (link == null) {\n return link;\n }\n !(typeof link === 'object' && typeof link[REF_KEY] === 'string' && link[ACTOR_IDENTIFIER_KEY] != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayModernRecord.getActorLinkedRecordID(): Expected `%s.%s` to be an actor specific linked ID, ' + 'was `%s`.', record[ID_KEY], storageKey, JSON.stringify(link)) : invariant(false) : void 0;\n return [link[ACTOR_IDENTIFIER_KEY], link[REF_KEY]];\n}\nfunction getResolverLinkedRecordID(record, typeName) {\n var id = getValue(record, RELAY_RESOLVER_VALUE_KEY);\n if (id == null || isSuspenseSentinel(id)) {\n return null;\n }\n if (typeof id === 'object') {\n id = id.id;\n }\n !(typeof id === 'string') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayModernRecord.getResolverLinkedRecordID(): Expected value to be a linked ID, ' + 'was `%s`.', JSON.stringify(id)) : invariant(false) : void 0;\n return generateClientObjectClientID(typeName, id);\n}\nfunction getResolverLinkedRecordIDs(record, typeName) {\n var resolverValue = getValue(record, RELAY_RESOLVER_VALUE_KEY);\n if (resolverValue == null || isSuspenseSentinel(resolverValue)) {\n return null;\n }\n !Array.isArray(resolverValue) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayModernRecord.getResolverLinkedRecordIDs(): Expected value to be an array of linked IDs, ' + 'was `%s`.', JSON.stringify(resolverValue)) : invariant(false) : void 0;\n return resolverValue.map(function (id) {\n if (id == null) {\n return null;\n }\n if (typeof id === 'object') {\n id = id.id;\n }\n !(typeof id === 'string') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayModernRecord.getResolverLinkedRecordIDs(): Expected item within resolver linked field to be a DataID, ' + 'was `%s`.', JSON.stringify(id)) : invariant(false) : void 0;\n return generateClientObjectClientID(typeName, id);\n });\n}\nfunction toJSON(record) {\n return record;\n}\nmodule.exports = {\n clone: clone,\n copyFields: copyFields,\n create: create,\n freeze: freeze,\n fromObject: fromObject,\n getDataID: getDataID,\n getErrors: getErrors,\n getFields: getFields,\n getInvalidationEpoch: getInvalidationEpoch,\n getLinkedRecordID: getLinkedRecordID,\n getLinkedRecordIDs: getLinkedRecordIDs,\n getType: getType,\n getValue: getValue,\n hasValue: hasValue,\n hasLinkedRecordID: hasLinkedRecordID,\n hasLinkedRecordIDs: hasLinkedRecordIDs,\n merge: merge,\n setErrors: setErrors,\n setValue: setValue,\n setLinkedRecordID: setLinkedRecordID,\n setLinkedRecordIDs: setLinkedRecordIDs,\n update: update,\n getActorLinkedRecordID: getActorLinkedRecordID,\n setActorLinkedRecordID: setActorLinkedRecordID,\n getResolverLinkedRecordID: getResolverLinkedRecordID,\n getResolverLinkedRecordIDs: getResolverLinkedRecordIDs,\n toJSON: toJSON\n};","'use strict';\n\nvar RelayFeatureFlags = require('../util/RelayFeatureFlags');\nvar _require = require('./RelayConcreteVariables'),\n getFragmentVariables = _require.getFragmentVariables;\nvar _require2 = require('./RelayStoreUtils'),\n CLIENT_EDGE_TRAVERSAL_PATH = _require2.CLIENT_EDGE_TRAVERSAL_PATH,\n FRAGMENT_OWNER_KEY = _require2.FRAGMENT_OWNER_KEY,\n FRAGMENT_POINTER_IS_WITHIN_UNMATCHED_TYPE_REFINEMENT = _require2.FRAGMENT_POINTER_IS_WITHIN_UNMATCHED_TYPE_REFINEMENT,\n FRAGMENTS_KEY = _require2.FRAGMENTS_KEY,\n ID_KEY = _require2.ID_KEY;\nvar areEqual = require(\"fbjs/lib/areEqual\");\nvar invariant = require('invariant');\nvar warning = require(\"fbjs/lib/warning\");\nfunction getSingularSelector(fragment, item) {\n !(typeof item === 'object' && item !== null && !Array.isArray(item)) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayModernSelector: Expected value for fragment `%s` to be an object, got ' + '`%s`.', fragment.name, JSON.stringify(item)) : invariant(false) : void 0;\n var dataID = item[ID_KEY];\n var fragments = item[FRAGMENTS_KEY];\n var mixedOwner = item[FRAGMENT_OWNER_KEY];\n var mixedClientEdgeTraversalPath = item[CLIENT_EDGE_TRAVERSAL_PATH];\n if (typeof dataID === 'string' && typeof fragments === 'object' && fragments !== null && typeof fragments[fragment.name] === 'object' && fragments[fragment.name] !== null && typeof mixedOwner === 'object' && mixedOwner !== null && (mixedClientEdgeTraversalPath == null || Array.isArray(mixedClientEdgeTraversalPath))) {\n var owner = mixedOwner;\n var clientEdgeTraversalPath = mixedClientEdgeTraversalPath;\n var argumentVariables = fragments[fragment.name];\n var fragmentVariables = getFragmentVariables(fragment, owner.variables, argumentVariables);\n var isWithinUnmatchedTypeRefinement = argumentVariables[FRAGMENT_POINTER_IS_WITHIN_UNMATCHED_TYPE_REFINEMENT] === true;\n return createReaderSelector(fragment, dataID, fragmentVariables, owner, isWithinUnmatchedTypeRefinement, clientEdgeTraversalPath);\n }\n if (process.env.NODE_ENV !== \"production\") {\n var stringifiedItem = JSON.stringify(item);\n if (stringifiedItem.length > 499) {\n stringifiedItem = stringifiedItem.substr(0, 498) + \"\\u2026\";\n }\n process.env.NODE_ENV !== \"production\" ? warning(false, 'RelayModernSelector: Expected object to contain data for fragment `%s`, got ' + '`%s`. Make sure that the parent operation/fragment included fragment ' + '`...%s` without `@relay(mask: false)`.', fragment.name, stringifiedItem, fragment.name) : void 0;\n }\n return null;\n}\nfunction getPluralSelector(fragment, items) {\n var selectors = null;\n items.forEach(function (item, ii) {\n var selector = item != null ? getSingularSelector(fragment, item) : null;\n if (selector != null) {\n selectors = selectors || [];\n selectors.push(selector);\n }\n });\n if (selectors == null) {\n return null;\n } else {\n return {\n kind: 'PluralReaderSelector',\n selectors: selectors\n };\n }\n}\nfunction getSelector(fragment, item) {\n if (item == null) {\n return item;\n } else if (fragment.metadata && fragment.metadata.plural === true) {\n !Array.isArray(item) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayModernSelector: Expected value for fragment `%s` to be an array, got `%s`. ' + 'Remove `@relay(plural: true)` from fragment `%s` to allow the prop to be an object.', fragment.name, JSON.stringify(item), fragment.name) : invariant(false) : void 0;\n return getPluralSelector(fragment, item);\n } else {\n !!Array.isArray(item) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayModernSelector: Expected value for fragment `%s` to be an object, got `%s`. ' + 'Add `@relay(plural: true)` to fragment `%s` to allow the prop to be an array of items.', fragment.name, JSON.stringify(item), fragment.name) : invariant(false) : void 0;\n return getSingularSelector(fragment, item);\n }\n}\nfunction getSelectorsFromObject(fragments, object) {\n var selectors = {};\n for (var key in fragments) {\n if (fragments.hasOwnProperty(key)) {\n var fragment = fragments[key];\n var item = object[key];\n selectors[key] = getSelector(fragment, item);\n }\n }\n return selectors;\n}\nfunction getDataIDsFromObject(fragments, object) {\n var ids = {};\n for (var key in fragments) {\n if (fragments.hasOwnProperty(key)) {\n var fragment = fragments[key];\n var item = object[key];\n ids[key] = getDataIDsFromFragment(fragment, item);\n }\n }\n return ids;\n}\nfunction getDataIDsFromFragment(fragment, item) {\n if (item == null) {\n return item;\n } else if (fragment.metadata && fragment.metadata.plural === true) {\n !Array.isArray(item) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayModernSelector: Expected value for fragment `%s` to be an array, got `%s`. ' + 'Remove `@relay(plural: true)` from fragment `%s` to allow the prop to be an object.', fragment.name, JSON.stringify(item), fragment.name) : invariant(false) : void 0;\n return getDataIDs(fragment, item);\n } else {\n !!Array.isArray(item) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayModernFragmentSpecResolver: Expected value for fragment `%s` to be an object, got `%s`. ' + 'Add `@relay(plural: true)` to fragment `%s` to allow the prop to be an array of items.', fragment.name, JSON.stringify(item), fragment.name) : invariant(false) : void 0;\n return getDataID(fragment, item);\n }\n}\nfunction getDataIDs(fragment, items) {\n var ids = null;\n items.forEach(function (item) {\n var id = item != null ? getDataID(fragment, item) : null;\n if (id != null) {\n ids = ids || [];\n ids.push(id);\n }\n });\n return ids;\n}\nfunction getDataID(fragment, item) {\n !(typeof item === 'object' && item !== null && !Array.isArray(item)) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayModernSelector: Expected value for fragment `%s` to be an object, got ' + '`%s`.', fragment.name, JSON.stringify(item)) : invariant(false) : void 0;\n var dataID = item[ID_KEY];\n if (typeof dataID === 'string') {\n return dataID;\n }\n process.env.NODE_ENV !== \"production\" ? warning(false, 'RelayModernSelector: Expected object to contain data for fragment `%s`, got ' + '`%s`. Make sure that the parent operation/fragment included fragment ' + '`...%s` without `@relay(mask: false)`, or `null` is passed as the fragment ' + \"reference for `%s` if it's conditonally included and the condition isn't met.\", fragment.name, JSON.stringify(item), fragment.name, fragment.name) : void 0;\n return null;\n}\nfunction getVariablesFromObject(fragments, object) {\n var variables = {};\n for (var key in fragments) {\n if (fragments.hasOwnProperty(key)) {\n var fragment = fragments[key];\n var item = object[key];\n var itemVariables = getVariablesFromFragment(fragment, item);\n Object.assign(variables, itemVariables);\n }\n }\n return variables;\n}\nfunction getVariablesFromFragment(fragment, item) {\n var _fragment$metadata;\n if (item == null) {\n return {};\n } else if (((_fragment$metadata = fragment.metadata) === null || _fragment$metadata === void 0 ? void 0 : _fragment$metadata.plural) === true) {\n !Array.isArray(item) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayModernSelector: Expected value for fragment `%s` to be an array, got `%s`. ' + 'Remove `@relay(plural: true)` from fragment `%s` to allow the prop to be an object.', fragment.name, JSON.stringify(item), fragment.name) : invariant(false) : void 0;\n return getVariablesFromPluralFragment(fragment, item);\n } else {\n !!Array.isArray(item) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayModernFragmentSpecResolver: Expected value for fragment `%s` to be an object, got `%s`. ' + 'Add `@relay(plural: true)` to fragment `%s` to allow the prop to be an array of items.', fragment.name, JSON.stringify(item), fragment.name) : invariant(false) : void 0;\n return getVariablesFromSingularFragment(fragment, item) || {};\n }\n}\nfunction getVariablesFromSingularFragment(fragment, item) {\n var selector = getSingularSelector(fragment, item);\n if (!selector) {\n return null;\n }\n return selector.variables;\n}\nfunction getVariablesFromPluralFragment(fragment, items) {\n var variables = {};\n items.forEach(function (value, ii) {\n if (value != null) {\n var itemVariables = getVariablesFromSingularFragment(fragment, value);\n if (itemVariables != null) {\n Object.assign(variables, itemVariables);\n }\n }\n });\n return variables;\n}\nfunction areEqualSingularSelectors(thisSelector, thatSelector) {\n return thisSelector.dataID === thatSelector.dataID && thisSelector.node === thatSelector.node && areEqual(thisSelector.variables, thatSelector.variables) && areEqualOwners(thisSelector.owner, thatSelector.owner) && (!RelayFeatureFlags.ENABLE_STRICT_EQUAL_SELECTORS || thisSelector.isWithinUnmatchedTypeRefinement === thatSelector.isWithinUnmatchedTypeRefinement && areEqualClientEdgeTraversalPaths(thisSelector.clientEdgeTraversalPath, thatSelector.clientEdgeTraversalPath));\n}\nfunction areEqualOwners(thisOwner, thatOwner) {\n if (thisOwner === thatOwner) {\n return true;\n } else {\n return thisOwner.identifier === thatOwner.identifier && areEqual(thisOwner.cacheConfig, thatOwner.cacheConfig);\n }\n}\nfunction areEqualClientEdgeTraversalPaths(thisPath, thatPath) {\n if (thisPath === thatPath) {\n return true;\n }\n if (thisPath == null || thatPath == null || thisPath.length !== thatPath.length) {\n return false;\n }\n var idx = thisPath.length;\n while (idx--) {\n var a = thisPath[idx];\n var b = thatPath[idx];\n if (a === b) {\n continue;\n }\n if (a == null || b == null || a.clientEdgeDestinationID !== b.clientEdgeDestinationID || a.readerClientEdge !== b.readerClientEdge) {\n return false;\n }\n }\n return true;\n}\nfunction areEqualSelectors(a, b) {\n if (a === b) {\n return true;\n } else if (a == null) {\n return b == null;\n } else if (b == null) {\n return a == null;\n } else if (a.kind === 'SingularReaderSelector' && b.kind === 'SingularReaderSelector') {\n return areEqualSingularSelectors(a, b);\n } else if (a.kind === 'PluralReaderSelector' && b.kind === 'PluralReaderSelector') {\n return a.selectors.length === b.selectors.length && a.selectors.every(function (s, i) {\n return areEqualSingularSelectors(s, b.selectors[i]);\n });\n } else {\n return false;\n }\n}\nfunction createReaderSelector(fragment, dataID, variables, request) {\n var isWithinUnmatchedTypeRefinement = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;\n var clientEdgeTraversalPath = arguments.length > 5 ? arguments[5] : undefined;\n return {\n kind: 'SingularReaderSelector',\n dataID: dataID,\n isWithinUnmatchedTypeRefinement: isWithinUnmatchedTypeRefinement,\n clientEdgeTraversalPath: clientEdgeTraversalPath !== null && clientEdgeTraversalPath !== void 0 ? clientEdgeTraversalPath : null,\n node: fragment,\n variables: variables,\n owner: request\n };\n}\nfunction createNormalizationSelector(node, dataID, variables) {\n return {\n dataID: dataID,\n node: node,\n variables: variables\n };\n}\nmodule.exports = {\n areEqualSelectors: areEqualSelectors,\n createReaderSelector: createReaderSelector,\n createNormalizationSelector: createNormalizationSelector,\n getDataIDsFromFragment: getDataIDsFromFragment,\n getDataIDsFromObject: getDataIDsFromObject,\n getSingularSelector: getSingularSelector,\n getPluralSelector: getPluralSelector,\n getSelector: getSelector,\n getSelectorsFromObject: getSelectorsFromObject,\n getVariablesFromSingularFragment: getVariablesFromSingularFragment,\n getVariablesFromPluralFragment: getVariablesFromPluralFragment,\n getVariablesFromFragment: getVariablesFromFragment,\n getVariablesFromObject: getVariablesFromObject\n};","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _createForOfIteratorHelper2 = _interopRequireDefault(require(\"@babel/runtime/helpers/createForOfIteratorHelper\"));\nvar _defineProperty2 = _interopRequireDefault(require(\"@babel/runtime/helpers/defineProperty\"));\nvar _require = require('../multi-actor-environment/ActorIdentifier'),\n INTERNAL_ACTOR_IDENTIFIER_DO_NOT_USE = _require.INTERNAL_ACTOR_IDENTIFIER_DO_NOT_USE,\n assertInternalActorIdentifier = _require.assertInternalActorIdentifier;\nvar deepFreeze = require('../util/deepFreeze');\nvar RelayFeatureFlags = require('../util/RelayFeatureFlags');\nvar resolveImmediate = require('../util/resolveImmediate');\nvar DataChecker = require('./DataChecker');\nvar defaultGetDataID = require('./defaultGetDataID');\nvar RelayModernRecord = require('./RelayModernRecord');\nvar RelayOptimisticRecordSource = require('./RelayOptimisticRecordSource');\nvar RelayReader = require('./RelayReader');\nvar RelayReferenceMarker = require('./RelayReferenceMarker');\nvar RelayStoreSubscriptions = require('./RelayStoreSubscriptions');\nvar RelayStoreUtils = require('./RelayStoreUtils');\nvar _require2 = require('./RelayStoreUtils'),\n ROOT_ID = _require2.ROOT_ID,\n ROOT_TYPE = _require2.ROOT_TYPE;\nvar _require3 = require('./ResolverCache'),\n RecordResolverCache = _require3.RecordResolverCache;\nvar invariant = require('invariant');\nvar DEFAULT_RELEASE_BUFFER_SIZE = 10;\nvar RelayModernStore = /*#__PURE__*/function () {\n function RelayModernStore(source, options) {\n var _this = this;\n var _options$gcReleaseBuf, _options$gcScheduler, _options$getDataID, _options$log, _options$operationLoa;\n (0, _defineProperty2[\"default\"])(this, \"_gcStep\", function () {\n if (_this._gcRun) {\n if (_this._gcRun.next().done) {\n _this._gcRun = null;\n } else {\n _this._gcScheduler(_this._gcStep);\n }\n }\n });\n if (process.env.NODE_ENV !== \"production\") {\n var storeIDs = source.getRecordIDs();\n for (var ii = 0; ii < storeIDs.length; ii++) {\n var record = source.get(storeIDs[ii]);\n if (record) {\n RelayModernRecord.freeze(record);\n }\n }\n }\n this._currentWriteEpoch = 0;\n this._gcHoldCounter = 0;\n this._gcReleaseBufferSize = (_options$gcReleaseBuf = options === null || options === void 0 ? void 0 : options.gcReleaseBufferSize) !== null && _options$gcReleaseBuf !== void 0 ? _options$gcReleaseBuf : DEFAULT_RELEASE_BUFFER_SIZE;\n this._gcRun = null;\n this._gcScheduler = (_options$gcScheduler = options === null || options === void 0 ? void 0 : options.gcScheduler) !== null && _options$gcScheduler !== void 0 ? _options$gcScheduler : resolveImmediate;\n this._getDataID = (_options$getDataID = options === null || options === void 0 ? void 0 : options.getDataID) !== null && _options$getDataID !== void 0 ? _options$getDataID : defaultGetDataID;\n this._globalInvalidationEpoch = null;\n this._invalidationSubscriptions = new Set();\n this._invalidatedRecordIDs = new Set();\n this.__log = (_options$log = options === null || options === void 0 ? void 0 : options.log) !== null && _options$log !== void 0 ? _options$log : null;\n this._queryCacheExpirationTime = options === null || options === void 0 ? void 0 : options.queryCacheExpirationTime;\n this._operationLoader = (_options$operationLoa = options === null || options === void 0 ? void 0 : options.operationLoader) !== null && _options$operationLoa !== void 0 ? _options$operationLoa : null;\n this._optimisticSource = null;\n this._recordSource = source;\n this._releaseBuffer = [];\n this._roots = new Map();\n this._shouldScheduleGC = false;\n this._resolverCache = new RecordResolverCache(function () {\n return _this._getMutableRecordSource();\n });\n this._storeSubscriptions = new RelayStoreSubscriptions(options === null || options === void 0 ? void 0 : options.log, this._resolverCache);\n this._updatedRecordIDs = new Set();\n this._shouldProcessClientComponents = options === null || options === void 0 ? void 0 : options.shouldProcessClientComponents;\n initializeRecordSource(this._recordSource);\n }\n var _proto = RelayModernStore.prototype;\n _proto.getSource = function getSource() {\n var _this$_optimisticSour;\n return (_this$_optimisticSour = this._optimisticSource) !== null && _this$_optimisticSour !== void 0 ? _this$_optimisticSour : this._recordSource;\n };\n _proto._getMutableRecordSource = function _getMutableRecordSource() {\n var _this$_optimisticSour2;\n return (_this$_optimisticSour2 = this._optimisticSource) !== null && _this$_optimisticSour2 !== void 0 ? _this$_optimisticSour2 : this._recordSource;\n };\n _proto.check = function check(operation, options) {\n var _options$handlers, _options$getSourceFor, _options$getTargetFor, _options$defaultActor;\n var selector = operation.root;\n var source = this._getMutableRecordSource();\n var globalInvalidationEpoch = this._globalInvalidationEpoch;\n var rootEntry = this._roots.get(operation.request.identifier);\n var operationLastWrittenAt = rootEntry != null ? rootEntry.epoch : null;\n if (globalInvalidationEpoch != null) {\n if (operationLastWrittenAt == null || operationLastWrittenAt <= globalInvalidationEpoch) {\n return {\n status: 'stale'\n };\n }\n }\n var handlers = (_options$handlers = options === null || options === void 0 ? void 0 : options.handlers) !== null && _options$handlers !== void 0 ? _options$handlers : [];\n var getSourceForActor = (_options$getSourceFor = options === null || options === void 0 ? void 0 : options.getSourceForActor) !== null && _options$getSourceFor !== void 0 ? _options$getSourceFor : function (actorIdentifier) {\n assertInternalActorIdentifier(actorIdentifier);\n return source;\n };\n var getTargetForActor = (_options$getTargetFor = options === null || options === void 0 ? void 0 : options.getTargetForActor) !== null && _options$getTargetFor !== void 0 ? _options$getTargetFor : function (actorIdentifier) {\n assertInternalActorIdentifier(actorIdentifier);\n return source;\n };\n var operationAvailability = DataChecker.check(getSourceForActor, getTargetForActor, (_options$defaultActor = options === null || options === void 0 ? void 0 : options.defaultActorIdentifier) !== null && _options$defaultActor !== void 0 ? _options$defaultActor : INTERNAL_ACTOR_IDENTIFIER_DO_NOT_USE, selector, handlers, this._operationLoader, this._getDataID, this._shouldProcessClientComponents);\n return getAvailabilityStatus(operationAvailability, operationLastWrittenAt, rootEntry === null || rootEntry === void 0 ? void 0 : rootEntry.fetchTime, this._queryCacheExpirationTime);\n };\n _proto.retain = function retain(operation) {\n var _this2 = this;\n var id = operation.request.identifier;\n var disposed = false;\n var dispose = function dispose() {\n if (disposed) {\n return;\n }\n disposed = true;\n var rootEntry = _this2._roots.get(id);\n if (rootEntry == null) {\n return;\n }\n rootEntry.refCount--;\n if (rootEntry.refCount === 0) {\n var _queryCacheExpirationTime = _this2._queryCacheExpirationTime;\n var rootEntryIsStale = rootEntry.fetchTime != null && _queryCacheExpirationTime != null && rootEntry.fetchTime <= Date.now() - _queryCacheExpirationTime;\n if (rootEntryIsStale) {\n _this2._roots[\"delete\"](id);\n _this2.scheduleGC();\n } else {\n _this2._releaseBuffer.push(id);\n if (_this2._releaseBuffer.length > _this2._gcReleaseBufferSize) {\n var _id = _this2._releaseBuffer.shift();\n _this2._roots[\"delete\"](_id);\n _this2.scheduleGC();\n }\n }\n }\n };\n var rootEntry = this._roots.get(id);\n if (rootEntry != null) {\n if (rootEntry.refCount === 0) {\n this._releaseBuffer = this._releaseBuffer.filter(function (_id) {\n return _id !== id;\n });\n }\n rootEntry.refCount += 1;\n } else {\n this._roots.set(id, {\n operation: operation,\n refCount: 1,\n epoch: null,\n fetchTime: null\n });\n }\n return {\n dispose: dispose\n };\n };\n _proto.lookup = function lookup(selector) {\n var source = this.getSource();\n var snapshot = RelayReader.read(source, selector, this._resolverCache);\n if (process.env.NODE_ENV !== \"production\") {\n deepFreeze(snapshot);\n }\n return snapshot;\n };\n _proto.notify = function notify(sourceOperation, invalidateStore) {\n var _this3 = this;\n var log = this.__log;\n if (log != null) {\n log({\n name: 'store.notify.start',\n sourceOperation: sourceOperation\n });\n }\n this._currentWriteEpoch++;\n if (invalidateStore === true) {\n this._globalInvalidationEpoch = this._currentWriteEpoch;\n }\n if (RelayFeatureFlags.ENABLE_RELAY_RESOLVERS) {\n this._resolverCache.invalidateDataIDs(this._updatedRecordIDs);\n }\n var source = this.getSource();\n var updatedOwners = [];\n this._storeSubscriptions.updateSubscriptions(source, this._updatedRecordIDs, updatedOwners, sourceOperation);\n this._invalidationSubscriptions.forEach(function (subscription) {\n _this3._updateInvalidationSubscription(subscription, invalidateStore === true);\n });\n if (log != null) {\n log({\n name: 'store.notify.complete',\n sourceOperation: sourceOperation,\n updatedRecordIDs: this._updatedRecordIDs,\n invalidatedRecordIDs: this._invalidatedRecordIDs\n });\n }\n this._updatedRecordIDs.clear();\n this._invalidatedRecordIDs.clear();\n if (sourceOperation != null) {\n var id = sourceOperation.request.identifier;\n var rootEntry = this._roots.get(id);\n if (rootEntry != null) {\n rootEntry.epoch = this._currentWriteEpoch;\n rootEntry.fetchTime = Date.now();\n } else if (sourceOperation.request.node.params.operationKind === 'query' && this._gcReleaseBufferSize > 0 && this._releaseBuffer.length < this._gcReleaseBufferSize) {\n var temporaryRootEntry = {\n operation: sourceOperation,\n refCount: 0,\n epoch: this._currentWriteEpoch,\n fetchTime: Date.now()\n };\n this._releaseBuffer.push(id);\n this._roots.set(id, temporaryRootEntry);\n }\n }\n return updatedOwners;\n };\n _proto.publish = function publish(source, idsMarkedForInvalidation) {\n var target = this._getMutableRecordSource();\n updateTargetFromSource(target, source, this._currentWriteEpoch + 1, idsMarkedForInvalidation, this._updatedRecordIDs, this._invalidatedRecordIDs);\n var log = this.__log;\n if (log != null) {\n log({\n name: 'store.publish',\n source: source,\n optimistic: target === this._optimisticSource\n });\n }\n };\n _proto.subscribe = function subscribe(snapshot, callback) {\n return this._storeSubscriptions.subscribe(snapshot, callback);\n };\n _proto.holdGC = function holdGC() {\n var _this4 = this;\n if (this._gcRun) {\n this._gcRun = null;\n this._shouldScheduleGC = true;\n }\n this._gcHoldCounter++;\n var dispose = function dispose() {\n if (_this4._gcHoldCounter > 0) {\n _this4._gcHoldCounter--;\n if (_this4._gcHoldCounter === 0 && _this4._shouldScheduleGC) {\n _this4.scheduleGC();\n _this4._shouldScheduleGC = false;\n }\n }\n };\n return {\n dispose: dispose\n };\n };\n _proto.toJSON = function toJSON() {\n return 'RelayModernStore()';\n };\n _proto.getEpoch = function getEpoch() {\n return this._currentWriteEpoch;\n };\n _proto.__getUpdatedRecordIDs = function __getUpdatedRecordIDs() {\n return this._updatedRecordIDs;\n };\n _proto.lookupInvalidationState = function lookupInvalidationState(dataIDs) {\n var _this5 = this;\n var invalidations = new Map();\n dataIDs.forEach(function (dataID) {\n var _RelayModernRecord$ge;\n var record = _this5.getSource().get(dataID);\n invalidations.set(dataID, (_RelayModernRecord$ge = RelayModernRecord.getInvalidationEpoch(record)) !== null && _RelayModernRecord$ge !== void 0 ? _RelayModernRecord$ge : null);\n });\n invalidations.set('global', this._globalInvalidationEpoch);\n return {\n dataIDs: dataIDs,\n invalidations: invalidations\n };\n };\n _proto.checkInvalidationState = function checkInvalidationState(prevInvalidationState) {\n var latestInvalidationState = this.lookupInvalidationState(prevInvalidationState.dataIDs);\n var currentInvalidations = latestInvalidationState.invalidations;\n var prevInvalidations = prevInvalidationState.invalidations;\n if (currentInvalidations.get('global') !== prevInvalidations.get('global')) {\n return true;\n }\n var _iterator = (0, _createForOfIteratorHelper2[\"default\"])(prevInvalidationState.dataIDs),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var dataID = _step.value;\n if (currentInvalidations.get(dataID) !== prevInvalidations.get(dataID)) {\n return true;\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n return false;\n };\n _proto.subscribeToInvalidationState = function subscribeToInvalidationState(invalidationState, callback) {\n var _this6 = this;\n var subscription = {\n callback: callback,\n invalidationState: invalidationState\n };\n var dispose = function dispose() {\n _this6._invalidationSubscriptions[\"delete\"](subscription);\n };\n this._invalidationSubscriptions.add(subscription);\n return {\n dispose: dispose\n };\n };\n _proto._updateInvalidationSubscription = function _updateInvalidationSubscription(subscription, invalidatedStore) {\n var _this7 = this;\n var callback = subscription.callback,\n invalidationState = subscription.invalidationState;\n var dataIDs = invalidationState.dataIDs;\n var isSubscribedToInvalidatedIDs = invalidatedStore || dataIDs.some(function (dataID) {\n return _this7._invalidatedRecordIDs.has(dataID);\n });\n if (!isSubscribedToInvalidatedIDs) {\n return;\n }\n callback();\n };\n _proto.snapshot = function snapshot() {\n !(this._optimisticSource == null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayModernStore: Unexpected call to snapshot() while a previous ' + 'snapshot exists.') : invariant(false) : void 0;\n var log = this.__log;\n if (log != null) {\n log({\n name: 'store.snapshot'\n });\n }\n this._storeSubscriptions.snapshotSubscriptions(this.getSource());\n if (this._gcRun) {\n this._gcRun = null;\n this._shouldScheduleGC = true;\n }\n this._optimisticSource = RelayOptimisticRecordSource.create(this.getSource());\n };\n _proto.restore = function restore() {\n !(this._optimisticSource != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayModernStore: Unexpected call to restore(), expected a snapshot ' + 'to exist (make sure to call snapshot()).') : invariant(false) : void 0;\n var log = this.__log;\n if (log != null) {\n log({\n name: 'store.restore'\n });\n }\n this._optimisticSource = null;\n if (this._shouldScheduleGC) {\n this.scheduleGC();\n }\n this._storeSubscriptions.restoreSubscriptions();\n };\n _proto.scheduleGC = function scheduleGC() {\n if (this._gcHoldCounter > 0) {\n this._shouldScheduleGC = true;\n return;\n }\n if (this._gcRun) {\n return;\n }\n this._gcRun = this._collect();\n this._gcScheduler(this._gcStep);\n };\n _proto.__gc = function __gc() {\n if (this._optimisticSource != null) {\n return;\n }\n var gcRun = this._collect();\n while (!gcRun.next().done) {}\n };\n _proto._collect = function* _collect() {\n top: while (true) {\n var startEpoch = this._currentWriteEpoch;\n var references = new Set();\n var _iterator2 = (0, _createForOfIteratorHelper2[\"default\"])(this._roots.values()),\n _step2;\n try {\n for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n var operation = _step2.value.operation;\n var selector = operation.root;\n RelayReferenceMarker.mark(this._recordSource, selector, references, this._operationLoader, this._shouldProcessClientComponents);\n yield;\n if (startEpoch !== this._currentWriteEpoch) {\n continue top;\n }\n }\n } catch (err) {\n _iterator2.e(err);\n } finally {\n _iterator2.f();\n }\n var log = this.__log;\n if (log != null) {\n log({\n name: 'store.gc',\n references: references\n });\n }\n if (references.size === 0) {\n this._recordSource.clear();\n } else {\n var storeIDs = this._recordSource.getRecordIDs();\n for (var ii = 0; ii < storeIDs.length; ii++) {\n var dataID = storeIDs[ii];\n if (!references.has(dataID)) {\n this._recordSource.remove(dataID);\n }\n }\n }\n return;\n }\n };\n return RelayModernStore;\n}();\nfunction initializeRecordSource(target) {\n if (!target.has(ROOT_ID)) {\n var rootRecord = RelayModernRecord.create(ROOT_ID, ROOT_TYPE);\n target.set(ROOT_ID, rootRecord);\n }\n}\nfunction updateTargetFromSource(target, source, currentWriteEpoch, idsMarkedForInvalidation, updatedRecordIDs, invalidatedRecordIDs) {\n if (idsMarkedForInvalidation) {\n idsMarkedForInvalidation.forEach(function (dataID) {\n var targetRecord = target.get(dataID);\n var sourceRecord = source.get(dataID);\n if (sourceRecord === null) {\n return;\n }\n var nextRecord;\n if (targetRecord != null) {\n nextRecord = RelayModernRecord.clone(targetRecord);\n } else {\n nextRecord = sourceRecord != null ? RelayModernRecord.clone(sourceRecord) : null;\n }\n if (!nextRecord) {\n return;\n }\n RelayModernRecord.setValue(nextRecord, RelayStoreUtils.INVALIDATED_AT_KEY, currentWriteEpoch);\n invalidatedRecordIDs.add(dataID);\n target.set(dataID, nextRecord);\n });\n }\n var dataIDs = source.getRecordIDs();\n for (var ii = 0; ii < dataIDs.length; ii++) {\n var dataID = dataIDs[ii];\n var sourceRecord = source.get(dataID);\n var targetRecord = target.get(dataID);\n if (process.env.NODE_ENV !== \"production\") {\n if (sourceRecord) {\n RelayModernRecord.freeze(sourceRecord);\n }\n }\n if (sourceRecord && targetRecord) {\n var nextRecord = RelayModernRecord.update(targetRecord, sourceRecord);\n if (nextRecord !== targetRecord) {\n if (process.env.NODE_ENV !== \"production\") {\n RelayModernRecord.freeze(nextRecord);\n }\n updatedRecordIDs.add(dataID);\n target.set(dataID, nextRecord);\n }\n } else if (sourceRecord === null) {\n target[\"delete\"](dataID);\n if (targetRecord !== null) {\n updatedRecordIDs.add(dataID);\n }\n } else if (sourceRecord) {\n target.set(dataID, sourceRecord);\n updatedRecordIDs.add(dataID);\n }\n }\n}\nfunction getAvailabilityStatus(operationAvailability, operationLastWrittenAt, operationFetchTime, queryCacheExpirationTime) {\n var mostRecentlyInvalidatedAt = operationAvailability.mostRecentlyInvalidatedAt,\n status = operationAvailability.status;\n if (typeof mostRecentlyInvalidatedAt === 'number') {\n if (operationLastWrittenAt == null || mostRecentlyInvalidatedAt > operationLastWrittenAt) {\n return {\n status: 'stale'\n };\n }\n }\n if (status === 'missing') {\n return {\n status: 'missing'\n };\n }\n if (operationFetchTime != null && queryCacheExpirationTime != null) {\n var isStale = operationFetchTime <= Date.now() - queryCacheExpirationTime;\n if (isStale) {\n return {\n status: 'stale'\n };\n }\n }\n return {\n status: 'available',\n fetchTime: operationFetchTime !== null && operationFetchTime !== void 0 ? operationFetchTime : null\n };\n}\nmodule.exports = RelayModernStore;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _createForOfIteratorHelper2 = _interopRequireDefault(require(\"@babel/runtime/helpers/createForOfIteratorHelper\"));\nvar invariant = require('invariant');\nvar RelayOperationTracker = /*#__PURE__*/function () {\n function RelayOperationTracker() {\n this._ownersToPendingOperations = new Map();\n this._pendingOperationsToOwners = new Map();\n this._ownersToPendingPromise = new Map();\n }\n var _proto = RelayOperationTracker.prototype;\n _proto.update = function update(pendingOperation, affectedOwners) {\n if (affectedOwners.size === 0) {\n return;\n }\n var pendingOperationIdentifier = pendingOperation.identifier;\n var newlyAffectedOwnersIdentifier = new Set();\n var _iterator = (0, _createForOfIteratorHelper2[\"default\"])(affectedOwners),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var owner = _step.value;\n var ownerIdentifier = owner.identifier;\n var pendingOperationsAffectingOwner = this._ownersToPendingOperations.get(ownerIdentifier);\n if (pendingOperationsAffectingOwner != null) {\n if (!pendingOperationsAffectingOwner.has(pendingOperationIdentifier)) {\n pendingOperationsAffectingOwner.set(pendingOperationIdentifier, pendingOperation);\n newlyAffectedOwnersIdentifier.add(ownerIdentifier);\n }\n } else {\n this._ownersToPendingOperations.set(ownerIdentifier, new Map([[pendingOperationIdentifier, pendingOperation]]));\n newlyAffectedOwnersIdentifier.add(ownerIdentifier);\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n if (newlyAffectedOwnersIdentifier.size === 0) {\n return;\n }\n var ownersAffectedByPendingOperation = this._pendingOperationsToOwners.get(pendingOperationIdentifier) || new Set();\n var _iterator2 = (0, _createForOfIteratorHelper2[\"default\"])(newlyAffectedOwnersIdentifier),\n _step2;\n try {\n for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n var _ownerIdentifier = _step2.value;\n this._resolveOwnerResolvers(_ownerIdentifier);\n ownersAffectedByPendingOperation.add(_ownerIdentifier);\n }\n } catch (err) {\n _iterator2.e(err);\n } finally {\n _iterator2.f();\n }\n this._pendingOperationsToOwners.set(pendingOperationIdentifier, ownersAffectedByPendingOperation);\n };\n _proto.complete = function complete(pendingOperation) {\n var pendingOperationIdentifier = pendingOperation.identifier;\n var affectedOwnersIdentifier = this._pendingOperationsToOwners.get(pendingOperationIdentifier);\n if (affectedOwnersIdentifier == null) {\n return;\n }\n var completedOwnersIdentifier = new Set();\n var updatedOwnersIdentifier = new Set();\n var _iterator3 = (0, _createForOfIteratorHelper2[\"default\"])(affectedOwnersIdentifier),\n _step3;\n try {\n for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {\n var ownerIdentifier = _step3.value;\n var pendingOperationsAffectingOwner = this._ownersToPendingOperations.get(ownerIdentifier);\n if (!pendingOperationsAffectingOwner) {\n continue;\n }\n pendingOperationsAffectingOwner[\"delete\"](pendingOperationIdentifier);\n if (pendingOperationsAffectingOwner.size > 0) {\n updatedOwnersIdentifier.add(ownerIdentifier);\n } else {\n completedOwnersIdentifier.add(ownerIdentifier);\n }\n }\n } catch (err) {\n _iterator3.e(err);\n } finally {\n _iterator3.f();\n }\n var _iterator4 = (0, _createForOfIteratorHelper2[\"default\"])(completedOwnersIdentifier),\n _step4;\n try {\n for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {\n var _ownerIdentifier2 = _step4.value;\n this._resolveOwnerResolvers(_ownerIdentifier2);\n this._ownersToPendingOperations[\"delete\"](_ownerIdentifier2);\n }\n } catch (err) {\n _iterator4.e(err);\n } finally {\n _iterator4.f();\n }\n var _iterator5 = (0, _createForOfIteratorHelper2[\"default\"])(updatedOwnersIdentifier),\n _step5;\n try {\n for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {\n var _ownerIdentifier3 = _step5.value;\n this._resolveOwnerResolvers(_ownerIdentifier3);\n }\n } catch (err) {\n _iterator5.e(err);\n } finally {\n _iterator5.f();\n }\n this._pendingOperationsToOwners[\"delete\"](pendingOperationIdentifier);\n };\n _proto._resolveOwnerResolvers = function _resolveOwnerResolvers(ownerIdentifier) {\n var promiseEntry = this._ownersToPendingPromise.get(ownerIdentifier);\n if (promiseEntry != null) {\n promiseEntry.resolve();\n }\n this._ownersToPendingPromise[\"delete\"](ownerIdentifier);\n };\n _proto.getPendingOperationsAffectingOwner = function getPendingOperationsAffectingOwner(owner) {\n var ownerIdentifier = owner.identifier;\n var pendingOperationsForOwner = this._ownersToPendingOperations.get(ownerIdentifier);\n if (pendingOperationsForOwner == null || pendingOperationsForOwner.size === 0) {\n return null;\n }\n var cachedPromiseEntry = this._ownersToPendingPromise.get(ownerIdentifier);\n if (cachedPromiseEntry != null) {\n return {\n promise: cachedPromiseEntry.promise,\n pendingOperations: cachedPromiseEntry.pendingOperations\n };\n }\n var resolve;\n var promise = new Promise(function (r) {\n resolve = r;\n });\n !(resolve != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayOperationTracker: Expected resolver to be defined. If you' + 'are seeing this, it is likely a bug in Relay.') : invariant(false) : void 0;\n var pendingOperations = Array.from(pendingOperationsForOwner.values());\n this._ownersToPendingPromise.set(ownerIdentifier, {\n promise: promise,\n resolve: resolve,\n pendingOperations: pendingOperations\n });\n return {\n promise: promise,\n pendingOperations: pendingOperations\n };\n };\n return RelayOperationTracker;\n}();\nmodule.exports = RelayOperationTracker;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _objectSpread2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar RelayModernRecord = require('./RelayModernRecord');\nvar RelayRecordSource = require('./RelayRecordSource');\nvar invariant = require('invariant');\nvar UNPUBLISH_RECORD_SENTINEL = RelayModernRecord.fromObject(Object.freeze({\n __UNPUBLISH_RECORD_SENTINEL: true\n}));\nvar RelayOptimisticRecordSource = /*#__PURE__*/function () {\n function RelayOptimisticRecordSource(base) {\n this._base = base;\n this._sink = RelayRecordSource.create();\n }\n var _proto = RelayOptimisticRecordSource.prototype;\n _proto.has = function has(dataID) {\n if (this._sink.has(dataID)) {\n var sinkRecord = this._sink.get(dataID);\n return sinkRecord !== UNPUBLISH_RECORD_SENTINEL;\n } else {\n return this._base.has(dataID);\n }\n };\n _proto.get = function get(dataID) {\n if (this._sink.has(dataID)) {\n var sinkRecord = this._sink.get(dataID);\n if (sinkRecord === UNPUBLISH_RECORD_SENTINEL) {\n return undefined;\n } else {\n return sinkRecord;\n }\n } else {\n return this._base.get(dataID);\n }\n };\n _proto.getStatus = function getStatus(dataID) {\n var record = this.get(dataID);\n if (record === undefined) {\n return 'UNKNOWN';\n } else if (record === null) {\n return 'NONEXISTENT';\n } else {\n return 'EXISTENT';\n }\n };\n _proto.clear = function clear() {\n this._base = RelayRecordSource.create();\n this._sink.clear();\n };\n _proto[\"delete\"] = function _delete(dataID) {\n this._sink[\"delete\"](dataID);\n };\n _proto.remove = function remove(dataID) {\n this._sink.set(dataID, UNPUBLISH_RECORD_SENTINEL);\n };\n _proto.set = function set(dataID, record) {\n this._sink.set(dataID, record);\n };\n _proto.getRecordIDs = function getRecordIDs() {\n return Object.keys(this.toJSON());\n };\n _proto.size = function size() {\n return Object.keys(this.toJSON()).length;\n };\n _proto.toJSON = function toJSON() {\n var _this = this;\n var merged = (0, _objectSpread2[\"default\"])({}, this._base.toJSON());\n this._sink.getRecordIDs().forEach(function (dataID) {\n var record = _this.get(dataID);\n if (record === undefined) {\n delete merged[dataID];\n } else {\n merged[dataID] = RelayModernRecord.toJSON(record);\n }\n });\n return merged;\n };\n _proto.getOptimisticRecordIDs = function getOptimisticRecordIDs() {\n return new Set(this._sink.getRecordIDs());\n };\n return RelayOptimisticRecordSource;\n}();\nfunction create(base) {\n return new RelayOptimisticRecordSource(base);\n}\nfunction getOptimisticRecordIDs(source) {\n !(source instanceof RelayOptimisticRecordSource) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'getOptimisticRecordIDs: Instance of RelayOptimisticRecordSource is expected') : invariant(false) : void 0;\n return source.getOptimisticRecordIDs();\n}\nmodule.exports = {\n create: create,\n getOptimisticRecordIDs: getOptimisticRecordIDs\n};","'use strict';\n\nvar _global$ErrorUtils$ap, _global$ErrorUtils;\nvar RelayRecordSourceMutator = require('../mutations/RelayRecordSourceMutator');\nvar RelayRecordSourceProxy = require('../mutations/RelayRecordSourceProxy');\nvar RelayRecordSourceSelectorProxy = require('../mutations/RelayRecordSourceSelectorProxy');\nvar RelayReader = require('./RelayReader');\nvar RelayRecordSource = require('./RelayRecordSource');\nvar invariant = require('invariant');\nvar warning = require(\"fbjs/lib/warning\");\nvar _global = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : undefined;\nvar applyWithGuard = (_global$ErrorUtils$ap = _global === null || _global === void 0 ? void 0 : (_global$ErrorUtils = _global.ErrorUtils) === null || _global$ErrorUtils === void 0 ? void 0 : _global$ErrorUtils.applyWithGuard) !== null && _global$ErrorUtils$ap !== void 0 ? _global$ErrorUtils$ap : function (callback, context, args, onError, name) {\n return callback.apply(context, args);\n};\nvar RelayPublishQueue = /*#__PURE__*/function () {\n function RelayPublishQueue(store, handlerProvider, getDataID, missingFieldHandlers) {\n this._hasStoreSnapshot = false;\n this._handlerProvider = handlerProvider || null;\n this._pendingBackupRebase = false;\n this._pendingData = new Set();\n this._pendingOptimisticUpdates = new Set();\n this._store = store;\n this._appliedOptimisticUpdates = new Set();\n this._gcHold = null;\n this._getDataID = getDataID;\n this._missingFieldHandlers = missingFieldHandlers;\n }\n var _proto = RelayPublishQueue.prototype;\n _proto.applyUpdate = function applyUpdate(updater) {\n !(!this._appliedOptimisticUpdates.has(updater) && !this._pendingOptimisticUpdates.has(updater)) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayPublishQueue: Cannot apply the same update function more than ' + 'once concurrently.') : invariant(false) : void 0;\n this._pendingOptimisticUpdates.add(updater);\n };\n _proto.revertUpdate = function revertUpdate(updater) {\n if (this._pendingOptimisticUpdates.has(updater)) {\n this._pendingOptimisticUpdates[\"delete\"](updater);\n } else if (this._appliedOptimisticUpdates.has(updater)) {\n this._pendingBackupRebase = true;\n this._appliedOptimisticUpdates[\"delete\"](updater);\n }\n };\n _proto.revertAll = function revertAll() {\n this._pendingBackupRebase = true;\n this._pendingOptimisticUpdates.clear();\n this._appliedOptimisticUpdates.clear();\n };\n _proto.commitPayload = function commitPayload(operation, payload, updater) {\n this._pendingBackupRebase = true;\n this._pendingData.add({\n kind: 'payload',\n operation: operation,\n payload: payload,\n updater: updater\n });\n };\n _proto.commitUpdate = function commitUpdate(updater) {\n this._pendingBackupRebase = true;\n this._pendingData.add({\n kind: 'updater',\n updater: updater\n });\n };\n _proto.commitSource = function commitSource(source) {\n this._pendingBackupRebase = true;\n this._pendingData.add({\n kind: 'source',\n source: source\n });\n };\n _proto.run = function run(sourceOperation) {\n var runWillClearGcHold = this._appliedOptimisticUpdates === 0 && !!this._gcHold;\n var runIsANoop = !this._pendingBackupRebase && this._pendingOptimisticUpdates.size === 0 && !runWillClearGcHold;\n if (process.env.NODE_ENV !== \"production\") {\n process.env.NODE_ENV !== \"production\" ? warning(!runIsANoop, 'RelayPublishQueue.run was called, but the call would have been a noop.') : void 0;\n process.env.NODE_ENV !== \"production\" ? warning(this._isRunning !== true, 'A store update was detected within another store update. Please ' + \"make sure new store updates aren't being executed within an \" + 'updater function for a different update.') : void 0;\n this._isRunning = true;\n }\n if (runIsANoop) {\n if (process.env.NODE_ENV !== \"production\") {\n this._isRunning = false;\n }\n return [];\n }\n if (this._pendingBackupRebase) {\n if (this._hasStoreSnapshot) {\n this._store.restore();\n this._hasStoreSnapshot = false;\n }\n }\n var invalidatedStore = this._commitData();\n if (this._pendingOptimisticUpdates.size || this._pendingBackupRebase && this._appliedOptimisticUpdates.size) {\n if (!this._hasStoreSnapshot) {\n this._store.snapshot();\n this._hasStoreSnapshot = true;\n }\n this._applyUpdates();\n }\n this._pendingBackupRebase = false;\n if (this._appliedOptimisticUpdates.size > 0) {\n if (!this._gcHold) {\n this._gcHold = this._store.holdGC();\n }\n } else {\n if (this._gcHold) {\n this._gcHold.dispose();\n this._gcHold = null;\n }\n }\n if (process.env.NODE_ENV !== \"production\") {\n this._isRunning = false;\n }\n return this._store.notify(sourceOperation, invalidatedStore);\n };\n _proto._publishSourceFromPayload = function _publishSourceFromPayload(pendingPayload) {\n var _this = this;\n var payload = pendingPayload.payload,\n operation = pendingPayload.operation,\n updater = pendingPayload.updater;\n var source = payload.source,\n fieldPayloads = payload.fieldPayloads;\n var mutator = new RelayRecordSourceMutator(this._store.getSource(), source);\n var recordSourceProxy = new RelayRecordSourceProxy(mutator, this._getDataID, this._handlerProvider, this._missingFieldHandlers);\n if (fieldPayloads && fieldPayloads.length) {\n fieldPayloads.forEach(function (fieldPayload) {\n var handler = _this._handlerProvider && _this._handlerProvider(fieldPayload.handle);\n !handler ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayModernEnvironment: Expected a handler to be provided for ' + 'handle `%s`.', fieldPayload.handle) : invariant(false) : void 0;\n handler.update(recordSourceProxy, fieldPayload);\n });\n }\n if (updater) {\n var selector = operation.fragment;\n !(selector != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayModernEnvironment: Expected a selector to be provided with updater function.') : invariant(false) : void 0;\n var recordSourceSelectorProxy = new RelayRecordSourceSelectorProxy(mutator, recordSourceProxy, selector, this._missingFieldHandlers);\n var selectorData = lookupSelector(source, selector);\n updater(recordSourceSelectorProxy, selectorData);\n }\n var idsMarkedForInvalidation = recordSourceProxy.getIDsMarkedForInvalidation();\n this._store.publish(source, idsMarkedForInvalidation);\n return recordSourceProxy.isStoreMarkedForInvalidation();\n };\n _proto._commitData = function _commitData() {\n var _this2 = this;\n if (!this._pendingData.size) {\n return false;\n }\n var invalidatedStore = false;\n this._pendingData.forEach(function (data) {\n if (data.kind === 'payload') {\n var payloadInvalidatedStore = _this2._publishSourceFromPayload(data);\n invalidatedStore = invalidatedStore || payloadInvalidatedStore;\n } else if (data.kind === 'source') {\n var source = data.source;\n _this2._store.publish(source);\n } else {\n var updater = data.updater;\n var sink = RelayRecordSource.create();\n var mutator = new RelayRecordSourceMutator(_this2._store.getSource(), sink);\n var recordSourceProxy = new RelayRecordSourceProxy(mutator, _this2._getDataID, _this2._handlerProvider, _this2._missingFieldHandlers);\n applyWithGuard(updater, null, [recordSourceProxy], null, 'RelayPublishQueue:commitData');\n invalidatedStore = invalidatedStore || recordSourceProxy.isStoreMarkedForInvalidation();\n var idsMarkedForInvalidation = recordSourceProxy.getIDsMarkedForInvalidation();\n _this2._store.publish(sink, idsMarkedForInvalidation);\n }\n });\n this._pendingData.clear();\n return invalidatedStore;\n };\n _proto._applyUpdates = function _applyUpdates() {\n var _this3 = this;\n var sink = RelayRecordSource.create();\n var mutator = new RelayRecordSourceMutator(this._store.getSource(), sink);\n var recordSourceProxy = new RelayRecordSourceProxy(mutator, this._getDataID, this._handlerProvider, this._missingFieldHandlers);\n var processUpdate = function processUpdate(optimisticUpdate) {\n if (optimisticUpdate.storeUpdater) {\n var storeUpdater = optimisticUpdate.storeUpdater;\n applyWithGuard(storeUpdater, null, [recordSourceProxy], null, 'RelayPublishQueue:applyUpdates');\n } else {\n var operation = optimisticUpdate.operation,\n payload = optimisticUpdate.payload,\n updater = optimisticUpdate.updater;\n var source = payload.source,\n fieldPayloads = payload.fieldPayloads;\n if (source) {\n recordSourceProxy.publishSource(source, fieldPayloads);\n }\n if (updater) {\n var selectorData;\n if (source) {\n selectorData = lookupSelector(source, operation.fragment);\n }\n var recordSourceSelectorProxy = new RelayRecordSourceSelectorProxy(mutator, recordSourceProxy, operation.fragment, _this3._missingFieldHandlers);\n applyWithGuard(updater, null, [recordSourceSelectorProxy, selectorData], null, 'RelayPublishQueue:applyUpdates');\n }\n }\n };\n if (this._pendingBackupRebase && this._appliedOptimisticUpdates.size) {\n this._appliedOptimisticUpdates.forEach(processUpdate);\n }\n if (this._pendingOptimisticUpdates.size) {\n this._pendingOptimisticUpdates.forEach(function (optimisticUpdate) {\n processUpdate(optimisticUpdate);\n _this3._appliedOptimisticUpdates.add(optimisticUpdate);\n });\n this._pendingOptimisticUpdates.clear();\n }\n this._store.publish(sink);\n };\n return RelayPublishQueue;\n}();\nfunction lookupSelector(source, selector) {\n var selectorData = RelayReader.read(source, selector).data;\n if (process.env.NODE_ENV !== \"production\") {\n var deepFreeze = require('../util/deepFreeze');\n if (selectorData) {\n deepFreeze(selectorData);\n }\n }\n return selectorData;\n}\nmodule.exports = RelayPublishQueue;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _defineProperty2 = _interopRequireDefault(require(\"@babel/runtime/helpers/defineProperty\"));\nvar _createForOfIteratorHelper2 = _interopRequireDefault(require(\"@babel/runtime/helpers/createForOfIteratorHelper\"));\nvar _toConsumableArray2 = _interopRequireDefault(require(\"@babel/runtime/helpers/toConsumableArray\"));\nvar _require = require('../util/RelayConcreteNode'),\n ACTOR_CHANGE = _require.ACTOR_CHANGE,\n ALIASED_FRAGMENT_SPREAD = _require.ALIASED_FRAGMENT_SPREAD,\n ALIASED_INLINE_FRAGMENT_SPREAD = _require.ALIASED_INLINE_FRAGMENT_SPREAD,\n CLIENT_EDGE_TO_CLIENT_OBJECT = _require.CLIENT_EDGE_TO_CLIENT_OBJECT,\n CLIENT_EDGE_TO_SERVER_OBJECT = _require.CLIENT_EDGE_TO_SERVER_OBJECT,\n CLIENT_EXTENSION = _require.CLIENT_EXTENSION,\n CONDITION = _require.CONDITION,\n DEFER = _require.DEFER,\n FRAGMENT_SPREAD = _require.FRAGMENT_SPREAD,\n INLINE_DATA_FRAGMENT_SPREAD = _require.INLINE_DATA_FRAGMENT_SPREAD,\n INLINE_FRAGMENT = _require.INLINE_FRAGMENT,\n LINKED_FIELD = _require.LINKED_FIELD,\n MODULE_IMPORT = _require.MODULE_IMPORT,\n RELAY_LIVE_RESOLVER = _require.RELAY_LIVE_RESOLVER,\n RELAY_RESOLVER = _require.RELAY_RESOLVER,\n REQUIRED_FIELD = _require.REQUIRED_FIELD,\n SCALAR_FIELD = _require.SCALAR_FIELD,\n STREAM = _require.STREAM;\nvar RelayFeatureFlags = require('../util/RelayFeatureFlags');\nvar _require2 = require('./experimental-live-resolvers/LiveResolverSuspenseSentinel'),\n isSuspenseSentinel = _require2.isSuspenseSentinel;\nvar RelayConcreteVariables = require('./RelayConcreteVariables');\nvar RelayModernRecord = require('./RelayModernRecord');\nvar _require3 = require('./RelayStoreUtils'),\n CLIENT_EDGE_TRAVERSAL_PATH = _require3.CLIENT_EDGE_TRAVERSAL_PATH,\n FRAGMENT_OWNER_KEY = _require3.FRAGMENT_OWNER_KEY,\n FRAGMENT_PROP_NAME_KEY = _require3.FRAGMENT_PROP_NAME_KEY,\n FRAGMENTS_KEY = _require3.FRAGMENTS_KEY,\n ID_KEY = _require3.ID_KEY,\n MODULE_COMPONENT_KEY = _require3.MODULE_COMPONENT_KEY,\n ROOT_ID = _require3.ROOT_ID,\n getArgumentValues = _require3.getArgumentValues,\n getModuleComponentKey = _require3.getModuleComponentKey,\n getStorageKey = _require3.getStorageKey;\nvar _require4 = require('./ResolverCache'),\n NoopResolverCache = _require4.NoopResolverCache;\nvar _require5 = require('./ResolverFragments'),\n RESOLVER_FRAGMENT_MISSING_DATA_SENTINEL = _require5.RESOLVER_FRAGMENT_MISSING_DATA_SENTINEL,\n withResolverContext = _require5.withResolverContext;\nvar _require6 = require('./TypeID'),\n generateTypeID = _require6.generateTypeID;\nvar invariant = require('invariant');\nfunction read(recordSource, selector, resolverCache) {\n var reader = new RelayReader(recordSource, selector, resolverCache !== null && resolverCache !== void 0 ? resolverCache : new NoopResolverCache());\n return reader.read();\n}\nvar RelayReader = /*#__PURE__*/function () {\n function RelayReader(recordSource, selector, resolverCache) {\n var _selector$clientEdgeT;\n this._clientEdgeTraversalPath = RelayFeatureFlags.ENABLE_CLIENT_EDGES && (_selector$clientEdgeT = selector.clientEdgeTraversalPath) !== null && _selector$clientEdgeT !== void 0 && _selector$clientEdgeT.length ? (0, _toConsumableArray2[\"default\"])(selector.clientEdgeTraversalPath) : [];\n this._missingClientEdges = [];\n this._missingLiveResolverFields = [];\n this._isMissingData = false;\n this._isWithinUnmatchedTypeRefinement = false;\n this._missingRequiredFields = null;\n this._errorResponseFields = null;\n this._owner = selector.owner;\n this._recordSource = recordSource;\n this._seenRecords = new Set();\n this._selector = selector;\n this._variables = selector.variables;\n this._resolverCache = resolverCache;\n this._resolverErrors = [];\n this._fragmentName = selector.node.name;\n this._updatedDataIDs = new Set();\n }\n var _proto = RelayReader.prototype;\n _proto.read = function read() {\n var _this$_selector = this._selector,\n node = _this$_selector.node,\n dataID = _this$_selector.dataID,\n isWithinUnmatchedTypeRefinement = _this$_selector.isWithinUnmatchedTypeRefinement;\n var abstractKey = node.abstractKey;\n var record = this._recordSource.get(dataID);\n var isDataExpectedToBePresent = !isWithinUnmatchedTypeRefinement;\n if (isDataExpectedToBePresent && abstractKey == null && record != null) {\n var recordType = RelayModernRecord.getType(record);\n if (recordType !== node.type && dataID !== ROOT_ID) {\n isDataExpectedToBePresent = false;\n }\n }\n if (isDataExpectedToBePresent && abstractKey != null && record != null) {\n var implementsInterface = this._implementsInterface(record, abstractKey);\n if (implementsInterface === false) {\n isDataExpectedToBePresent = false;\n } else if (implementsInterface == null) {\n this._isMissingData = true;\n }\n }\n this._isWithinUnmatchedTypeRefinement = !isDataExpectedToBePresent;\n var data = this._traverse(node, dataID, null);\n if (this._updatedDataIDs.size > 0) {\n this._resolverCache.notifyUpdatedSubscribers(this._updatedDataIDs);\n this._updatedDataIDs.clear();\n }\n return {\n data: data,\n isMissingData: this._isMissingData && isDataExpectedToBePresent,\n missingClientEdges: RelayFeatureFlags.ENABLE_CLIENT_EDGES && this._missingClientEdges.length ? this._missingClientEdges : null,\n missingLiveResolverFields: this._missingLiveResolverFields,\n seenRecords: this._seenRecords,\n selector: this._selector,\n missingRequiredFields: this._missingRequiredFields,\n relayResolverErrors: this._resolverErrors,\n errorResponseFields: this._errorResponseFields\n };\n };\n _proto._maybeAddErrorResponseFields = function _maybeAddErrorResponseFields(record, storageKey) {\n if (!RelayFeatureFlags.ENABLE_FIELD_ERROR_HANDLING) {\n return;\n }\n var errors = RelayModernRecord.getErrors(record, storageKey);\n if (errors == null) {\n return;\n }\n var owner = this._fragmentName;\n if (this._errorResponseFields == null) {\n this._errorResponseFields = [];\n }\n var _iterator = (0, _createForOfIteratorHelper2[\"default\"])(errors),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var _error$path;\n var error = _step.value;\n this._errorResponseFields.push({\n owner: owner,\n path: ((_error$path = error.path) !== null && _error$path !== void 0 ? _error$path : []).join('.'),\n error: error\n });\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n };\n _proto._markDataAsMissing = function _markDataAsMissing() {\n this._isMissingData = true;\n if (RelayFeatureFlags.ENABLE_CLIENT_EDGES && this._clientEdgeTraversalPath.length) {\n var top = this._clientEdgeTraversalPath[this._clientEdgeTraversalPath.length - 1];\n if (top !== null) {\n this._missingClientEdges.push({\n request: top.readerClientEdge.operation,\n clientEdgeDestinationID: top.clientEdgeDestinationID\n });\n }\n }\n };\n _proto._traverse = function _traverse(node, dataID, prevData) {\n var record = this._recordSource.get(dataID);\n this._seenRecords.add(dataID);\n if (record == null) {\n if (record === undefined) {\n this._markDataAsMissing();\n }\n return record;\n }\n var data = prevData || {};\n var hadRequiredData = this._traverseSelections(node.selections, record, data);\n return hadRequiredData ? data : null;\n };\n _proto._getVariableValue = function _getVariableValue(name) {\n !this._variables.hasOwnProperty(name) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayReader(): Undefined variable `%s`.', name) : invariant(false) : void 0;\n return this._variables[name];\n };\n _proto._maybeReportUnexpectedNull = function _maybeReportUnexpectedNull(fieldPath, action) {\n var _this$_missingRequire;\n if (((_this$_missingRequire = this._missingRequiredFields) === null || _this$_missingRequire === void 0 ? void 0 : _this$_missingRequire.action) === 'THROW') {\n return;\n }\n var owner = this._fragmentName;\n switch (action) {\n case 'THROW':\n this._missingRequiredFields = {\n action: action,\n field: {\n path: fieldPath,\n owner: owner\n }\n };\n return;\n case 'LOG':\n if (this._missingRequiredFields == null) {\n this._missingRequiredFields = {\n action: action,\n fields: [{\n path: fieldPath,\n owner: owner\n }]\n };\n } else {\n this._missingRequiredFields = {\n action: action,\n fields: [].concat((0, _toConsumableArray2[\"default\"])(this._missingRequiredFields.fields), [{\n path: fieldPath,\n owner: owner\n }])\n };\n }\n return;\n default:\n action;\n }\n };\n _proto._traverseSelections = function _traverseSelections(selections, record, data) {\n for (var i = 0; i < selections.length; i++) {\n var selection = selections[i];\n switch (selection.kind) {\n case REQUIRED_FIELD:\n {\n var fieldValue = this._readRequiredField(selection, record, data);\n if (fieldValue == null) {\n var action = selection.action;\n if (action !== 'NONE') {\n this._maybeReportUnexpectedNull(selection.path, action);\n }\n return false;\n }\n break;\n }\n case SCALAR_FIELD:\n this._readScalar(selection, record, data);\n break;\n case LINKED_FIELD:\n if (selection.plural) {\n this._readPluralLink(selection, record, data);\n } else {\n this._readLink(selection, record, data);\n }\n break;\n case CONDITION:\n var conditionValue = Boolean(this._getVariableValue(selection.condition));\n if (conditionValue === selection.passingValue) {\n var hasExpectedData = this._traverseSelections(selection.selections, record, data);\n if (!hasExpectedData) {\n return false;\n }\n }\n break;\n case INLINE_FRAGMENT:\n {\n if (this._readInlineFragment(selection, record, data) === false) {\n return false;\n }\n break;\n }\n case RELAY_LIVE_RESOLVER:\n case RELAY_RESOLVER:\n {\n if (!RelayFeatureFlags.ENABLE_RELAY_RESOLVERS) {\n throw new Error('Relay Resolver fields are not yet supported.');\n }\n this._readResolverField(selection, record, data);\n break;\n }\n case FRAGMENT_SPREAD:\n this._createFragmentPointer(selection, record, data);\n break;\n case ALIASED_FRAGMENT_SPREAD:\n data[selection.name] = this._createAliasedFragmentSpread(selection, record);\n break;\n case ALIASED_INLINE_FRAGMENT_SPREAD:\n {\n var _fieldValue = this._readInlineFragment(selection.fragment, record, {});\n if (_fieldValue === false) {\n _fieldValue = null;\n }\n data[selection.name] = _fieldValue;\n break;\n }\n case MODULE_IMPORT:\n this._readModuleImport(selection, record, data);\n break;\n case INLINE_DATA_FRAGMENT_SPREAD:\n this._createInlineDataOrResolverFragmentPointer(selection, record, data);\n break;\n case DEFER:\n case CLIENT_EXTENSION:\n {\n var isMissingData = this._isMissingData;\n var alreadyMissingClientEdges = this._missingClientEdges.length;\n if (RelayFeatureFlags.ENABLE_CLIENT_EDGES) {\n this._clientEdgeTraversalPath.push(null);\n }\n var _hasExpectedData = this._traverseSelections(selection.selections, record, data);\n this._isMissingData = isMissingData || this._missingClientEdges.length > alreadyMissingClientEdges || this._missingLiveResolverFields.length > 0;\n if (RelayFeatureFlags.ENABLE_CLIENT_EDGES) {\n this._clientEdgeTraversalPath.pop();\n }\n if (!_hasExpectedData) {\n return false;\n }\n break;\n }\n case STREAM:\n {\n var _hasExpectedData2 = this._traverseSelections(selection.selections, record, data);\n if (!_hasExpectedData2) {\n return false;\n }\n break;\n }\n case ACTOR_CHANGE:\n this._readActorChange(selection, record, data);\n break;\n case CLIENT_EDGE_TO_CLIENT_OBJECT:\n case CLIENT_EDGE_TO_SERVER_OBJECT:\n if (RelayFeatureFlags.ENABLE_CLIENT_EDGES) {\n this._readClientEdge(selection, record, data);\n } else {\n throw new Error('Client edges are not yet supported.');\n }\n break;\n default:\n selection;\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayReader(): Unexpected ast kind `%s`.', selection.kind) : invariant(false) : void 0;\n }\n }\n return true;\n };\n _proto._readRequiredField = function _readRequiredField(selection, record, data) {\n switch (selection.field.kind) {\n case SCALAR_FIELD:\n return this._readScalar(selection.field, record, data);\n case LINKED_FIELD:\n if (selection.field.plural) {\n return this._readPluralLink(selection.field, record, data);\n } else {\n return this._readLink(selection.field, record, data);\n }\n case RELAY_RESOLVER:\n if (!RelayFeatureFlags.ENABLE_RELAY_RESOLVERS) {\n throw new Error('Relay Resolver fields are not yet supported.');\n }\n return this._readResolverField(selection.field, record, data);\n case RELAY_LIVE_RESOLVER:\n if (!RelayFeatureFlags.ENABLE_RELAY_RESOLVERS) {\n throw new Error('Relay Resolver fields are not yet supported.');\n }\n return this._readResolverField(selection.field, record, data);\n case CLIENT_EDGE_TO_CLIENT_OBJECT:\n case CLIENT_EDGE_TO_SERVER_OBJECT:\n if (!RelayFeatureFlags.ENABLE_RELAY_RESOLVERS) {\n throw new Error('Relay Resolver fields are not yet supported.');\n }\n return this._readClientEdge(selection.field, record, data);\n default:\n selection.field.kind;\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayReader(): Unexpected ast kind `%s`.', selection.kind) : invariant(false) : void 0;\n }\n };\n _proto._readResolverField = function _readResolverField(field, record, data) {\n var _field$alias;\n var parentRecordID = RelayModernRecord.getDataID(record);\n var result = this._readResolverFieldImpl(field, parentRecordID);\n var applicationName = (_field$alias = field.alias) !== null && _field$alias !== void 0 ? _field$alias : field.name;\n data[applicationName] = result;\n return result;\n };\n _proto._readResolverFieldImpl = function _readResolverFieldImpl(field, parentRecordID) {\n var _this = this;\n var fragment = field.fragment;\n var snapshot;\n var getDataForResolverFragment = function getDataForResolverFragment(singularReaderSelector) {\n if (snapshot != null) {\n return {\n data: snapshot.data,\n isMissingData: snapshot.isMissingData\n };\n }\n snapshot = read(_this._recordSource, singularReaderSelector, _this._resolverCache);\n return {\n data: snapshot.data,\n isMissingData: snapshot.isMissingData\n };\n };\n var evaluate = function evaluate() {\n if (fragment != null) {\n var key = {\n __id: parentRecordID,\n __fragmentOwner: _this._owner,\n __fragments: (0, _defineProperty2[\"default\"])({}, fragment.name, fragment.args ? getArgumentValues(fragment.args, _this._variables) : {})\n };\n var resolverContext = {\n getDataForResolverFragment: getDataForResolverFragment\n };\n return withResolverContext(resolverContext, function () {\n var _getResolverValue = getResolverValue(field, _this._variables, key),\n resolverResult = _getResolverValue[0],\n resolverError = _getResolverValue[1];\n return {\n resolverResult: resolverResult,\n snapshot: snapshot,\n error: resolverError\n };\n });\n } else {\n var _getResolverValue2 = getResolverValue(field, _this._variables, null),\n resolverResult = _getResolverValue2[0],\n _resolverError = _getResolverValue2[1];\n return {\n resolverResult: resolverResult,\n snapshot: undefined,\n error: _resolverError\n };\n }\n };\n var _this$_resolverCache$ = this._resolverCache.readFromCacheOrEvaluate(parentRecordID, field, this._variables, evaluate, getDataForResolverFragment),\n result = _this$_resolverCache$[0],\n seenRecord = _this$_resolverCache$[1],\n resolverError = _this$_resolverCache$[2],\n cachedSnapshot = _this$_resolverCache$[3],\n suspenseID = _this$_resolverCache$[4],\n updatedDataIDs = _this$_resolverCache$[5];\n this._propogateResolverMetadata(field.path, cachedSnapshot, resolverError, seenRecord, suspenseID, updatedDataIDs);\n return result;\n };\n _proto._propogateResolverMetadata = function _propogateResolverMetadata(fieldPath, cachedSnapshot, resolverError, seenRecord, suspenseID, updatedDataIDs) {\n if (cachedSnapshot != null) {\n if (cachedSnapshot.missingRequiredFields != null) {\n this._addMissingRequiredFields(cachedSnapshot.missingRequiredFields);\n }\n if (cachedSnapshot.missingClientEdges != null) {\n var _iterator2 = (0, _createForOfIteratorHelper2[\"default\"])(cachedSnapshot.missingClientEdges),\n _step2;\n try {\n for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n var missing = _step2.value;\n this._missingClientEdges.push(missing);\n }\n } catch (err) {\n _iterator2.e(err);\n } finally {\n _iterator2.f();\n }\n }\n if (cachedSnapshot.missingLiveResolverFields != null) {\n this._isMissingData = this._isMissingData || cachedSnapshot.missingLiveResolverFields.length > 0;\n var _iterator3 = (0, _createForOfIteratorHelper2[\"default\"])(cachedSnapshot.missingLiveResolverFields),\n _step3;\n try {\n for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {\n var missingResolverField = _step3.value;\n this._missingLiveResolverFields.push(missingResolverField);\n }\n } catch (err) {\n _iterator3.e(err);\n } finally {\n _iterator3.f();\n }\n }\n var _iterator4 = (0, _createForOfIteratorHelper2[\"default\"])(cachedSnapshot.relayResolverErrors),\n _step4;\n try {\n for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {\n var error = _step4.value;\n this._resolverErrors.push(error);\n }\n } catch (err) {\n _iterator4.e(err);\n } finally {\n _iterator4.f();\n }\n this._isMissingData = this._isMissingData || cachedSnapshot.isMissingData;\n }\n if (resolverError) {\n this._resolverErrors.push({\n field: {\n path: fieldPath,\n owner: this._fragmentName\n },\n error: resolverError\n });\n }\n if (seenRecord != null) {\n this._seenRecords.add(seenRecord);\n }\n if (suspenseID != null) {\n this._isMissingData = true;\n this._missingLiveResolverFields.push({\n path: \"\".concat(this._fragmentName, \".\").concat(fieldPath),\n liveStateID: suspenseID\n });\n }\n if (updatedDataIDs != null) {\n var _iterator5 = (0, _createForOfIteratorHelper2[\"default\"])(updatedDataIDs),\n _step5;\n try {\n for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {\n var recordID = _step5.value;\n this._updatedDataIDs.add(recordID);\n }\n } catch (err) {\n _iterator5.e(err);\n } finally {\n _iterator5.f();\n }\n }\n };\n _proto._readClientEdge = function _readClientEdge(field, record, data) {\n var _this2 = this;\n var _backingField$alias;\n var backingField = field.backingField;\n !(backingField.kind !== 'ClientExtension') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Client extension client edges are not yet implemented.') : invariant(false) : void 0;\n var applicationName = (_backingField$alias = backingField.alias) !== null && _backingField$alias !== void 0 ? _backingField$alias : backingField.name;\n var backingFieldData = {};\n this._traverseSelections([backingField], record, backingFieldData);\n var clientEdgeResolverResponse = backingFieldData[applicationName];\n if (clientEdgeResolverResponse == null || isSuspenseSentinel(clientEdgeResolverResponse)) {\n data[applicationName] = clientEdgeResolverResponse;\n return clientEdgeResolverResponse;\n }\n var validClientEdgeResolverResponse = assertValidClientEdgeResolverResponse(field, clientEdgeResolverResponse);\n switch (validClientEdgeResolverResponse.kind) {\n case 'PluralConcrete':\n var storeIDs = getStoreIDsForPluralClientEdgeResolver(field, validClientEdgeResolverResponse.ids, this._resolverCache);\n var validStoreIDs = storeIDs;\n if (field.modelResolver != null) {\n var modelResolver = field.modelResolver;\n validStoreIDs = storeIDs.map(function (storeID) {\n var model = _this2._readResolverFieldImpl(modelResolver, storeID);\n return model != null ? storeID : null;\n });\n }\n this._clientEdgeTraversalPath.push(null);\n var edgeValues = this._readLinkedIds(field.linkedField, validStoreIDs, record, data);\n this._clientEdgeTraversalPath.pop();\n data[applicationName] = edgeValues;\n return edgeValues;\n case 'SingularConcrete':\n var _getStoreIDAndTravers = getStoreIDAndTraversalPathSegmentForSingularClientEdgeResolver(field, validClientEdgeResolverResponse.id, this._resolverCache),\n storeID = _getStoreIDAndTravers[0],\n traversalPathSegment = _getStoreIDAndTravers[1];\n if (field.modelResolver != null) {\n var model = this._readResolverFieldImpl(field.modelResolver, storeID);\n if (model == null) {\n data[applicationName] = null;\n return null;\n }\n }\n this._clientEdgeTraversalPath.push(traversalPathSegment);\n var prevData = data[applicationName];\n !(prevData == null || typeof prevData === 'object') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayReader(): Expected data for field `%s` on record `%s` ' + 'to be an object, got `%s`.', applicationName, RelayModernRecord.getDataID(record), prevData) : invariant(false) : void 0;\n var edgeValue = this._traverse(field.linkedField, storeID, prevData);\n this._clientEdgeTraversalPath.pop();\n data[applicationName] = edgeValue;\n return edgeValue;\n default:\n validClientEdgeResolverResponse.kind;\n }\n };\n _proto._readScalar = function _readScalar(field, record, data) {\n var _field$alias2;\n var applicationName = (_field$alias2 = field.alias) !== null && _field$alias2 !== void 0 ? _field$alias2 : field.name;\n var storageKey = getStorageKey(field, this._variables);\n var value = RelayModernRecord.getValue(record, storageKey);\n if (value === null) {\n this._maybeAddErrorResponseFields(record, storageKey);\n } else if (value === undefined) {\n this._markDataAsMissing();\n }\n data[applicationName] = value;\n return value;\n };\n _proto._readLink = function _readLink(field, record, data) {\n var _field$alias3;\n var applicationName = (_field$alias3 = field.alias) !== null && _field$alias3 !== void 0 ? _field$alias3 : field.name;\n var storageKey = getStorageKey(field, this._variables);\n var linkedID = RelayModernRecord.getLinkedRecordID(record, storageKey);\n if (linkedID == null) {\n data[applicationName] = linkedID;\n if (linkedID === null) {\n this._maybeAddErrorResponseFields(record, storageKey);\n } else if (linkedID === undefined) {\n this._markDataAsMissing();\n }\n return linkedID;\n }\n var prevData = data[applicationName];\n !(prevData == null || typeof prevData === 'object') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayReader(): Expected data for field `%s` on record `%s` ' + 'to be an object, got `%s`.', applicationName, RelayModernRecord.getDataID(record), prevData) : invariant(false) : void 0;\n var value = this._traverse(field, linkedID, prevData);\n data[applicationName] = value;\n return value;\n };\n _proto._readActorChange = function _readActorChange(field, record, data) {\n var _field$alias4;\n var applicationName = (_field$alias4 = field.alias) !== null && _field$alias4 !== void 0 ? _field$alias4 : field.name;\n var storageKey = getStorageKey(field, this._variables);\n var externalRef = RelayModernRecord.getActorLinkedRecordID(record, storageKey);\n if (externalRef == null) {\n data[applicationName] = externalRef;\n if (externalRef === undefined) {\n this._markDataAsMissing();\n } else if (externalRef === null) {\n this._maybeAddErrorResponseFields(record, storageKey);\n }\n return data[applicationName];\n }\n var actorIdentifier = externalRef[0],\n dataID = externalRef[1];\n var fragmentRef = {};\n this._createFragmentPointer(field.fragmentSpread, RelayModernRecord.fromObject({\n __id: dataID\n }), fragmentRef);\n data[applicationName] = {\n __fragmentRef: fragmentRef,\n __viewer: actorIdentifier\n };\n return data[applicationName];\n };\n _proto._readPluralLink = function _readPluralLink(field, record, data) {\n var storageKey = getStorageKey(field, this._variables);\n var linkedIDs = RelayModernRecord.getLinkedRecordIDs(record, storageKey);\n if (linkedIDs === null) {\n this._maybeAddErrorResponseFields(record, storageKey);\n }\n return this._readLinkedIds(field, linkedIDs, record, data);\n };\n _proto._readLinkedIds = function _readLinkedIds(field, linkedIDs, record, data) {\n var _this3 = this;\n var _field$alias5;\n var applicationName = (_field$alias5 = field.alias) !== null && _field$alias5 !== void 0 ? _field$alias5 : field.name;\n if (linkedIDs == null) {\n data[applicationName] = linkedIDs;\n if (linkedIDs === undefined) {\n this._markDataAsMissing();\n }\n return linkedIDs;\n }\n var prevData = data[applicationName];\n !(prevData == null || Array.isArray(prevData)) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayReader(): Expected data for field `%s` on record `%s` ' + 'to be an array, got `%s`.', applicationName, RelayModernRecord.getDataID(record), prevData) : invariant(false) : void 0;\n var linkedArray = prevData || [];\n linkedIDs.forEach(function (linkedID, nextIndex) {\n if (linkedID == null) {\n if (linkedID === undefined) {\n _this3._markDataAsMissing();\n }\n linkedArray[nextIndex] = linkedID;\n return;\n }\n var prevItem = linkedArray[nextIndex];\n !(prevItem == null || typeof prevItem === 'object') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayReader(): Expected data for field `%s` on record `%s` ' + 'to be an object, got `%s`.', applicationName, RelayModernRecord.getDataID(record), prevItem) : invariant(false) : void 0;\n linkedArray[nextIndex] = _this3._traverse(field, linkedID, prevItem);\n });\n data[applicationName] = linkedArray;\n return linkedArray;\n };\n _proto._readModuleImport = function _readModuleImport(moduleImport, record, data) {\n var componentKey = getModuleComponentKey(moduleImport.documentName);\n var component = RelayModernRecord.getValue(record, componentKey);\n if (component == null) {\n if (component === undefined) {\n this._markDataAsMissing();\n }\n return;\n }\n this._createFragmentPointer({\n kind: 'FragmentSpread',\n name: moduleImport.fragmentName,\n args: moduleImport.args\n }, record, data);\n data[FRAGMENT_PROP_NAME_KEY] = moduleImport.fragmentPropName;\n data[MODULE_COMPONENT_KEY] = component;\n };\n _proto._createAliasedFragmentSpread = function _createAliasedFragmentSpread(namedFragmentSpread, record) {\n var abstractKey = namedFragmentSpread.abstractKey;\n if (abstractKey == null) {\n var typeName = RelayModernRecord.getType(record);\n if (typeName == null || typeName !== namedFragmentSpread.type) {\n return null;\n }\n } else {\n var implementsInterface = this._implementsInterface(record, abstractKey);\n if (implementsInterface === false) {\n return null;\n } else if (implementsInterface == null) {\n this._markDataAsMissing();\n return undefined;\n }\n }\n var fieldData = {};\n this._createFragmentPointer(namedFragmentSpread.fragment, record, fieldData);\n return RelayModernRecord.fromObject(fieldData);\n };\n _proto._readInlineFragment = function _readInlineFragment(inlineFragment, record, data) {\n var abstractKey = inlineFragment.abstractKey;\n if (abstractKey == null) {\n var typeName = RelayModernRecord.getType(record);\n if (typeName == null || typeName !== inlineFragment.type) {\n return null;\n } else {\n var hasExpectedData = this._traverseSelections(inlineFragment.selections, record, data);\n if (!hasExpectedData) {\n return false;\n }\n }\n } else {\n var implementsInterface = this._implementsInterface(record, abstractKey);\n var parentIsMissingData = this._isMissingData;\n var parentIsWithinUnmatchedTypeRefinement = this._isWithinUnmatchedTypeRefinement;\n this._isWithinUnmatchedTypeRefinement = parentIsWithinUnmatchedTypeRefinement || implementsInterface === false;\n this._traverseSelections(inlineFragment.selections, record, data);\n this._isWithinUnmatchedTypeRefinement = parentIsWithinUnmatchedTypeRefinement;\n if (implementsInterface === false) {\n this._isMissingData = parentIsMissingData;\n return undefined;\n } else if (implementsInterface == null) {\n this._markDataAsMissing();\n return null;\n }\n }\n return data;\n };\n _proto._createFragmentPointer = function _createFragmentPointer(fragmentSpread, record, data) {\n var fragmentPointers = data[FRAGMENTS_KEY];\n if (fragmentPointers == null) {\n fragmentPointers = data[FRAGMENTS_KEY] = {};\n }\n !(typeof fragmentPointers === 'object' && fragmentPointers != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayReader: Expected fragment spread data to be an object, got `%s`.', fragmentPointers) : invariant(false) : void 0;\n if (data[ID_KEY] == null) {\n data[ID_KEY] = RelayModernRecord.getDataID(record);\n }\n fragmentPointers[fragmentSpread.name] = getArgumentValues(fragmentSpread.args, this._variables, this._isWithinUnmatchedTypeRefinement);\n data[FRAGMENT_OWNER_KEY] = this._owner;\n if (RelayFeatureFlags.ENABLE_CLIENT_EDGES) {\n if (this._clientEdgeTraversalPath.length > 0 && this._clientEdgeTraversalPath[this._clientEdgeTraversalPath.length - 1] !== null) {\n data[CLIENT_EDGE_TRAVERSAL_PATH] = (0, _toConsumableArray2[\"default\"])(this._clientEdgeTraversalPath);\n }\n }\n };\n _proto._createInlineDataOrResolverFragmentPointer = function _createInlineDataOrResolverFragmentPointer(fragmentSpreadOrFragment, record, data) {\n var fragmentPointers = data[FRAGMENTS_KEY];\n if (fragmentPointers == null) {\n fragmentPointers = data[FRAGMENTS_KEY] = {};\n }\n !(typeof fragmentPointers === 'object' && fragmentPointers != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayReader: Expected fragment spread data to be an object, got `%s`.', fragmentPointers) : invariant(false) : void 0;\n if (data[ID_KEY] == null) {\n data[ID_KEY] = RelayModernRecord.getDataID(record);\n }\n var inlineData = {};\n var parentFragmentName = this._fragmentName;\n this._fragmentName = fragmentSpreadOrFragment.name;\n var parentVariables = this._variables;\n var argumentVariables = fragmentSpreadOrFragment.args ? getArgumentValues(fragmentSpreadOrFragment.args, this._variables) : {};\n this._variables = RelayConcreteVariables.getFragmentVariables(fragmentSpreadOrFragment, this._owner.variables, argumentVariables);\n this._traverseSelections(fragmentSpreadOrFragment.selections, record, inlineData);\n this._variables = parentVariables;\n this._fragmentName = parentFragmentName;\n fragmentPointers[fragmentSpreadOrFragment.name] = inlineData;\n };\n _proto._addMissingRequiredFields = function _addMissingRequiredFields(additional) {\n if (this._missingRequiredFields == null) {\n this._missingRequiredFields = additional;\n return;\n }\n if (this._missingRequiredFields.action === 'THROW') {\n return;\n }\n if (additional.action === 'THROW') {\n this._missingRequiredFields = additional;\n return;\n }\n this._missingRequiredFields = {\n action: 'LOG',\n fields: [].concat((0, _toConsumableArray2[\"default\"])(this._missingRequiredFields.fields), (0, _toConsumableArray2[\"default\"])(additional.fields))\n };\n };\n _proto._implementsInterface = function _implementsInterface(record, abstractKey) {\n var typeName = RelayModernRecord.getType(record);\n var typeRecord = this._recordSource.get(generateTypeID(typeName));\n var implementsInterface = typeRecord != null ? RelayModernRecord.getValue(typeRecord, abstractKey) : null;\n return implementsInterface;\n };\n return RelayReader;\n}();\nfunction getResolverValue(field, variables, fragmentKey) {\n var resolverFunction = typeof field.resolverModule === 'function' ? field.resolverModule : field.resolverModule[\"default\"];\n var resolverResult = null;\n var resolverError = null;\n try {\n var resolverFunctionArgs = [];\n if (field.fragment != null) {\n resolverFunctionArgs.push(fragmentKey);\n }\n var args = field.args ? getArgumentValues(field.args, variables) : undefined;\n resolverFunctionArgs.push(args);\n resolverResult = resolverFunction.apply(null, resolverFunctionArgs);\n } catch (e) {\n if (e === RESOLVER_FRAGMENT_MISSING_DATA_SENTINEL) {\n resolverResult = undefined;\n } else {\n resolverError = e;\n }\n }\n return [resolverResult, resolverError];\n}\nfunction assertValidClientEdgeResolverResponse(field, clientEdgeResolverResponse) {\n if (field.linkedField.plural) {\n !Array.isArray(clientEdgeResolverResponse) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Expected plural Client Edge Relay Resolver to return an array containing IDs or objects with shape {id}.') : invariant(false) : void 0;\n return {\n kind: 'PluralConcrete',\n ids: clientEdgeResolverResponse.map(function (response) {\n return extractIdFromResponse(response, 'Expected this plural Client Edge Relay Resolver to return an array containing IDs or objects with shape {id}.');\n })\n };\n } else {\n return {\n kind: 'SingularConcrete',\n id: extractIdFromResponse(clientEdgeResolverResponse, 'Expected this Client Edge Relay Resolver to return an ID of type `string` or an object with shape {id}.')\n };\n }\n}\nfunction getStoreIDAndTraversalPathSegmentForSingularClientEdgeResolver(field, clientEdgeResolverResponse, resolverCache) {\n if (field.kind === CLIENT_EDGE_TO_CLIENT_OBJECT) {\n if (field.backingField.normalizationInfo == null) {\n var concreteType = field.concreteType;\n !(concreteType != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Expected at least one of backingField.normalizationInfo or field.concreteType to be non-null. ' + 'This indicates a bug in Relay.') : invariant(false) : void 0;\n return [resolverCache.ensureClientRecord(clientEdgeResolverResponse, concreteType), null];\n } else {\n return [clientEdgeResolverResponse, null];\n }\n } else {\n return [clientEdgeResolverResponse, {\n readerClientEdge: field,\n clientEdgeDestinationID: clientEdgeResolverResponse\n }];\n }\n}\nfunction getStoreIDsForPluralClientEdgeResolver(field, clientEdgeResolverResponse, resolverCache) {\n if (field.kind === CLIENT_EDGE_TO_CLIENT_OBJECT) {\n if (field.backingField.normalizationInfo == null) {\n var concreteType = field.concreteType;\n !(concreteType != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Expected at least one of backingField.normalizationInfo or field.concreteType to be non-null. ' + 'This indicates a bug in Relay.') : invariant(false) : void 0;\n return clientEdgeResolverResponse.map(function (id) {\n return resolverCache.ensureClientRecord(id, concreteType);\n });\n } else {\n return clientEdgeResolverResponse;\n }\n } else {\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Unexpected Client Edge to plural server type. This should be prevented by the compiler.') : invariant(false) : void 0;\n }\n}\nfunction extractIdFromResponse(individualResponse, errorMessage) {\n if (typeof individualResponse === 'string') {\n return individualResponse;\n } else if (typeof individualResponse === 'object' && individualResponse != null && typeof individualResponse.id === 'string') {\n return individualResponse.id;\n }\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, errorMessage) : invariant(false) : void 0;\n}\nmodule.exports = {\n read: read\n};","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _createForOfIteratorHelper2 = _interopRequireDefault(require(\"@babel/runtime/helpers/createForOfIteratorHelper\"));\nvar RelayModernRecord = require('./RelayModernRecord');\nvar RelayRecordState = require('./RelayRecordState');\nvar EXISTENT = RelayRecordState.EXISTENT,\n NONEXISTENT = RelayRecordState.NONEXISTENT,\n UNKNOWN = RelayRecordState.UNKNOWN;\nvar RelayRecordSource = /*#__PURE__*/function () {\n function RelayRecordSource(records) {\n var _this = this;\n this._records = new Map();\n if (records != null) {\n Object.keys(records).forEach(function (key) {\n var object = records[key];\n var record = RelayModernRecord.fromObject(object);\n _this._records.set(key, record);\n });\n }\n }\n RelayRecordSource.create = function create(records) {\n return new RelayRecordSource(records);\n };\n var _proto = RelayRecordSource.prototype;\n _proto.clear = function clear() {\n this._records = new Map();\n };\n _proto[\"delete\"] = function _delete(dataID) {\n this._records.set(dataID, null);\n };\n _proto.get = function get(dataID) {\n return this._records.get(dataID);\n };\n _proto.getRecordIDs = function getRecordIDs() {\n return Array.from(this._records.keys());\n };\n _proto.getStatus = function getStatus(dataID) {\n if (!this._records.has(dataID)) {\n return UNKNOWN;\n }\n return this._records.get(dataID) == null ? NONEXISTENT : EXISTENT;\n };\n _proto.has = function has(dataID) {\n return this._records.has(dataID);\n };\n _proto.remove = function remove(dataID) {\n this._records[\"delete\"](dataID);\n };\n _proto.set = function set(dataID, record) {\n this._records.set(dataID, record);\n };\n _proto.size = function size() {\n return this._records.size;\n };\n _proto.toJSON = function toJSON() {\n var obj = {};\n var _iterator = (0, _createForOfIteratorHelper2[\"default\"])(this._records),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var _step$value = _step.value,\n key = _step$value[0],\n record = _step$value[1];\n obj[key] = RelayModernRecord.toJSON(record);\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n return obj;\n };\n return RelayRecordSource;\n}();\nmodule.exports = RelayRecordSource;","'use strict';\n\nvar RelayRecordState = {\n EXISTENT: 'EXISTENT',\n NONEXISTENT: 'NONEXISTENT',\n UNKNOWN: 'UNKNOWN'\n};\nmodule.exports = RelayRecordState;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _createForOfIteratorHelper2 = _interopRequireDefault(require(\"@babel/runtime/helpers/createForOfIteratorHelper\"));\nvar getOperation = require('../util/getOperation');\nvar RelayConcreteNode = require('../util/RelayConcreteNode');\nvar cloneRelayHandleSourceField = require('./cloneRelayHandleSourceField');\nvar getOutputTypeRecordIDs = require('./experimental-live-resolvers/getOutputTypeRecordIDs');\nvar _require = require('./RelayConcreteVariables'),\n getLocalVariables = _require.getLocalVariables;\nvar RelayModernRecord = require('./RelayModernRecord');\nvar RelayStoreUtils = require('./RelayStoreUtils');\nvar _require2 = require('./TypeID'),\n generateTypeID = _require2.generateTypeID;\nvar invariant = require('invariant');\nvar ACTOR_CHANGE = RelayConcreteNode.ACTOR_CHANGE,\n CONDITION = RelayConcreteNode.CONDITION,\n CLIENT_COMPONENT = RelayConcreteNode.CLIENT_COMPONENT,\n CLIENT_EXTENSION = RelayConcreteNode.CLIENT_EXTENSION,\n DEFER = RelayConcreteNode.DEFER,\n FRAGMENT_SPREAD = RelayConcreteNode.FRAGMENT_SPREAD,\n INLINE_FRAGMENT = RelayConcreteNode.INLINE_FRAGMENT,\n LINKED_FIELD = RelayConcreteNode.LINKED_FIELD,\n MODULE_IMPORT = RelayConcreteNode.MODULE_IMPORT,\n LINKED_HANDLE = RelayConcreteNode.LINKED_HANDLE,\n SCALAR_FIELD = RelayConcreteNode.SCALAR_FIELD,\n SCALAR_HANDLE = RelayConcreteNode.SCALAR_HANDLE,\n STREAM = RelayConcreteNode.STREAM,\n TYPE_DISCRIMINATOR = RelayConcreteNode.TYPE_DISCRIMINATOR,\n RELAY_RESOLVER = RelayConcreteNode.RELAY_RESOLVER,\n RELAY_LIVE_RESOLVER = RelayConcreteNode.RELAY_LIVE_RESOLVER,\n CLIENT_EDGE_TO_CLIENT_OBJECT = RelayConcreteNode.CLIENT_EDGE_TO_CLIENT_OBJECT;\nvar getStorageKey = RelayStoreUtils.getStorageKey,\n getModuleOperationKey = RelayStoreUtils.getModuleOperationKey;\nfunction mark(recordSource, selector, references, operationLoader, shouldProcessClientComponents) {\n var dataID = selector.dataID,\n node = selector.node,\n variables = selector.variables;\n var marker = new RelayReferenceMarker(recordSource, variables, references, operationLoader, shouldProcessClientComponents);\n marker.mark(node, dataID);\n}\nvar RelayReferenceMarker = /*#__PURE__*/function () {\n function RelayReferenceMarker(recordSource, variables, references, operationLoader, shouldProcessClientComponents) {\n this._operationLoader = operationLoader !== null && operationLoader !== void 0 ? operationLoader : null;\n this._operationName = null;\n this._recordSource = recordSource;\n this._references = references;\n this._variables = variables;\n this._shouldProcessClientComponents = shouldProcessClientComponents;\n }\n var _proto = RelayReferenceMarker.prototype;\n _proto.mark = function mark(node, dataID) {\n if (node.kind === 'Operation' || node.kind === 'SplitOperation') {\n this._operationName = node.name;\n }\n this._traverse(node, dataID);\n };\n _proto._traverse = function _traverse(node, dataID) {\n this._references.add(dataID);\n var record = this._recordSource.get(dataID);\n if (record == null) {\n return;\n }\n this._traverseSelections(node.selections, record);\n };\n _proto._getVariableValue = function _getVariableValue(name) {\n !this._variables.hasOwnProperty(name) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayReferenceMarker(): Undefined variable `%s`.', name) : invariant(false) : void 0;\n return this._variables[name];\n };\n _proto._traverseSelections = function _traverseSelections(selections, record) {\n var _this = this;\n selections.forEach(function (selection) {\n switch (selection.kind) {\n case ACTOR_CHANGE:\n _this._traverseLink(selection.linkedField, record);\n break;\n case LINKED_FIELD:\n if (selection.plural) {\n _this._traversePluralLink(selection, record);\n } else {\n _this._traverseLink(selection, record);\n }\n break;\n case CONDITION:\n var conditionValue = Boolean(_this._getVariableValue(selection.condition));\n if (conditionValue === selection.passingValue) {\n _this._traverseSelections(selection.selections, record);\n }\n break;\n case INLINE_FRAGMENT:\n if (selection.abstractKey == null) {\n var typeName = RelayModernRecord.getType(record);\n if (typeName != null && typeName === selection.type || typeName === RelayStoreUtils.ROOT_TYPE) {\n _this._traverseSelections(selection.selections, record);\n }\n } else {\n var _typeName = RelayModernRecord.getType(record);\n var typeID = generateTypeID(_typeName);\n _this._references.add(typeID);\n _this._traverseSelections(selection.selections, record);\n }\n break;\n case FRAGMENT_SPREAD:\n var prevVariables = _this._variables;\n _this._variables = getLocalVariables(_this._variables, selection.fragment.argumentDefinitions, selection.args);\n _this._traverseSelections(selection.fragment.selections, record);\n _this._variables = prevVariables;\n break;\n case LINKED_HANDLE:\n var handleField = cloneRelayHandleSourceField(selection, selections, _this._variables);\n if (handleField.plural) {\n _this._traversePluralLink(handleField, record);\n } else {\n _this._traverseLink(handleField, record);\n }\n break;\n case DEFER:\n case STREAM:\n _this._traverseSelections(selection.selections, record);\n break;\n case SCALAR_FIELD:\n case SCALAR_HANDLE:\n break;\n case TYPE_DISCRIMINATOR:\n {\n var _typeName2 = RelayModernRecord.getType(record);\n var _typeID = generateTypeID(_typeName2);\n _this._references.add(_typeID);\n break;\n }\n case MODULE_IMPORT:\n _this._traverseModuleImport(selection, record);\n break;\n case CLIENT_EXTENSION:\n _this._traverseSelections(selection.selections, record);\n break;\n case CLIENT_COMPONENT:\n if (_this._shouldProcessClientComponents === false) {\n break;\n }\n _this._traverseSelections(selection.fragment.selections, record);\n break;\n case RELAY_RESOLVER:\n _this._traverseResolverField(selection, record);\n break;\n case RELAY_LIVE_RESOLVER:\n _this._traverseResolverField(selection, record);\n break;\n case CLIENT_EDGE_TO_CLIENT_OBJECT:\n _this._traverseClientEdgeToClientObject(selection, record);\n break;\n default:\n selection;\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayReferenceMarker: Unknown AST node `%s`.', selection) : invariant(false) : void 0;\n }\n });\n };\n _proto._traverseClientEdgeToClientObject = function _traverseClientEdgeToClientObject(field, record) {\n var dataID = this._traverseResolverField(field.backingField, record);\n if (dataID == null) {\n return;\n }\n var resolverRecord = this._recordSource.get(dataID);\n if (resolverRecord == null) {\n return;\n }\n if (field.backingField.isOutputType) {\n var outputTypeRecordIDs = getOutputTypeRecordIDs(resolverRecord);\n if (outputTypeRecordIDs != null) {\n var _iterator = (0, _createForOfIteratorHelper2[\"default\"])(outputTypeRecordIDs),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var _dataID = _step.value;\n this._references.add(_dataID);\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n }\n } else {\n var linkedField = field.linkedField;\n var concreteType = linkedField.concreteType;\n if (concreteType == null) {\n return;\n }\n if (linkedField.plural) {\n var dataIDs = RelayModernRecord.getResolverLinkedRecordIDs(resolverRecord, concreteType);\n if (dataIDs != null) {\n var _iterator2 = (0, _createForOfIteratorHelper2[\"default\"])(dataIDs),\n _step2;\n try {\n for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n var _dataID2 = _step2.value;\n if (_dataID2 != null) {\n this._traverse(linkedField, _dataID2);\n }\n }\n } catch (err) {\n _iterator2.e(err);\n } finally {\n _iterator2.f();\n }\n }\n } else {\n var _dataID3 = RelayModernRecord.getResolverLinkedRecordID(resolverRecord, concreteType);\n if (_dataID3 != null) {\n this._traverse(linkedField, _dataID3);\n }\n }\n }\n };\n _proto._traverseResolverField = function _traverseResolverField(field, record) {\n var storageKey = getStorageKey(field, this._variables);\n var dataID = RelayModernRecord.getLinkedRecordID(record, storageKey);\n if (dataID != null) {\n this._references.add(dataID);\n }\n var fragment = field.fragment;\n if (fragment != null) {\n this._traverseSelections([fragment], record);\n }\n return dataID;\n };\n _proto._traverseModuleImport = function _traverseModuleImport(moduleImport, record) {\n var _this$_operationName;\n var operationLoader = this._operationLoader;\n !(operationLoader !== null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayReferenceMarker: Expected an operationLoader to be configured when using `@module`. ' + 'Could not load fragment `%s` in operation `%s`.', moduleImport.fragmentName, (_this$_operationName = this._operationName) !== null && _this$_operationName !== void 0 ? _this$_operationName : '(unknown)') : invariant(false) : void 0;\n var operationKey = getModuleOperationKey(moduleImport.documentName);\n var operationReference = RelayModernRecord.getValue(record, operationKey);\n if (operationReference == null) {\n return;\n }\n var normalizationRootNode = operationLoader.get(operationReference);\n if (normalizationRootNode != null) {\n var operation = getOperation(normalizationRootNode);\n var prevVariables = this._variables;\n this._variables = getLocalVariables(this._variables, operation.argumentDefinitions, moduleImport.args);\n this._traverseSelections(operation.selections, record);\n this._variables = prevVariables;\n }\n };\n _proto._traverseLink = function _traverseLink(field, record) {\n var storageKey = getStorageKey(field, this._variables);\n var linkedID = RelayModernRecord.getLinkedRecordID(record, storageKey);\n if (linkedID == null) {\n return;\n }\n this._traverse(field, linkedID);\n };\n _proto._traversePluralLink = function _traversePluralLink(field, record) {\n var _this2 = this;\n var storageKey = getStorageKey(field, this._variables);\n var linkedIDs = RelayModernRecord.getLinkedRecordIDs(record, storageKey);\n if (linkedIDs == null) {\n return;\n }\n linkedIDs.forEach(function (linkedID) {\n if (linkedID != null) {\n _this2._traverse(field, linkedID);\n }\n });\n };\n return RelayReferenceMarker;\n}();\nmodule.exports = {\n mark: mark\n};","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _createForOfIteratorHelper2 = _interopRequireDefault(require(\"@babel/runtime/helpers/createForOfIteratorHelper\"));\nvar _toConsumableArray2 = _interopRequireDefault(require(\"@babel/runtime/helpers/toConsumableArray\"));\nvar _require = require('../multi-actor-environment/ActorUtils'),\n ACTOR_IDENTIFIER_FIELD_NAME = _require.ACTOR_IDENTIFIER_FIELD_NAME,\n getActorIdentifierFromPayload = _require.getActorIdentifierFromPayload;\nvar _require2 = require('../util/RelayConcreteNode'),\n ACTOR_CHANGE = _require2.ACTOR_CHANGE,\n CLIENT_COMPONENT = _require2.CLIENT_COMPONENT,\n CLIENT_EDGE_TO_CLIENT_OBJECT = _require2.CLIENT_EDGE_TO_CLIENT_OBJECT,\n CLIENT_EXTENSION = _require2.CLIENT_EXTENSION,\n CONDITION = _require2.CONDITION,\n DEFER = _require2.DEFER,\n FRAGMENT_SPREAD = _require2.FRAGMENT_SPREAD,\n INLINE_FRAGMENT = _require2.INLINE_FRAGMENT,\n LINKED_FIELD = _require2.LINKED_FIELD,\n LINKED_HANDLE = _require2.LINKED_HANDLE,\n MODULE_IMPORT = _require2.MODULE_IMPORT,\n RELAY_LIVE_RESOLVER = _require2.RELAY_LIVE_RESOLVER,\n RELAY_RESOLVER = _require2.RELAY_RESOLVER,\n SCALAR_FIELD = _require2.SCALAR_FIELD,\n SCALAR_HANDLE = _require2.SCALAR_HANDLE,\n STREAM = _require2.STREAM,\n TYPE_DISCRIMINATOR = _require2.TYPE_DISCRIMINATOR;\nvar _require3 = require('./ClientID'),\n generateClientID = _require3.generateClientID,\n isClientID = _require3.isClientID;\nvar _require4 = require('./RelayConcreteVariables'),\n getLocalVariables = _require4.getLocalVariables;\nvar _require5 = require('./RelayErrorTrie'),\n buildErrorTrie = _require5.buildErrorTrie,\n getErrorsByKey = _require5.getErrorsByKey,\n getNestedErrorTrieByKey = _require5.getNestedErrorTrieByKey;\nvar RelayModernRecord = require('./RelayModernRecord');\nvar _require6 = require('./RelayModernSelector'),\n createNormalizationSelector = _require6.createNormalizationSelector;\nvar _require7 = require('./RelayStoreUtils'),\n ROOT_ID = _require7.ROOT_ID,\n TYPENAME_KEY = _require7.TYPENAME_KEY,\n getArgumentValues = _require7.getArgumentValues,\n getHandleStorageKey = _require7.getHandleStorageKey,\n getModuleComponentKey = _require7.getModuleComponentKey,\n getModuleOperationKey = _require7.getModuleOperationKey,\n getStorageKey = _require7.getStorageKey;\nvar _require8 = require('./TypeID'),\n TYPE_SCHEMA_TYPE = _require8.TYPE_SCHEMA_TYPE,\n generateTypeID = _require8.generateTypeID;\nvar areEqual = require(\"fbjs/lib/areEqual\");\nvar invariant = require('invariant');\nvar warning = require(\"fbjs/lib/warning\");\nfunction normalize(recordSource, selector, response, options, errors) {\n var dataID = selector.dataID,\n node = selector.node,\n variables = selector.variables;\n var normalizer = new RelayResponseNormalizer(recordSource, variables, options);\n return normalizer.normalizeResponse(node, dataID, response, errors);\n}\nvar RelayResponseNormalizer = /*#__PURE__*/function () {\n function RelayResponseNormalizer(recordSource, variables, options) {\n this._actorIdentifier = options.actorIdentifier;\n this._getDataId = options.getDataID;\n this._handleFieldPayloads = [];\n this._treatMissingFieldsAsNull = options.treatMissingFieldsAsNull;\n this._incrementalPlaceholders = [];\n this._isClientExtension = false;\n this._isUnmatchedAbstractType = false;\n this._followupPayloads = [];\n this._path = options.path ? (0, _toConsumableArray2[\"default\"])(options.path) : [];\n this._recordSource = recordSource;\n this._variables = variables;\n this._shouldProcessClientComponents = options.shouldProcessClientComponents;\n }\n var _proto = RelayResponseNormalizer.prototype;\n _proto.normalizeResponse = function normalizeResponse(node, dataID, data, errors) {\n var record = this._recordSource.get(dataID);\n !record ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayResponseNormalizer(): Expected root record `%s` to exist.', dataID) : invariant(false) : void 0;\n this._assignClientAbstractTypes(node);\n this._errorTrie = buildErrorTrie(errors);\n this._traverseSelections(node, record, data);\n return {\n errors: errors,\n fieldPayloads: this._handleFieldPayloads,\n incrementalPlaceholders: this._incrementalPlaceholders,\n followupPayloads: this._followupPayloads,\n source: this._recordSource,\n isFinal: false\n };\n };\n _proto._assignClientAbstractTypes = function _assignClientAbstractTypes(node) {\n var clientAbstractTypes = node.clientAbstractTypes;\n if (clientAbstractTypes != null) {\n for (var _i = 0, _Object$keys = Object.keys(clientAbstractTypes); _i < _Object$keys.length; _i++) {\n var abstractType = _Object$keys[_i];\n var _iterator = (0, _createForOfIteratorHelper2[\"default\"])(clientAbstractTypes[abstractType]),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var concreteType = _step.value;\n var typeID = generateTypeID(concreteType);\n var typeRecord = this._recordSource.get(typeID);\n if (typeRecord == null) {\n typeRecord = RelayModernRecord.create(typeID, TYPE_SCHEMA_TYPE);\n this._recordSource.set(typeID, typeRecord);\n }\n RelayModernRecord.setValue(typeRecord, abstractType, true);\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n }\n }\n };\n _proto._getVariableValue = function _getVariableValue(name) {\n !this._variables.hasOwnProperty(name) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayResponseNormalizer(): Undefined variable `%s`.', name) : invariant(false) : void 0;\n return this._variables[name];\n };\n _proto._getRecordType = function _getRecordType(data) {\n var typeName = data[TYPENAME_KEY];\n !(typeName != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayResponseNormalizer(): Expected a typename for record `%s`.', JSON.stringify(data, null, 2)) : invariant(false) : void 0;\n return typeName;\n };\n _proto._traverseSelections = function _traverseSelections(node, record, data) {\n for (var i = 0; i < node.selections.length; i++) {\n var selection = node.selections[i];\n switch (selection.kind) {\n case SCALAR_FIELD:\n case LINKED_FIELD:\n this._normalizeField(selection, record, data);\n break;\n case CONDITION:\n var conditionValue = Boolean(this._getVariableValue(selection.condition));\n if (conditionValue === selection.passingValue) {\n this._traverseSelections(selection, record, data);\n }\n break;\n case FRAGMENT_SPREAD:\n {\n var prevVariables = this._variables;\n this._variables = getLocalVariables(this._variables, selection.fragment.argumentDefinitions, selection.args);\n this._traverseSelections(selection.fragment, record, data);\n this._variables = prevVariables;\n break;\n }\n case INLINE_FRAGMENT:\n {\n var abstractKey = selection.abstractKey;\n if (abstractKey == null) {\n var typeName = RelayModernRecord.getType(record);\n if (typeName === selection.type) {\n this._traverseSelections(selection, record, data);\n }\n } else {\n var implementsInterface = data.hasOwnProperty(abstractKey);\n var _typeName = RelayModernRecord.getType(record);\n var typeID = generateTypeID(_typeName);\n var typeRecord = this._recordSource.get(typeID);\n if (typeRecord == null) {\n typeRecord = RelayModernRecord.create(typeID, TYPE_SCHEMA_TYPE);\n this._recordSource.set(typeID, typeRecord);\n }\n RelayModernRecord.setValue(typeRecord, abstractKey, implementsInterface);\n if (implementsInterface) {\n this._traverseSelections(selection, record, data);\n }\n }\n break;\n }\n case TYPE_DISCRIMINATOR:\n {\n var _abstractKey = selection.abstractKey;\n var _implementsInterface = data.hasOwnProperty(_abstractKey);\n var _typeName2 = RelayModernRecord.getType(record);\n var _typeID = generateTypeID(_typeName2);\n var _typeRecord = this._recordSource.get(_typeID);\n if (_typeRecord == null) {\n _typeRecord = RelayModernRecord.create(_typeID, TYPE_SCHEMA_TYPE);\n this._recordSource.set(_typeID, _typeRecord);\n }\n RelayModernRecord.setValue(_typeRecord, _abstractKey, _implementsInterface);\n break;\n }\n case LINKED_HANDLE:\n case SCALAR_HANDLE:\n var args = selection.args ? getArgumentValues(selection.args, this._variables) : {};\n var fieldKey = getStorageKey(selection, this._variables);\n var handleKey = getHandleStorageKey(selection, this._variables);\n this._handleFieldPayloads.push({\n args: args,\n dataID: RelayModernRecord.getDataID(record),\n fieldKey: fieldKey,\n handle: selection.handle,\n handleKey: handleKey,\n handleArgs: selection.handleArgs ? getArgumentValues(selection.handleArgs, this._variables) : {}\n });\n break;\n case MODULE_IMPORT:\n this._normalizeModuleImport(selection, record, data);\n break;\n case DEFER:\n this._normalizeDefer(selection, record, data);\n break;\n case STREAM:\n this._normalizeStream(selection, record, data);\n break;\n case CLIENT_EXTENSION:\n var isClientExtension = this._isClientExtension;\n this._isClientExtension = true;\n this._traverseSelections(selection, record, data);\n this._isClientExtension = isClientExtension;\n break;\n case CLIENT_COMPONENT:\n if (this._shouldProcessClientComponents === false) {\n break;\n }\n this._traverseSelections(selection.fragment, record, data);\n break;\n case ACTOR_CHANGE:\n this._normalizeActorChange(selection, record, data);\n break;\n case RELAY_RESOLVER:\n this._normalizeResolver(selection, record, data);\n break;\n case RELAY_LIVE_RESOLVER:\n this._normalizeResolver(selection, record, data);\n break;\n case CLIENT_EDGE_TO_CLIENT_OBJECT:\n this._normalizeResolver(selection.backingField, record, data);\n break;\n default:\n selection;\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayResponseNormalizer(): Unexpected ast kind `%s`.', selection.kind) : invariant(false) : void 0;\n }\n }\n };\n _proto._normalizeResolver = function _normalizeResolver(resolver, record, data) {\n if (resolver.fragment != null) {\n this._traverseSelections(resolver.fragment, record, data);\n }\n };\n _proto._normalizeDefer = function _normalizeDefer(defer, record, data) {\n var isDeferred = defer[\"if\"] === null || this._getVariableValue(defer[\"if\"]);\n if (process.env.NODE_ENV !== \"production\") {\n process.env.NODE_ENV !== \"production\" ? warning(typeof isDeferred === 'boolean', 'RelayResponseNormalizer: Expected value for @defer `if` argument to ' + 'be a boolean, got `%s`.', isDeferred) : void 0;\n }\n if (isDeferred === false) {\n this._traverseSelections(defer, record, data);\n } else {\n this._incrementalPlaceholders.push({\n kind: 'defer',\n data: data,\n label: defer.label,\n path: (0, _toConsumableArray2[\"default\"])(this._path),\n selector: createNormalizationSelector(defer, RelayModernRecord.getDataID(record), this._variables),\n typeName: RelayModernRecord.getType(record),\n actorIdentifier: this._actorIdentifier\n });\n }\n };\n _proto._normalizeStream = function _normalizeStream(stream, record, data) {\n this._traverseSelections(stream, record, data);\n var isStreamed = stream[\"if\"] === null || this._getVariableValue(stream[\"if\"]);\n if (process.env.NODE_ENV !== \"production\") {\n process.env.NODE_ENV !== \"production\" ? warning(typeof isStreamed === 'boolean', 'RelayResponseNormalizer: Expected value for @stream `if` argument ' + 'to be a boolean, got `%s`.', isStreamed) : void 0;\n }\n if (isStreamed === true) {\n this._incrementalPlaceholders.push({\n kind: 'stream',\n label: stream.label,\n path: (0, _toConsumableArray2[\"default\"])(this._path),\n parentID: RelayModernRecord.getDataID(record),\n node: stream,\n variables: this._variables,\n actorIdentifier: this._actorIdentifier\n });\n }\n };\n _proto._normalizeModuleImport = function _normalizeModuleImport(moduleImport, record, data) {\n !(typeof data === 'object' && data) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayResponseNormalizer: Expected data for @module to be an object.') : invariant(false) : void 0;\n var typeName = RelayModernRecord.getType(record);\n var componentKey = getModuleComponentKey(moduleImport.documentName);\n var componentReference = moduleImport.componentModuleProvider || data[componentKey];\n RelayModernRecord.setValue(record, componentKey, componentReference !== null && componentReference !== void 0 ? componentReference : null);\n var operationKey = getModuleOperationKey(moduleImport.documentName);\n var operationReference = moduleImport.operationModuleProvider || data[operationKey];\n RelayModernRecord.setValue(record, operationKey, operationReference !== null && operationReference !== void 0 ? operationReference : null);\n if (operationReference != null) {\n this._followupPayloads.push({\n kind: 'ModuleImportPayload',\n args: moduleImport.args,\n data: data,\n dataID: RelayModernRecord.getDataID(record),\n operationReference: operationReference,\n path: (0, _toConsumableArray2[\"default\"])(this._path),\n typeName: typeName,\n variables: this._variables,\n actorIdentifier: this._actorIdentifier\n });\n }\n };\n _proto._normalizeField = function _normalizeField(selection, record, data) {\n !(typeof data === 'object' && data) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'writeField(): Expected data for field `%s` to be an object.', selection.name) : invariant(false) : void 0;\n var responseKey = selection.alias || selection.name;\n var storageKey = getStorageKey(selection, this._variables);\n var fieldValue = data[responseKey];\n if (fieldValue == null) {\n if (fieldValue === undefined) {\n var isOptionalField = this._isClientExtension || this._isUnmatchedAbstractType;\n if (isOptionalField) {\n return;\n } else if (!this._treatMissingFieldsAsNull) {\n if (process.env.NODE_ENV !== \"production\") {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'RelayResponseNormalizer: Payload did not contain a value ' + 'for field `%s: %s`. Check that you are parsing with the same ' + 'query that was used to fetch the payload.', responseKey, storageKey) : void 0;\n }\n return;\n }\n }\n if (process.env.NODE_ENV !== \"production\") {\n if (selection.kind === SCALAR_FIELD) {\n this._validateConflictingFieldsWithIdenticalId(record, storageKey, null);\n }\n }\n RelayModernRecord.setValue(record, storageKey, null);\n var errorTrie = this._errorTrie;\n if (errorTrie != null) {\n var errors = getErrorsByKey(errorTrie, responseKey);\n if (errors != null) {\n RelayModernRecord.setErrors(record, storageKey, errors);\n }\n }\n return;\n }\n if (selection.kind === SCALAR_FIELD) {\n if (process.env.NODE_ENV !== \"production\") {\n this._validateConflictingFieldsWithIdenticalId(record, storageKey, fieldValue);\n }\n RelayModernRecord.setValue(record, storageKey, fieldValue);\n } else if (selection.kind === LINKED_FIELD) {\n this._path.push(responseKey);\n var oldErrorTrie = this._errorTrie;\n this._errorTrie = oldErrorTrie == null ? null : getNestedErrorTrieByKey(oldErrorTrie, responseKey);\n if (selection.plural) {\n this._normalizePluralLink(selection, record, storageKey, fieldValue);\n } else {\n this._normalizeLink(selection, record, storageKey, fieldValue);\n }\n this._errorTrie = oldErrorTrie;\n this._path.pop();\n } else {\n selection;\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayResponseNormalizer(): Unexpected ast kind `%s` during normalization.', selection.kind) : invariant(false) : void 0;\n }\n };\n _proto._normalizeActorChange = function _normalizeActorChange(selection, record, data) {\n var _field$concreteType;\n var field = selection.linkedField;\n !(typeof data === 'object' && data) ? process.env.NODE_ENV !== \"production\" ? invariant(false, '_normalizeActorChange(): Expected data for field `%s` to be an object.', field.name) : invariant(false) : void 0;\n var responseKey = field.alias || field.name;\n var storageKey = getStorageKey(field, this._variables);\n var fieldValue = data[responseKey];\n if (fieldValue == null) {\n if (fieldValue === undefined) {\n var isOptionalField = this._isClientExtension || this._isUnmatchedAbstractType;\n if (isOptionalField) {\n return;\n } else if (!this._treatMissingFieldsAsNull) {\n if (process.env.NODE_ENV !== \"production\") {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'RelayResponseNormalizer: Payload did not contain a value ' + 'for field `%s: %s`. Check that you are parsing with the same ' + 'query that was used to fetch the payload.', responseKey, storageKey) : void 0;\n }\n return;\n }\n }\n RelayModernRecord.setValue(record, storageKey, null);\n return;\n }\n var actorIdentifier = getActorIdentifierFromPayload(fieldValue);\n if (actorIdentifier == null) {\n if (process.env.NODE_ENV !== \"production\") {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'RelayResponseNormalizer: Payload did not contain a value ' + 'for field `%s`. Check that you are parsing with the same ' + 'query that was used to fetch the payload. Payload is `%s`.', ACTOR_IDENTIFIER_FIELD_NAME, JSON.stringify(fieldValue, null, 2)) : void 0;\n }\n RelayModernRecord.setValue(record, storageKey, null);\n return;\n }\n var typeName = (_field$concreteType = field.concreteType) !== null && _field$concreteType !== void 0 ? _field$concreteType : this._getRecordType(fieldValue);\n var nextID = this._getDataId(fieldValue, typeName) || RelayModernRecord.getLinkedRecordID(record, storageKey) || generateClientID(RelayModernRecord.getDataID(record), storageKey);\n !(typeof nextID === 'string') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayResponseNormalizer: Expected id on field `%s` to be a string.', storageKey) : invariant(false) : void 0;\n RelayModernRecord.setActorLinkedRecordID(record, storageKey, actorIdentifier, nextID);\n this._followupPayloads.push({\n kind: 'ActorPayload',\n data: fieldValue,\n dataID: nextID,\n path: [].concat((0, _toConsumableArray2[\"default\"])(this._path), [responseKey]),\n typeName: typeName,\n variables: this._variables,\n node: field,\n actorIdentifier: actorIdentifier\n });\n };\n _proto._normalizeLink = function _normalizeLink(field, record, storageKey, fieldValue) {\n var _field$concreteType2;\n !(typeof fieldValue === 'object' && fieldValue) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayResponseNormalizer: Expected data for field `%s` to be an object.', storageKey) : invariant(false) : void 0;\n var nextID = this._getDataId(fieldValue, (_field$concreteType2 = field.concreteType) !== null && _field$concreteType2 !== void 0 ? _field$concreteType2 : this._getRecordType(fieldValue)) || RelayModernRecord.getLinkedRecordID(record, storageKey) || generateClientID(RelayModernRecord.getDataID(record), storageKey);\n !(typeof nextID === 'string') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayResponseNormalizer: Expected id on field `%s` to be a string.', storageKey) : invariant(false) : void 0;\n if (process.env.NODE_ENV !== \"production\") {\n this._validateConflictingLinkedFieldsWithIdenticalId(RelayModernRecord.getLinkedRecordID(record, storageKey), nextID, storageKey);\n }\n RelayModernRecord.setLinkedRecordID(record, storageKey, nextID);\n var nextRecord = this._recordSource.get(nextID);\n if (!nextRecord) {\n var typeName = field.concreteType || this._getRecordType(fieldValue);\n nextRecord = RelayModernRecord.create(nextID, typeName);\n this._recordSource.set(nextID, nextRecord);\n } else if (process.env.NODE_ENV !== \"production\") {\n this._validateRecordType(nextRecord, field, fieldValue);\n }\n this._traverseSelections(field, nextRecord, fieldValue);\n };\n _proto._normalizePluralLink = function _normalizePluralLink(field, record, storageKey, fieldValue) {\n var _this = this;\n !Array.isArray(fieldValue) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayResponseNormalizer: Expected data for field `%s` to be an array ' + 'of objects.', storageKey) : invariant(false) : void 0;\n var prevIDs = RelayModernRecord.getLinkedRecordIDs(record, storageKey);\n var nextIDs = [];\n fieldValue.forEach(function (item, nextIndex) {\n var _field$concreteType3;\n if (item == null) {\n nextIDs.push(item);\n return;\n }\n _this._path.push(String(nextIndex));\n var oldErrorTrie = _this._errorTrie;\n _this._errorTrie = oldErrorTrie == null ? null : getNestedErrorTrieByKey(oldErrorTrie, nextIndex);\n !(typeof item === 'object') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayResponseNormalizer: Expected elements for field `%s` to be ' + 'objects.', storageKey) : invariant(false) : void 0;\n var nextID = _this._getDataId(item, (_field$concreteType3 = field.concreteType) !== null && _field$concreteType3 !== void 0 ? _field$concreteType3 : _this._getRecordType(item)) || prevIDs && prevIDs[nextIndex] || generateClientID(RelayModernRecord.getDataID(record), storageKey, nextIndex);\n !(typeof nextID === 'string') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayResponseNormalizer: Expected id of elements of field `%s` to ' + 'be strings.', storageKey) : invariant(false) : void 0;\n nextIDs.push(nextID);\n var nextRecord = _this._recordSource.get(nextID);\n if (!nextRecord) {\n var typeName = field.concreteType || _this._getRecordType(item);\n nextRecord = RelayModernRecord.create(nextID, typeName);\n _this._recordSource.set(nextID, nextRecord);\n } else if (process.env.NODE_ENV !== \"production\") {\n _this._validateRecordType(nextRecord, field, item);\n }\n if (process.env.NODE_ENV !== \"production\") {\n if (prevIDs) {\n _this._validateConflictingLinkedFieldsWithIdenticalId(prevIDs[nextIndex], nextID, storageKey);\n }\n }\n _this._traverseSelections(field, nextRecord, item);\n _this._errorTrie = oldErrorTrie;\n _this._path.pop();\n });\n RelayModernRecord.setLinkedRecordIDs(record, storageKey, nextIDs);\n };\n _proto._validateRecordType = function _validateRecordType(record, field, payload) {\n var _field$concreteType4;\n var typeName = (_field$concreteType4 = field.concreteType) !== null && _field$concreteType4 !== void 0 ? _field$concreteType4 : this._getRecordType(payload);\n var dataID = RelayModernRecord.getDataID(record);\n process.env.NODE_ENV !== \"production\" ? warning(isClientID(dataID) && dataID !== ROOT_ID || RelayModernRecord.getType(record) === typeName, 'RelayResponseNormalizer: Invalid record `%s`. Expected %s to be ' + 'consistent, but the record was assigned conflicting types `%s` ' + 'and `%s`. The GraphQL server likely violated the globally unique ' + 'id requirement by returning the same id for different objects.', dataID, TYPENAME_KEY, RelayModernRecord.getType(record), typeName) : void 0;\n };\n _proto._validateConflictingFieldsWithIdenticalId = function _validateConflictingFieldsWithIdenticalId(record, storageKey, fieldValue) {\n if (process.env.NODE_ENV !== \"production\") {\n var dataID = RelayModernRecord.getDataID(record);\n var previousValue = RelayModernRecord.getValue(record, storageKey);\n process.env.NODE_ENV !== \"production\" ? warning(storageKey === TYPENAME_KEY || previousValue === undefined || areEqual(previousValue, fieldValue), 'RelayResponseNormalizer: Invalid record. The record contains two ' + 'instances of the same id: `%s` with conflicting field, %s and its values: %s and %s. ' + 'If two fields are different but share ' + 'the same id, one field will overwrite the other.', dataID, storageKey, previousValue, fieldValue) : void 0;\n }\n };\n _proto._validateConflictingLinkedFieldsWithIdenticalId = function _validateConflictingLinkedFieldsWithIdenticalId(prevID, nextID, storageKey) {\n if (process.env.NODE_ENV !== \"production\") {\n process.env.NODE_ENV !== \"production\" ? warning(prevID === undefined || prevID === nextID, 'RelayResponseNormalizer: Invalid record. The record contains ' + 'references to the conflicting field, %s and its id values: %s and %s. ' + 'We need to make sure that the record the field points ' + 'to remains consistent or one field will overwrite the other.', storageKey, prevID, nextID) : void 0;\n }\n };\n return RelayResponseNormalizer;\n}();\nmodule.exports = {\n normalize: normalize\n};","'use strict';\n\nvar deepFreeze = require('../util/deepFreeze');\nvar recycleNodesInto = require('../util/recycleNodesInto');\nvar RelayFeatureFlags = require('../util/RelayFeatureFlags');\nvar hasOverlappingIDs = require('./hasOverlappingIDs');\nvar hasSignificantOverlappingIDs = require('./hasSignificantOverlappingIDs');\nvar RelayReader = require('./RelayReader');\nvar RelayStoreSubscriptions = /*#__PURE__*/function () {\n function RelayStoreSubscriptions(log, resolverCache) {\n this._subscriptions = new Set();\n this.__log = log;\n this._resolverCache = resolverCache;\n }\n var _proto = RelayStoreSubscriptions.prototype;\n _proto.subscribe = function subscribe(snapshot, callback) {\n var _this = this;\n var subscription = {\n backup: null,\n callback: callback,\n snapshot: snapshot,\n stale: false\n };\n var dispose = function dispose() {\n _this._subscriptions[\"delete\"](subscription);\n };\n this._subscriptions.add(subscription);\n return {\n dispose: dispose\n };\n };\n _proto.snapshotSubscriptions = function snapshotSubscriptions(source) {\n var _this2 = this;\n this._subscriptions.forEach(function (subscription) {\n if (!subscription.stale) {\n subscription.backup = subscription.snapshot;\n return;\n }\n var snapshot = subscription.snapshot;\n var backup = RelayReader.read(source, snapshot.selector, _this2._resolverCache);\n var nextData = recycleNodesInto(snapshot.data, backup.data);\n backup.data = nextData;\n subscription.backup = backup;\n });\n };\n _proto.restoreSubscriptions = function restoreSubscriptions() {\n this._subscriptions.forEach(function (subscription) {\n var backup = subscription.backup;\n subscription.backup = null;\n if (backup) {\n if (backup.data !== subscription.snapshot.data) {\n subscription.stale = true;\n }\n subscription.snapshot = {\n data: subscription.snapshot.data,\n isMissingData: backup.isMissingData,\n missingClientEdges: backup.missingClientEdges,\n missingLiveResolverFields: backup.missingLiveResolverFields,\n seenRecords: backup.seenRecords,\n selector: backup.selector,\n missingRequiredFields: backup.missingRequiredFields,\n relayResolverErrors: backup.relayResolverErrors,\n errorResponseFields: backup.errorResponseFields\n };\n } else {\n subscription.stale = true;\n }\n });\n };\n _proto.updateSubscriptions = function updateSubscriptions(source, updatedRecordIDs, updatedOwners, sourceOperation) {\n var _this3 = this;\n var hasUpdatedRecords = updatedRecordIDs.size !== 0;\n this._subscriptions.forEach(function (subscription) {\n var owner = _this3._updateSubscription(source, subscription, updatedRecordIDs, hasUpdatedRecords, sourceOperation);\n if (owner != null) {\n updatedOwners.push(owner);\n }\n });\n };\n _proto._updateSubscription = function _updateSubscription(source, subscription, updatedRecordIDs, hasUpdatedRecords, sourceOperation) {\n var backup = subscription.backup,\n callback = subscription.callback,\n snapshot = subscription.snapshot,\n stale = subscription.stale;\n var hasOverlappingUpdates = hasUpdatedRecords && hasOverlappingIDs(snapshot.seenRecords, updatedRecordIDs);\n if (!stale && !hasOverlappingUpdates) {\n return;\n }\n var nextSnapshot = hasOverlappingUpdates || !backup ? RelayReader.read(source, snapshot.selector, this._resolverCache) : backup;\n var nextData = recycleNodesInto(snapshot.data, nextSnapshot.data);\n nextSnapshot = {\n data: nextData,\n isMissingData: nextSnapshot.isMissingData,\n missingClientEdges: nextSnapshot.missingClientEdges,\n missingLiveResolverFields: nextSnapshot.missingLiveResolverFields,\n seenRecords: nextSnapshot.seenRecords,\n selector: nextSnapshot.selector,\n missingRequiredFields: nextSnapshot.missingRequiredFields,\n relayResolverErrors: nextSnapshot.relayResolverErrors,\n errorResponseFields: nextSnapshot.errorResponseFields\n };\n if (process.env.NODE_ENV !== \"production\") {\n deepFreeze(nextSnapshot);\n }\n subscription.snapshot = nextSnapshot;\n subscription.stale = false;\n if (nextSnapshot.data !== snapshot.data) {\n if (this.__log && RelayFeatureFlags.ENABLE_NOTIFY_SUBSCRIPTION) {\n this.__log({\n name: 'store.notify.subscription',\n sourceOperation: sourceOperation,\n snapshot: snapshot,\n nextSnapshot: nextSnapshot\n });\n }\n callback(nextSnapshot);\n return snapshot.selector.owner;\n }\n if (RelayFeatureFlags.ENABLE_LOOSE_SUBSCRIPTION_ATTRIBUTION && (stale || hasSignificantOverlappingIDs(snapshot.seenRecords, updatedRecordIDs))) {\n return snapshot.selector.owner;\n }\n };\n return RelayStoreSubscriptions;\n}();\nmodule.exports = RelayStoreSubscriptions;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _toConsumableArray2 = _interopRequireDefault(require(\"@babel/runtime/helpers/toConsumableArray\"));\nvar getRelayHandleKey = require('../util/getRelayHandleKey');\nvar RelayConcreteNode = require('../util/RelayConcreteNode');\nvar stableCopy = require('../util/stableCopy');\nvar invariant = require('invariant');\nvar VARIABLE = RelayConcreteNode.VARIABLE,\n LITERAL = RelayConcreteNode.LITERAL,\n OBJECT_VALUE = RelayConcreteNode.OBJECT_VALUE,\n LIST_VALUE = RelayConcreteNode.LIST_VALUE;\nvar ERRORS_KEY = '__errors';\nvar MODULE_COMPONENT_KEY_PREFIX = '__module_component_';\nvar MODULE_OPERATION_KEY_PREFIX = '__module_operation_';\nfunction getArgumentValue(arg, variables) {\n if (arg.kind === VARIABLE) {\n return getStableVariableValue(arg.variableName, variables);\n } else if (arg.kind === LITERAL) {\n return arg.value;\n } else if (arg.kind === OBJECT_VALUE) {\n var value = {};\n arg.fields.forEach(function (field) {\n value[field.name] = getArgumentValue(field, variables);\n });\n return value;\n } else if (arg.kind === LIST_VALUE) {\n var _value = [];\n arg.items.forEach(function (item) {\n item != null ? _value.push(getArgumentValue(item, variables)) : null;\n });\n return _value;\n }\n}\nfunction getArgumentValues(args, variables, isWithinUnmatchedTypeRefinement) {\n var values = {};\n if (isWithinUnmatchedTypeRefinement) {\n values[RelayStoreUtils.FRAGMENT_POINTER_IS_WITHIN_UNMATCHED_TYPE_REFINEMENT] = true;\n }\n if (args) {\n args.forEach(function (arg) {\n values[arg.name] = getArgumentValue(arg, variables);\n });\n }\n return values;\n}\nfunction getHandleStorageKey(handleField, variables) {\n var dynamicKey = handleField.dynamicKey,\n handle = handleField.handle,\n key = handleField.key,\n name = handleField.name,\n args = handleField.args,\n filters = handleField.filters;\n var handleName = getRelayHandleKey(handle, key, name);\n var filterArgs = null;\n if (args && filters && args.length !== 0 && filters.length !== 0) {\n filterArgs = args.filter(function (arg) {\n return filters.indexOf(arg.name) > -1;\n });\n }\n if (dynamicKey) {\n filterArgs = filterArgs != null ? [dynamicKey].concat((0, _toConsumableArray2[\"default\"])(filterArgs)) : [dynamicKey];\n }\n if (filterArgs === null) {\n return handleName;\n } else {\n return formatStorageKey(handleName, getArgumentValues(filterArgs, variables));\n }\n}\nfunction getStorageKey(field, variables) {\n if (field.storageKey) {\n return field.storageKey;\n }\n var args = getArguments(field);\n var name = field.name;\n return args && args.length !== 0 ? formatStorageKey(name, getArgumentValues(args, variables)) : name;\n}\nfunction getArguments(field) {\n if (field.kind === 'RelayResolver' || field.kind === 'RelayLiveResolver') {\n var _field$fragment2;\n if (field.args == null) {\n var _field$fragment;\n return (_field$fragment = field.fragment) === null || _field$fragment === void 0 ? void 0 : _field$fragment.args;\n }\n if (((_field$fragment2 = field.fragment) === null || _field$fragment2 === void 0 ? void 0 : _field$fragment2.args) == null) {\n return field.args;\n }\n return field.args.concat(field.fragment.args);\n }\n var args = typeof field.args === 'undefined' ? undefined : field.args;\n return args;\n}\nfunction getStableStorageKey(name, args) {\n return formatStorageKey(name, stableCopy(args));\n}\nfunction formatStorageKey(name, argValues) {\n if (!argValues) {\n return name;\n }\n var values = [];\n for (var argName in argValues) {\n if (argValues.hasOwnProperty(argName)) {\n var value = argValues[argName];\n if (value != null) {\n var _JSON$stringify;\n values.push(argName + ':' + ((_JSON$stringify = JSON.stringify(value)) !== null && _JSON$stringify !== void 0 ? _JSON$stringify : 'undefined'));\n }\n }\n }\n return values.length === 0 ? name : name + \"(\".concat(values.join(','), \")\");\n}\nfunction getStableVariableValue(name, variables) {\n !variables.hasOwnProperty(name) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'getVariableValue(): Undefined variable `%s`.', name) : invariant(false) : void 0;\n return stableCopy(variables[name]);\n}\nfunction getModuleComponentKey(documentName) {\n return \"\".concat(MODULE_COMPONENT_KEY_PREFIX).concat(documentName);\n}\nfunction getModuleOperationKey(documentName) {\n return \"\".concat(MODULE_OPERATION_KEY_PREFIX).concat(documentName);\n}\nvar RelayStoreUtils = {\n ACTOR_IDENTIFIER_KEY: '__actorIdentifier',\n CLIENT_EDGE_TRAVERSAL_PATH: '__clientEdgeTraversalPath',\n FRAGMENTS_KEY: '__fragments',\n FRAGMENT_OWNER_KEY: '__fragmentOwner',\n FRAGMENT_POINTER_IS_WITHIN_UNMATCHED_TYPE_REFINEMENT: '$isWithinUnmatchedTypeRefinement',\n FRAGMENT_PROP_NAME_KEY: '__fragmentPropName',\n MODULE_COMPONENT_KEY: '__module_component',\n ERRORS_KEY: ERRORS_KEY,\n ID_KEY: '__id',\n REF_KEY: '__ref',\n REFS_KEY: '__refs',\n ROOT_ID: 'client:root',\n ROOT_TYPE: '__Root',\n TYPENAME_KEY: '__typename',\n INVALIDATED_AT_KEY: '__invalidated_at',\n RELAY_RESOLVER_VALUE_KEY: '__resolverValue',\n RELAY_RESOLVER_INVALIDATION_KEY: '__resolverValueMayBeInvalid',\n RELAY_RESOLVER_SNAPSHOT_KEY: '__resolverSnapshot',\n RELAY_RESOLVER_ERROR_KEY: '__resolverError',\n RELAY_RESOLVER_OUTPUT_TYPE_RECORD_IDS: '__resolverOutputTypeRecordIDs',\n formatStorageKey: formatStorageKey,\n getArgumentValue: getArgumentValue,\n getArgumentValues: getArgumentValues,\n getHandleStorageKey: getHandleStorageKey,\n getStorageKey: getStorageKey,\n getStableStorageKey: getStableStorageKey,\n getModuleComponentKey: getModuleComponentKey,\n getModuleOperationKey: getModuleOperationKey\n};\nmodule.exports = RelayStoreUtils;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _createForOfIteratorHelper2 = _interopRequireDefault(require(\"@babel/runtime/helpers/createForOfIteratorHelper\"));\nvar recycleNodesInto = require('../util/recycleNodesInto');\nvar _require = require('../util/RelayConcreteNode'),\n RELAY_LIVE_RESOLVER = _require.RELAY_LIVE_RESOLVER;\nvar RelayFeatureFlags = require('../util/RelayFeatureFlags');\nvar shallowFreeze = require('../util/shallowFreeze');\nvar _require2 = require('./ClientID'),\n generateClientID = _require2.generateClientID;\nvar RelayModernRecord = require('./RelayModernRecord');\nvar _require3 = require('./RelayStoreUtils'),\n RELAY_RESOLVER_ERROR_KEY = _require3.RELAY_RESOLVER_ERROR_KEY,\n RELAY_RESOLVER_INVALIDATION_KEY = _require3.RELAY_RESOLVER_INVALIDATION_KEY,\n RELAY_RESOLVER_SNAPSHOT_KEY = _require3.RELAY_RESOLVER_SNAPSHOT_KEY,\n RELAY_RESOLVER_VALUE_KEY = _require3.RELAY_RESOLVER_VALUE_KEY,\n getStorageKey = _require3.getStorageKey;\nvar invariant = require('invariant');\nvar warning = require(\"fbjs/lib/warning\");\nvar emptySet = new Set();\nvar NoopResolverCache = /*#__PURE__*/function () {\n function NoopResolverCache() {}\n var _proto = NoopResolverCache.prototype;\n _proto.readFromCacheOrEvaluate = function readFromCacheOrEvaluate(recordID, field, variables, evaluate, getDataForResolverFragment) {\n !(field.kind !== RELAY_LIVE_RESOLVER) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'This store does not support Live Resolvers') : invariant(false) : void 0;\n var _evaluate = evaluate(),\n resolverResult = _evaluate.resolverResult,\n snapshot = _evaluate.snapshot,\n error = _evaluate.error;\n return [resolverResult, undefined, error, snapshot, undefined, undefined];\n };\n _proto.invalidateDataIDs = function invalidateDataIDs(updatedDataIDs) {};\n _proto.ensureClientRecord = function ensureClientRecord(id, typeName) {\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Client Edges to Client Objects are not supported in this version of Relay Store') : invariant(false) : void 0;\n };\n _proto.notifyUpdatedSubscribers = function notifyUpdatedSubscribers(updatedDataIDs) {};\n return NoopResolverCache;\n}();\nfunction addDependencyEdge(edges, from, to) {\n var set = edges.get(from);\n if (!set) {\n set = new Set();\n edges.set(from, set);\n }\n set.add(to);\n}\nvar RecordResolverCache = /*#__PURE__*/function () {\n function RecordResolverCache(getRecordSource) {\n this._resolverIDToRecordIDs = new Map();\n this._recordIDToResolverIDs = new Map();\n this._getRecordSource = getRecordSource;\n }\n var _proto2 = RecordResolverCache.prototype;\n _proto2.readFromCacheOrEvaluate = function readFromCacheOrEvaluate(recordID, field, variables, evaluate, getDataForResolverFragment) {\n var recordSource = this._getRecordSource();\n var record = recordSource.get(recordID);\n !(record != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'We expect record to exist in the store.') : invariant(false) : void 0;\n var storageKey = getStorageKey(field, variables);\n var linkedID = RelayModernRecord.getLinkedRecordID(record, storageKey);\n var linkedRecord = linkedID == null ? null : recordSource.get(linkedID);\n if (linkedRecord == null || this._isInvalid(linkedRecord, getDataForResolverFragment)) {\n var _linkedID;\n linkedID = (_linkedID = linkedID) !== null && _linkedID !== void 0 ? _linkedID : generateClientID(recordID, storageKey);\n linkedRecord = RelayModernRecord.create(linkedID, '__RELAY_RESOLVER__');\n var evaluationResult = evaluate();\n if (RelayFeatureFlags.ENABLE_SHALLOW_FREEZE_RESOLVER_VALUES) {\n shallowFreeze(evaluationResult.resolverResult);\n }\n RelayModernRecord.setValue(linkedRecord, RELAY_RESOLVER_VALUE_KEY, evaluationResult.resolverResult);\n RelayModernRecord.setValue(linkedRecord, RELAY_RESOLVER_SNAPSHOT_KEY, evaluationResult.snapshot);\n RelayModernRecord.setValue(linkedRecord, RELAY_RESOLVER_ERROR_KEY, evaluationResult.error);\n recordSource.set(linkedID, linkedRecord);\n var currentRecord = recordSource.get(recordID);\n !(currentRecord != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Expected the parent record to still be in the record source.') : invariant(false) : void 0;\n var nextRecord = RelayModernRecord.clone(currentRecord);\n RelayModernRecord.setLinkedRecordID(nextRecord, storageKey, linkedID);\n recordSource.set(recordID, nextRecord);\n if (field.fragment != null) {\n var _evaluationResult$sna;\n var fragmentStorageKey = getStorageKey(field.fragment, variables);\n var resolverID = generateClientID(recordID, fragmentStorageKey);\n addDependencyEdge(this._resolverIDToRecordIDs, resolverID, linkedID);\n addDependencyEdge(this._recordIDToResolverIDs, recordID, resolverID);\n var seenRecordIds = (_evaluationResult$sna = evaluationResult.snapshot) === null || _evaluationResult$sna === void 0 ? void 0 : _evaluationResult$sna.seenRecords;\n if (seenRecordIds != null) {\n var _iterator = (0, _createForOfIteratorHelper2[\"default\"])(seenRecordIds),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var seenRecordID = _step.value;\n addDependencyEdge(this._recordIDToResolverIDs, seenRecordID, resolverID);\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n }\n }\n }\n var answer = RelayModernRecord.getValue(linkedRecord, RELAY_RESOLVER_VALUE_KEY);\n var snapshot = RelayModernRecord.getValue(linkedRecord, RELAY_RESOLVER_SNAPSHOT_KEY);\n var error = RelayModernRecord.getValue(linkedRecord, RELAY_RESOLVER_ERROR_KEY);\n return [answer, linkedID, error, snapshot, undefined, undefined];\n };\n _proto2.invalidateDataIDs = function invalidateDataIDs(updatedDataIDs) {\n var recordSource = this._getRecordSource();\n var visited = new Set();\n var recordsToVisit = Array.from(updatedDataIDs);\n while (recordsToVisit.length) {\n var recordID = recordsToVisit.pop();\n updatedDataIDs.add(recordID);\n var _iterator2 = (0, _createForOfIteratorHelper2[\"default\"])((_this$_recordIDToReso = this._recordIDToResolverIDs.get(recordID)) !== null && _this$_recordIDToReso !== void 0 ? _this$_recordIDToReso : emptySet),\n _step2;\n try {\n for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n var _this$_recordIDToReso;\n var fragment = _step2.value;\n if (!visited.has(fragment)) {\n var _iterator3 = (0, _createForOfIteratorHelper2[\"default\"])((_this$_resolverIDToRe = this._resolverIDToRecordIDs.get(fragment)) !== null && _this$_resolverIDToRe !== void 0 ? _this$_resolverIDToRe : emptySet),\n _step3;\n try {\n for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {\n var _this$_resolverIDToRe;\n var anotherRecordID = _step3.value;\n this._markInvalidatedResolverRecord(anotherRecordID, recordSource, updatedDataIDs);\n if (!visited.has(anotherRecordID)) {\n recordsToVisit.push(anotherRecordID);\n }\n }\n } catch (err) {\n _iterator3.e(err);\n } finally {\n _iterator3.f();\n }\n }\n }\n } catch (err) {\n _iterator2.e(err);\n } finally {\n _iterator2.f();\n }\n }\n };\n _proto2._markInvalidatedResolverRecord = function _markInvalidatedResolverRecord(dataID, recordSource, updatedDataIDs) {\n var record = recordSource.get(dataID);\n if (!record) {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'Expected a resolver record with ID %s, but it was missing.', dataID) : void 0;\n return;\n }\n var nextRecord = RelayModernRecord.clone(record);\n RelayModernRecord.setValue(nextRecord, RELAY_RESOLVER_INVALIDATION_KEY, true);\n recordSource.set(dataID, nextRecord);\n };\n _proto2._isInvalid = function _isInvalid(record, getDataForResolverFragment) {\n if (!RelayModernRecord.getValue(record, RELAY_RESOLVER_INVALIDATION_KEY)) {\n return false;\n }\n var snapshot = RelayModernRecord.getValue(record, RELAY_RESOLVER_SNAPSHOT_KEY);\n var originalInputs = snapshot === null || snapshot === void 0 ? void 0 : snapshot.data;\n var readerSelector = snapshot === null || snapshot === void 0 ? void 0 : snapshot.selector;\n if (originalInputs == null || readerSelector == null) {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'Expected previous inputs and reader selector on resolver record with ID %s, but they were missing.', RelayModernRecord.getDataID(record)) : void 0;\n return true;\n }\n var _getDataForResolverFr = getDataForResolverFragment(readerSelector),\n latestValues = _getDataForResolverFr.data;\n var recycled = recycleNodesInto(originalInputs, latestValues);\n if (recycled !== originalInputs) {\n return true;\n }\n return false;\n };\n _proto2.ensureClientRecord = function ensureClientRecord(id, typename) {\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Client Edges to Client Objects are not supported in this version of Relay Store') : invariant(false) : void 0;\n };\n _proto2.notifyUpdatedSubscribers = function notifyUpdatedSubscribers(updatedDataIDs) {\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Processing @outputType records is not supported in this version of Relay Store') : invariant(false) : void 0;\n };\n return RecordResolverCache;\n}();\nmodule.exports = {\n NoopResolverCache: NoopResolverCache,\n RecordResolverCache: RecordResolverCache\n};","'use strict';\n\nvar _require = require('../query/GraphQLTag'),\n getFragment = _require.getFragment;\nvar _require2 = require('./RelayModernSelector'),\n getSelector = _require2.getSelector;\nvar invariant = require('invariant');\nvar contextStack = [];\nfunction withResolverContext(context, cb) {\n contextStack.push(context);\n try {\n return cb();\n } finally {\n contextStack.pop();\n }\n}\nfunction readFragment(fragmentInput, fragmentKey) {\n if (!contextStack.length) {\n throw new Error('readFragment should be called only from within a Relay Resolver function.');\n }\n var context = contextStack[contextStack.length - 1];\n var fragmentNode = getFragment(fragmentInput);\n var fragmentSelector = getSelector(fragmentNode, fragmentKey);\n !(fragmentSelector != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, \"Expected a selector for the fragment of the resolver \".concat(fragmentNode.name, \", but got null.\")) : invariant(false) : void 0;\n !(fragmentSelector.kind === 'SingularReaderSelector') ? process.env.NODE_ENV !== \"production\" ? invariant(false, \"Expected a singular reader selector for the fragment of the resolver \".concat(fragmentNode.name, \", but it was plural.\")) : invariant(false) : void 0;\n var _context$getDataForRe = context.getDataForResolverFragment(fragmentSelector, fragmentKey),\n data = _context$getDataForRe.data,\n isMissingData = _context$getDataForRe.isMissingData;\n if (isMissingData) {\n throw RESOLVER_FRAGMENT_MISSING_DATA_SENTINEL;\n }\n return data;\n}\nvar RESOLVER_FRAGMENT_MISSING_DATA_SENTINEL = {};\nmodule.exports = {\n readFragment: readFragment,\n withResolverContext: withResolverContext,\n RESOLVER_FRAGMENT_MISSING_DATA_SENTINEL: RESOLVER_FRAGMENT_MISSING_DATA_SENTINEL\n};","'use strict';\n\nvar PREFIX = 'client:__type:';\nvar TYPE_SCHEMA_TYPE = '__TypeSchema';\nfunction generateTypeID(typeName) {\n return PREFIX + typeName;\n}\nfunction isTypeID(id) {\n return id.indexOf(PREFIX) === 0;\n}\nmodule.exports = {\n generateTypeID: generateTypeID,\n isTypeID: isTypeID,\n TYPE_SCHEMA_TYPE: TYPE_SCHEMA_TYPE\n};","'use strict';\n\nvar _require = require('./ClientID'),\n generateClientID = _require.generateClientID;\nvar _require2 = require('./RelayStoreUtils'),\n ROOT_ID = _require2.ROOT_ID;\nvar VIEWER_ID = generateClientID(ROOT_ID, 'viewer');\nvar VIEWER_TYPE = 'Viewer';\nmodule.exports = {\n VIEWER_ID: VIEWER_ID,\n VIEWER_TYPE: VIEWER_TYPE\n};","'use strict';\n\nvar _require = require('../util/RelayConcreteNode'),\n LINKED_FIELD = _require.LINKED_FIELD;\nvar _require2 = require('./RelayStoreUtils'),\n getHandleStorageKey = _require2.getHandleStorageKey;\nvar areEqual = require(\"fbjs/lib/areEqual\");\nvar invariant = require('invariant');\nfunction cloneRelayHandleSourceField(handleField, selections, variables) {\n var sourceField = selections.find(function (source) {\n return source.kind === LINKED_FIELD && source.name === handleField.name && source.alias === handleField.alias && areEqual(source.args, handleField.args);\n });\n !(sourceField && sourceField.kind === LINKED_FIELD) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'cloneRelayHandleSourceField: Expected a corresponding source field for ' + 'handle `%s`.', handleField.handle) : invariant(false) : void 0;\n var handleKey = getHandleStorageKey(handleField, variables);\n return {\n kind: 'LinkedField',\n alias: sourceField.alias,\n name: handleKey,\n storageKey: handleKey,\n args: null,\n concreteType: sourceField.concreteType,\n plural: sourceField.plural,\n selections: sourceField.selections\n };\n}\nmodule.exports = cloneRelayHandleSourceField;","'use strict';\n\nvar _require = require('../util/RelayConcreteNode'),\n SCALAR_FIELD = _require.SCALAR_FIELD;\nvar _require2 = require('./RelayStoreUtils'),\n getHandleStorageKey = _require2.getHandleStorageKey;\nvar areEqual = require(\"fbjs/lib/areEqual\");\nvar invariant = require('invariant');\nfunction cloneRelayScalarHandleSourceField(handleField, selections, variables) {\n var sourceField = selections.find(function (source) {\n return source.kind === SCALAR_FIELD && source.name === handleField.name && source.alias === handleField.alias && areEqual(source.args, handleField.args);\n });\n !(sourceField && sourceField.kind === SCALAR_FIELD) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'cloneRelayScalarHandleSourceField: Expected a corresponding source field for ' + 'handle `%s`.', handleField.handle) : invariant(false) : void 0;\n var handleKey = getHandleStorageKey(handleField, variables);\n return {\n kind: 'ScalarField',\n alias: sourceField.alias,\n name: handleKey,\n storageKey: handleKey,\n args: null\n };\n}\nmodule.exports = cloneRelayScalarHandleSourceField;","'use strict';\n\nvar RelayModernFragmentSpecResolver = require('./RelayModernFragmentSpecResolver');\nvar warning = require(\"fbjs/lib/warning\");\nfunction createFragmentSpecResolver(context, containerName, fragments, props, rootIsQueryRenderer, callback) {\n if (process.env.NODE_ENV !== \"production\") {\n var fragmentNames = Object.keys(fragments);\n fragmentNames.forEach(function (fragmentName) {\n var propValue = props[fragmentName];\n process.env.NODE_ENV !== \"production\" ? warning(propValue !== undefined, 'createFragmentSpecResolver: Expected prop `%s` to be supplied to `%s`, but ' + 'got `undefined`. Pass an explicit `null` if this is intentional.', fragmentName, containerName) : void 0;\n });\n }\n return new RelayModernFragmentSpecResolver(context, fragments, props, callback, rootIsQueryRenderer);\n}\nmodule.exports = createFragmentSpecResolver;","'use strict';\n\nvar invariant = require('invariant');\nvar relayContext;\nvar firstReact;\nfunction createRelayContext(react) {\n if (!relayContext) {\n relayContext = react.createContext(null);\n if (process.env.NODE_ENV !== \"production\") {\n relayContext.displayName = 'RelayContext';\n }\n firstReact = react;\n }\n !(react === firstReact) ? process.env.NODE_ENV !== \"production\" ? invariant(false, '[createRelayContext]: You are passing a different instance of React', react.version) : invariant(false) : void 0;\n return relayContext;\n}\nmodule.exports = createRelayContext;","'use strict';\n\nvar _require = require('./ViewerPattern'),\n VIEWER_ID = _require.VIEWER_ID,\n VIEWER_TYPE = _require.VIEWER_TYPE;\nfunction defaultGetDataID(fieldValue, typeName) {\n if (typeName === VIEWER_TYPE) {\n return fieldValue.id == null ? VIEWER_ID : fieldValue.id;\n }\n return fieldValue.id;\n}\nmodule.exports = defaultGetDataID;","'use strict';\n\nvar defaultRelayFieldLogger = function defaultRelayFieldLogger(event) {\n if (process.env.NODE_ENV !== \"production\" && event.kind === 'missing_field.log') {\n throw new Error('Relay Environment Configuration Error (dev only): `@required(action: LOG)` requires that the Relay Environment be configured with a `relayFieldLogger`.');\n }\n};\nmodule.exports = defaultRelayFieldLogger;","'use strict';\n\nvar LIVE_RESOLVER_SUSPENSE_SENTINEL = Object.freeze({\n __LIVE_RESOLVER_SUSPENSE_SENTINEL: true\n});\nfunction suspenseSentinel() {\n return LIVE_RESOLVER_SUSPENSE_SENTINEL;\n}\nfunction isSuspenseSentinel(value) {\n return value === LIVE_RESOLVER_SUSPENSE_SENTINEL;\n}\nmodule.exports = {\n isSuspenseSentinel: isSuspenseSentinel,\n suspenseSentinel: suspenseSentinel\n};","'use strict';\n\nvar RelayModernRecord = require('../RelayModernRecord');\nvar _require = require('../RelayStoreUtils'),\n RELAY_RESOLVER_OUTPUT_TYPE_RECORD_IDS = _require.RELAY_RESOLVER_OUTPUT_TYPE_RECORD_IDS;\nvar invariant = require('invariant');\nfunction getOutputTypeRecordIDs(record) {\n var maybeOutputTypeRecordIDs = RelayModernRecord.getValue(record, RELAY_RESOLVER_OUTPUT_TYPE_RECORD_IDS);\n if (maybeOutputTypeRecordIDs == null) {\n return null;\n }\n !(maybeOutputTypeRecordIDs instanceof Set) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'getOutputTypeRecordIDs: Expected the `%s` field on record `%s` to be of type Set. Instead, it is a %s.', RELAY_RESOLVER_OUTPUT_TYPE_RECORD_IDS, typeof maybeOutputTypeRecordIDs) : invariant(false) : void 0;\n return maybeOutputTypeRecordIDs;\n}\nmodule.exports = getOutputTypeRecordIDs;","'use strict';\n\nvar ITERATOR_KEY = Symbol.iterator;\nfunction hasOverlappingIDs(seenRecords, updatedRecordIDs) {\n var iterator = seenRecords[ITERATOR_KEY]();\n var next = iterator.next();\n while (!next.done) {\n var key = next.value;\n if (updatedRecordIDs.has(key)) {\n return true;\n }\n next = iterator.next();\n }\n return false;\n}\nmodule.exports = hasOverlappingIDs;","'use strict';\n\nvar _require = require('./RelayStoreUtils'),\n ROOT_ID = _require.ROOT_ID;\nvar _require2 = require('./ViewerPattern'),\n VIEWER_ID = _require2.VIEWER_ID;\nvar ITERATOR_KEY = Symbol.iterator;\nfunction hasSignificantOverlappingIDs(seenRecords, updatedRecordIDs) {\n var iterator = seenRecords[ITERATOR_KEY]();\n var next = iterator.next();\n while (!next.done) {\n var key = next.value;\n if (updatedRecordIDs.has(key) && key !== ROOT_ID && key !== VIEWER_ID) {\n return true;\n }\n next = iterator.next();\n }\n return false;\n}\nmodule.exports = hasSignificantOverlappingIDs;","'use strict';\n\nfunction isRelayModernEnvironment(environment) {\n return Boolean(environment && environment['@@RelayModernEnvironment']);\n}\nmodule.exports = isRelayModernEnvironment;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _objectSpread2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar _RelayModernRecord = _interopRequireDefault(require(\"./RelayModernRecord\"));\nvar _RelayRecordSource = _interopRequireDefault(require(\"./RelayRecordSource\"));\nvar _RelayResponseNormalizer = _interopRequireDefault(require(\"./RelayResponseNormalizer\"));\nfunction normalizeResponse(response, selector, typeName, options) {\n var _response$extensions;\n var data = response.data,\n errors = response.errors;\n var source = _RelayRecordSource[\"default\"].create();\n var record = _RelayModernRecord[\"default\"].create(selector.dataID, typeName);\n source.set(selector.dataID, record);\n var relayPayload = _RelayResponseNormalizer[\"default\"].normalize(source, selector, data, options, errors);\n return (0, _objectSpread2[\"default\"])((0, _objectSpread2[\"default\"])({}, relayPayload), {}, {\n isFinal: ((_response$extensions = response.extensions) === null || _response$extensions === void 0 ? void 0 : _response$extensions.is_final) === true\n });\n}\nmodule.exports = normalizeResponse;","'use strict';\n\nvar _require = require('../query/GraphQLTag'),\n getInlineDataFragment = _require.getInlineDataFragment;\nvar _require2 = require('./RelayStoreUtils'),\n FRAGMENTS_KEY = _require2.FRAGMENTS_KEY;\nvar invariant = require('invariant');\nfunction readInlineData(fragment, fragmentRef) {\n var _fragmentRef$FRAGMENT;\n var inlineDataFragment = getInlineDataFragment(fragment);\n if (fragmentRef == null) {\n return fragmentRef;\n }\n !(typeof fragmentRef === 'object') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'readInlineData(): Expected an object, got `%s`.', typeof fragmentRef) : invariant(false) : void 0;\n var inlineData = (_fragmentRef$FRAGMENT = fragmentRef[FRAGMENTS_KEY]) === null || _fragmentRef$FRAGMENT === void 0 ? void 0 : _fragmentRef$FRAGMENT[inlineDataFragment.name];\n !(inlineData != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'readInlineData(): Expected fragment `%s` to be spread in the parent ' + 'fragment.', inlineDataFragment.name) : invariant(false) : void 0;\n return inlineData;\n}\nmodule.exports = readInlineData;","'use strict';\n\nvar RelayDeclarativeMutationConfig = require('../mutations/RelayDeclarativeMutationConfig');\nvar _require = require('../query/GraphQLTag'),\n getRequest = _require.getRequest;\nvar _require2 = require('../store/RelayModernOperationDescriptor'),\n createOperationDescriptor = _require2.createOperationDescriptor;\nvar _require3 = require('../store/RelayModernSelector'),\n createReaderSelector = _require3.createReaderSelector;\nvar warning = require(\"fbjs/lib/warning\");\nfunction requestSubscription(environment, config) {\n var subscription = getRequest(config.subscription);\n if (subscription.params.operationKind !== 'subscription') {\n throw new Error('requestSubscription: Must use Subscription operation');\n }\n var configs = config.configs,\n onCompleted = config.onCompleted,\n onError = config.onError,\n onNext = config.onNext,\n variables = config.variables,\n cacheConfig = config.cacheConfig;\n var operation = createOperationDescriptor(subscription, variables, cacheConfig);\n process.env.NODE_ENV !== \"production\" ? warning(!(config.updater && configs), 'requestSubscription: Expected only one of `updater` and `configs` to be provided') : void 0;\n var _ref = configs ? RelayDeclarativeMutationConfig.convert(configs, subscription, null, config.updater) : config,\n updater = _ref.updater;\n var sub = environment.executeSubscription({\n operation: operation,\n updater: updater\n }).subscribe({\n next: function next(responses) {\n if (onNext != null) {\n var selector = operation.fragment;\n var nextID;\n if (Array.isArray(responses)) {\n var _responses$, _responses$$extension;\n nextID = (_responses$ = responses[0]) === null || _responses$ === void 0 ? void 0 : (_responses$$extension = _responses$.extensions) === null || _responses$$extension === void 0 ? void 0 : _responses$$extension.__relay_subscription_root_id;\n } else {\n var _responses$extensions;\n nextID = (_responses$extensions = responses.extensions) === null || _responses$extensions === void 0 ? void 0 : _responses$extensions.__relay_subscription_root_id;\n }\n if (typeof nextID === 'string') {\n selector = createReaderSelector(selector.node, nextID, selector.variables, selector.owner);\n }\n var data = environment.lookup(selector).data;\n onNext(data);\n }\n },\n error: onError,\n complete: onCompleted\n });\n return {\n dispose: sub.unsubscribe\n };\n}\nmodule.exports = requestSubscription;","'use strict';\n\nvar RelayConcreteNode = {\n ACTOR_CHANGE: 'ActorChange',\n CONDITION: 'Condition',\n CLIENT_COMPONENT: 'ClientComponent',\n CLIENT_EDGE_TO_SERVER_OBJECT: 'ClientEdgeToServerObject',\n CLIENT_EDGE_TO_CLIENT_OBJECT: 'ClientEdgeToClientObject',\n CLIENT_EXTENSION: 'ClientExtension',\n DEFER: 'Defer',\n CONNECTION: 'Connection',\n FRAGMENT: 'Fragment',\n FRAGMENT_SPREAD: 'FragmentSpread',\n INLINE_DATA_FRAGMENT_SPREAD: 'InlineDataFragmentSpread',\n INLINE_DATA_FRAGMENT: 'InlineDataFragment',\n INLINE_FRAGMENT: 'InlineFragment',\n LINKED_FIELD: 'LinkedField',\n LINKED_HANDLE: 'LinkedHandle',\n LITERAL: 'Literal',\n LIST_VALUE: 'ListValue',\n LOCAL_ARGUMENT: 'LocalArgument',\n MODULE_IMPORT: 'ModuleImport',\n ALIASED_FRAGMENT_SPREAD: 'AliasedFragmentSpread',\n ALIASED_INLINE_FRAGMENT_SPREAD: 'AliasedInlineFragmentSpread',\n RELAY_RESOLVER: 'RelayResolver',\n RELAY_LIVE_RESOLVER: 'RelayLiveResolver',\n REQUIRED_FIELD: 'RequiredField',\n OBJECT_VALUE: 'ObjectValue',\n OPERATION: 'Operation',\n REQUEST: 'Request',\n ROOT_ARGUMENT: 'RootArgument',\n SCALAR_FIELD: 'ScalarField',\n SCALAR_HANDLE: 'ScalarHandle',\n SPLIT_OPERATION: 'SplitOperation',\n STREAM: 'Stream',\n TYPE_DISCRIMINATOR: 'TypeDiscriminator',\n UPDATABLE_QUERY: 'UpdatableQuery',\n VARIABLE: 'Variable'\n};\nmodule.exports = RelayConcreteNode;","'use strict';\n\nmodule.exports = {\n DEFAULT_HANDLE_KEY: ''\n};","'use strict';\n\nfunction createError(type, name, messageFormat) {\n for (var _len = arguments.length, messageParams = new Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {\n messageParams[_key - 3] = arguments[_key];\n }\n var index = 0;\n var message = messageFormat.replace(/%s/g, function () {\n return String(messageParams[index++]);\n });\n var err = new Error(message);\n var error = Object.assign(err, {\n name: name,\n messageFormat: messageFormat,\n messageParams: messageParams,\n type: type,\n taalOpcodes: [2, 2]\n });\n if (error.stack === undefined) {\n try {\n throw error;\n } catch (_unused) {}\n }\n return error;\n}\nmodule.exports = {\n create: function create(name, messageFormat) {\n for (var _len2 = arguments.length, messageParams = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {\n messageParams[_key2 - 2] = arguments[_key2];\n }\n return createError.apply(void 0, ['error', name, messageFormat].concat(messageParams));\n },\n createWarning: function createWarning(name, messageFormat) {\n for (var _len3 = arguments.length, messageParams = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {\n messageParams[_key3 - 2] = arguments[_key3];\n }\n return createError.apply(void 0, ['warn', name, messageFormat].concat(messageParams));\n }\n};","'use strict';\n\nvar RelayFeatureFlags = {\n ENABLE_CLIENT_EDGES: false,\n ENABLE_VARIABLE_CONNECTION_KEY: false,\n ENABLE_RELAY_RESOLVERS: false,\n ENABLE_GETFRAGMENTIDENTIFIER_OPTIMIZATION: false,\n ENABLE_FRIENDLY_QUERY_NAME_GQL_URL: false,\n ENABLE_LOAD_QUERY_REQUEST_DEDUPING: true,\n ENABLE_DO_NOT_WRAP_LIVE_QUERY: false,\n ENABLE_NOTIFY_SUBSCRIPTION: false,\n BATCH_ASYNC_MODULE_UPDATES_FN: null,\n ENABLE_CONTAINERS_SUBSCRIBE_ON_COMMIT: false,\n MAX_DATA_ID_LENGTH: null,\n STRING_INTERN_LEVEL: 0,\n LOG_MISSING_RECORDS_IN_PROD: false,\n ENABLE_LOOSE_SUBSCRIPTION_ATTRIBUTION: false,\n ENABLE_OPERATION_TRACKER_OPTIMISTIC_UPDATES: false,\n ENABLE_RELAY_OPERATION_TRACKER_SUSPENSE: false,\n ENABLE_FIELD_ERROR_HANDLING: false,\n ENABLE_FIELD_ERROR_HANDLING_THROW_BY_DEFAULT: false,\n ENABLE_FIELD_ERROR_HANDLING_CATCH_DIRECTIVE: false,\n ENABLE_SHALLOW_FREEZE_RESOLVER_VALUES: true,\n ENABLE_STRICT_EQUAL_SELECTORS: false\n};\nmodule.exports = RelayFeatureFlags;","'use strict';\n\nvar profileHandlersByName = {};\nvar defaultProfiler = {\n stop: function stop() {}\n};\nvar RelayProfiler = {\n profile: function profile(name, state) {\n var handlers = profileHandlersByName[name];\n if (handlers && handlers.length > 0) {\n var stopHandlers = [];\n for (var ii = handlers.length - 1; ii >= 0; ii--) {\n var stopHandler = handlers[ii](name, state);\n stopHandlers.unshift(stopHandler);\n }\n return {\n stop: function stop(error) {\n stopHandlers.forEach(function (stopHandler) {\n return stopHandler(error);\n });\n }\n };\n }\n return defaultProfiler;\n },\n attachProfileHandler: function attachProfileHandler(name, handler) {\n if (!profileHandlersByName.hasOwnProperty(name)) {\n profileHandlersByName[name] = [];\n }\n profileHandlersByName[name].push(handler);\n },\n detachProfileHandler: function detachProfileHandler(name, handler) {\n if (profileHandlersByName.hasOwnProperty(name)) {\n removeFromArray(profileHandlersByName[name], handler);\n }\n }\n};\nfunction removeFromArray(array, element) {\n var index = array.indexOf(element);\n if (index !== -1) {\n array.splice(index, 1);\n }\n}\nmodule.exports = RelayProfiler;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _createForOfIteratorHelper2 = _interopRequireDefault(require(\"@babel/runtime/helpers/createForOfIteratorHelper\"));\nvar _defineProperty2 = _interopRequireDefault(require(\"@babel/runtime/helpers/defineProperty\"));\nvar RelayObservable = require('../network/RelayObservable');\nvar invariant = require('invariant');\nvar RelayReplaySubject = /*#__PURE__*/function () {\n function RelayReplaySubject() {\n var _this = this;\n (0, _defineProperty2[\"default\"])(this, \"_complete\", false);\n (0, _defineProperty2[\"default\"])(this, \"_events\", []);\n (0, _defineProperty2[\"default\"])(this, \"_sinks\", new Set());\n (0, _defineProperty2[\"default\"])(this, \"_subscription\", []);\n this._observable = RelayObservable.create(function (sink) {\n _this._sinks.add(sink);\n var events = _this._events;\n for (var i = 0; i < events.length; i++) {\n if (sink.closed) {\n break;\n }\n var event = events[i];\n switch (event.kind) {\n case 'complete':\n sink.complete();\n break;\n case 'error':\n sink.error(event.error);\n break;\n case 'next':\n sink.next(event.data);\n break;\n default:\n event.kind;\n !false ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayReplaySubject: Unknown event kind `%s`.', event.kind) : invariant(false) : void 0;\n }\n }\n return function () {\n _this._sinks[\"delete\"](sink);\n };\n });\n }\n var _proto = RelayReplaySubject.prototype;\n _proto.complete = function complete() {\n if (this._complete === true) {\n return;\n }\n this._complete = true;\n this._events.push({\n kind: 'complete'\n });\n this._sinks.forEach(function (sink) {\n return sink.complete();\n });\n };\n _proto.error = function error(_error) {\n if (this._complete === true) {\n return;\n }\n this._complete = true;\n this._events.push({\n kind: 'error',\n error: _error\n });\n this._sinks.forEach(function (sink) {\n return sink.error(_error);\n });\n };\n _proto.next = function next(data) {\n if (this._complete === true) {\n return;\n }\n this._events.push({\n kind: 'next',\n data: data\n });\n this._sinks.forEach(function (sink) {\n return sink.next(data);\n });\n };\n _proto.subscribe = function subscribe(observer) {\n var subscription = this._observable.subscribe(observer);\n this._subscription.push(subscription);\n return subscription;\n };\n _proto.unsubscribe = function unsubscribe() {\n var _iterator = (0, _createForOfIteratorHelper2[\"default\"])(this._subscription),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var subscription = _step.value;\n subscription.unsubscribe();\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n this._subscription = [];\n };\n _proto.getObserverCount = function getObserverCount() {\n return this._sinks.size;\n };\n return RelayReplaySubject;\n}();\nmodule.exports = RelayReplaySubject;","'use strict';\n\nvar internTable = new Map();\nvar nextIndex = 1;\nvar digits = initDigitTable();\nvar INTERN_PREFIX = '\\t';\nvar ESCAPE_PREFIX = '\\v';\nfunction initDigitTable() {\n var digits = new Set();\n for (var i = 0; i < 10; ++i) {\n digits.add(i.toString());\n }\n return digits;\n}\nfunction escape(str) {\n if (str[0] === INTERN_PREFIX && digits.has(str[1]) || str[0] === ESCAPE_PREFIX) {\n return ESCAPE_PREFIX + str;\n }\n return str;\n}\nfunction intern(str, limit) {\n if (limit == null || str.length < limit) {\n return escape(str);\n }\n var internedString = internTable.get(str);\n if (internedString != null) {\n return internedString;\n }\n internedString = INTERN_PREFIX + nextIndex++;\n internTable.set(str, internedString);\n return internedString;\n}\nmodule.exports = {\n intern: intern\n};","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _objectSpread2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar _require = require('../store/RelayStoreUtils'),\n getModuleComponentKey = _require.getModuleComponentKey,\n getModuleOperationKey = _require.getModuleOperationKey;\nfunction createPayloadFor3DField(name, operation, component, response) {\n var data = (0, _objectSpread2[\"default\"])({}, response);\n data[getModuleComponentKey(name)] = component;\n data[getModuleOperationKey(name)] = operation;\n return data;\n}\nmodule.exports = createPayloadFor3DField;","'use strict';\n\nfunction deepFreeze(object) {\n if (!shouldBeFrozen(object)) {\n return object;\n }\n Object.freeze(object);\n Object.getOwnPropertyNames(object).forEach(function (name) {\n var property = object[name];\n if (property && typeof property === 'object' && !Object.isFrozen(property)) {\n deepFreeze(property);\n }\n });\n return object;\n}\nfunction shouldBeFrozen(value) {\n return value != null && (Array.isArray(value) || typeof value === 'object' && value.constructor === Object);\n}\nmodule.exports = deepFreeze;","'use strict';\n\nvar id = 100000;\nfunction generateID() {\n return id++;\n}\nmodule.exports = generateID;","'use strict';\n\nvar _require = require('../store/RelayModernSelector'),\n getDataIDsFromFragment = _require.getDataIDsFromFragment,\n getSelector = _require.getSelector,\n getVariablesFromFragment = _require.getVariablesFromFragment;\nvar isEmptyObject = require('./isEmptyObject');\nvar RelayFeatureFlags = require('./RelayFeatureFlags');\nvar stableCopy = require('./stableCopy');\nvar _require2 = require('./StringInterner'),\n intern = _require2.intern;\nfunction getFragmentIdentifier(fragmentNode, fragmentRef) {\n var selector = getSelector(fragmentNode, fragmentRef);\n var fragmentOwnerIdentifier = selector == null ? 'null' : selector.kind === 'SingularReaderSelector' ? selector.owner.identifier : '[' + selector.selectors.map(function (sel) {\n return sel.owner.identifier;\n }).join(',') + ']';\n var fragmentVariables = getVariablesFromFragment(fragmentNode, fragmentRef);\n var dataIDs = getDataIDsFromFragment(fragmentNode, fragmentRef);\n if (RelayFeatureFlags.ENABLE_GETFRAGMENTIDENTIFIER_OPTIMIZATION) {\n var ids = typeof dataIDs === 'undefined' ? 'missing' : dataIDs == null ? 'null' : Array.isArray(dataIDs) ? '[' + dataIDs.join(',') + ']' : dataIDs;\n ids = RelayFeatureFlags.STRING_INTERN_LEVEL <= 1 ? ids : intern(ids, RelayFeatureFlags.MAX_DATA_ID_LENGTH);\n return fragmentOwnerIdentifier + '/' + fragmentNode.name + '/' + (fragmentVariables == null || isEmptyObject(fragmentVariables) ? '{}' : JSON.stringify(stableCopy(fragmentVariables))) + '/' + ids;\n } else {\n var _JSON$stringify;\n var _ids = (_JSON$stringify = JSON.stringify(dataIDs)) !== null && _JSON$stringify !== void 0 ? _JSON$stringify : 'missing';\n _ids = RelayFeatureFlags.STRING_INTERN_LEVEL <= 1 ? _ids : intern(_ids, RelayFeatureFlags.MAX_DATA_ID_LENGTH);\n return fragmentOwnerIdentifier + '/' + fragmentNode.name + '/' + JSON.stringify(stableCopy(fragmentVariables)) + '/' + _ids;\n }\n}\nmodule.exports = getFragmentIdentifier;","'use strict';\n\nvar _require = require('./RelayConcreteNode'),\n REQUEST = _require.REQUEST,\n SPLIT_OPERATION = _require.SPLIT_OPERATION;\nfunction getOperation(node) {\n switch (node.kind) {\n case REQUEST:\n return node.operation;\n case SPLIT_OPERATION:\n default:\n return node;\n }\n}\nmodule.exports = getOperation;","'use strict';\n\nvar getRefetchMetadata = require('./getRefetchMetadata');\nvar invariant = require('invariant');\nfunction getPaginationMetadata(fragmentNode, componentDisplayName) {\n var _fragmentNode$metadat, _fragmentNode$metadat2;\n var _getRefetchMetadata = getRefetchMetadata(fragmentNode, componentDisplayName),\n paginationRequest = _getRefetchMetadata.refetchableRequest,\n refetchMetadata = _getRefetchMetadata.refetchMetadata;\n var paginationMetadata = refetchMetadata.connection;\n !(paginationMetadata != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: getPaginationMetadata(): Expected fragment `%s` to include a ' + 'connection when using `%s`. Did you forget to add a @connection ' + 'directive to the connection field in the fragment?', componentDisplayName, fragmentNode.name) : invariant(false) : void 0;\n var connectionPathInFragmentData = paginationMetadata.path;\n var connectionMetadata = ((_fragmentNode$metadat = (_fragmentNode$metadat2 = fragmentNode.metadata) === null || _fragmentNode$metadat2 === void 0 ? void 0 : _fragmentNode$metadat2.connection) !== null && _fragmentNode$metadat !== void 0 ? _fragmentNode$metadat : [])[0];\n !(connectionMetadata != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: getPaginationMetadata(): Expected fragment `%s` to include a ' + 'connection when using `%s`. Did you forget to add a @connection ' + 'directive to the connection field in the fragment?', componentDisplayName, fragmentNode.name) : invariant(false) : void 0;\n var identifierInfo = refetchMetadata.identifierInfo;\n !((identifierInfo === null || identifierInfo === void 0 ? void 0 : identifierInfo.identifierField) == null || typeof identifierInfo.identifierField === 'string') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: getRefetchMetadata(): Expected `identifierField` to be a string.') : invariant(false) : void 0;\n return {\n connectionPathInFragmentData: connectionPathInFragmentData,\n identifierField: identifierInfo === null || identifierInfo === void 0 ? void 0 : identifierInfo.identifierField,\n paginationRequest: paginationRequest,\n paginationMetadata: paginationMetadata,\n stream: connectionMetadata.stream === true\n };\n}\nmodule.exports = getPaginationMetadata;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _defineProperty2 = _interopRequireDefault(require(\"@babel/runtime/helpers/defineProperty\"));\nvar _objectSpread4 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectSpread2\"));\nvar invariant = require('invariant');\nvar warning = require(\"fbjs/lib/warning\");\nfunction getPaginationVariables(direction, count, cursor, baseVariables, extraVariables, paginationMetadata) {\n var _objectSpread3;\n var backwardMetadata = paginationMetadata.backward,\n forwardMetadata = paginationMetadata.forward;\n if (direction === 'backward') {\n var _objectSpread2;\n !(backwardMetadata != null && backwardMetadata.count != null && backwardMetadata.cursor != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: Expected backward pagination metadata to be available. ' + \"If you're seeing this, this is likely a bug in Relay.\") : invariant(false) : void 0;\n process.env.NODE_ENV !== \"production\" ? warning(!extraVariables.hasOwnProperty(backwardMetadata.cursor), 'Relay: `UNSTABLE_extraVariables` provided by caller should not ' + 'contain cursor variable `%s`. This variable is automatically ' + 'determined by Relay.', backwardMetadata.cursor) : void 0;\n process.env.NODE_ENV !== \"production\" ? warning(!extraVariables.hasOwnProperty(backwardMetadata.count), 'Relay: `UNSTABLE_extraVariables` provided by caller should not ' + 'contain count variable `%s`. This variable is automatically ' + 'determined by Relay.', backwardMetadata.count) : void 0;\n var _paginationVariables = (0, _objectSpread4[\"default\"])((0, _objectSpread4[\"default\"])((0, _objectSpread4[\"default\"])({}, baseVariables), extraVariables), {}, (_objectSpread2 = {}, (0, _defineProperty2[\"default\"])(_objectSpread2, backwardMetadata.cursor, cursor), (0, _defineProperty2[\"default\"])(_objectSpread2, backwardMetadata.count, count), _objectSpread2));\n if (forwardMetadata && forwardMetadata.cursor) {\n _paginationVariables[forwardMetadata.cursor] = null;\n }\n if (forwardMetadata && forwardMetadata.count) {\n _paginationVariables[forwardMetadata.count] = null;\n }\n return _paginationVariables;\n }\n !(forwardMetadata != null && forwardMetadata.count != null && forwardMetadata.cursor != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: Expected forward pagination metadata to be available. ' + \"If you're seeing this, this is likely a bug in Relay.\") : invariant(false) : void 0;\n process.env.NODE_ENV !== \"production\" ? warning(!extraVariables.hasOwnProperty(forwardMetadata.cursor), 'Relay: `UNSTABLE_extraVariables` provided by caller should not ' + 'contain cursor variable `%s`. This variable is automatically ' + 'determined by Relay.', forwardMetadata.cursor) : void 0;\n process.env.NODE_ENV !== \"production\" ? warning(!extraVariables.hasOwnProperty(forwardMetadata.count), 'Relay: `UNSTABLE_extraVariables` provided by caller should not ' + 'contain count variable `%s`. This variable is automatically ' + 'determined by Relay.', forwardMetadata.count) : void 0;\n var paginationVariables = (0, _objectSpread4[\"default\"])((0, _objectSpread4[\"default\"])((0, _objectSpread4[\"default\"])({}, baseVariables), extraVariables), {}, (_objectSpread3 = {}, (0, _defineProperty2[\"default\"])(_objectSpread3, forwardMetadata.cursor, cursor), (0, _defineProperty2[\"default\"])(_objectSpread3, forwardMetadata.count, count), _objectSpread3));\n if (backwardMetadata && backwardMetadata.cursor) {\n paginationVariables[backwardMetadata.cursor] = null;\n }\n if (backwardMetadata && backwardMetadata.count) {\n paginationVariables[backwardMetadata.count] = null;\n }\n return paginationVariables;\n}\nmodule.exports = getPaginationVariables;","'use strict';\n\nvar _require = require('../query/fetchQueryInternal'),\n getPromiseForActiveRequest = _require.getPromiseForActiveRequest;\nfunction getPendingOperationsForFragment(environment, fragmentNode, fragmentOwner) {\n var _pendingOperations$ma, _pendingOperations;\n var pendingOperations = [];\n var promise = getPromiseForActiveRequest(environment, fragmentOwner);\n if (promise != null) {\n pendingOperations = [fragmentOwner];\n } else {\n var _result$pendingOperat, _result$promise;\n var result = environment.getOperationTracker().getPendingOperationsAffectingOwner(fragmentOwner);\n pendingOperations = (_result$pendingOperat = result === null || result === void 0 ? void 0 : result.pendingOperations) !== null && _result$pendingOperat !== void 0 ? _result$pendingOperat : [];\n promise = (_result$promise = result === null || result === void 0 ? void 0 : result.promise) !== null && _result$promise !== void 0 ? _result$promise : null;\n }\n if (!promise) {\n return null;\n }\n var pendingOperationName = (_pendingOperations$ma = (_pendingOperations = pendingOperations) === null || _pendingOperations === void 0 ? void 0 : _pendingOperations.map(function (op) {\n return op.node.params.name;\n }).join(',')) !== null && _pendingOperations$ma !== void 0 ? _pendingOperations$ma : null;\n if (pendingOperationName == null || pendingOperationName.length === 0) {\n pendingOperationName = 'Unknown pending operation';\n }\n var fragmentName = fragmentNode.name;\n var promiseDisplayName = pendingOperationName === fragmentName ? \"Relay(\".concat(pendingOperationName, \")\") : \"Relay(\".concat(pendingOperationName, \":\").concat(fragmentName, \")\");\n promise.displayName = promiseDisplayName;\n environment.__log({\n name: 'pendingoperation.found',\n fragment: fragmentNode,\n fragmentOwner: fragmentOwner,\n pendingOperations: pendingOperations\n });\n return {\n promise: promise,\n pendingOperations: pendingOperations\n };\n}\nmodule.exports = getPendingOperationsForFragment;","'use strict';\n\nvar invariant = require('invariant');\nfunction getRefetchMetadata(fragmentNode, componentDisplayName) {\n var _fragmentNode$metadat, _fragmentNode$metadat2;\n !(((_fragmentNode$metadat = fragmentNode.metadata) === null || _fragmentNode$metadat === void 0 ? void 0 : _fragmentNode$metadat.plural) !== true) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: getRefetchMetadata(): Expected fragment `%s` not to be plural when using ' + '`%s`. Remove `@relay(plural: true)` from fragment `%s` ' + 'in order to use it with `%s`.', fragmentNode.name, componentDisplayName, fragmentNode.name, componentDisplayName) : invariant(false) : void 0;\n var refetchMetadata = (_fragmentNode$metadat2 = fragmentNode.metadata) === null || _fragmentNode$metadat2 === void 0 ? void 0 : _fragmentNode$metadat2.refetch;\n !(refetchMetadata != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: getRefetchMetadata(): Expected fragment `%s` to be refetchable when using `%s`. ' + 'Did you forget to add a @refetchable directive to the fragment?', componentDisplayName, fragmentNode.name) : invariant(false) : void 0;\n var refetchableRequest = refetchMetadata.operation[\"default\"] ? refetchMetadata.operation[\"default\"] : refetchMetadata.operation;\n var fragmentRefPathInResponse = refetchMetadata.fragmentPathInResult;\n !(typeof refetchableRequest !== 'string') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: getRefetchMetadata(): Expected refetch query to be an ' + \"operation and not a string when using `%s`. If you're seeing this, \" + 'this is likely a bug in Relay.', componentDisplayName) : invariant(false) : void 0;\n var identifierInfo = refetchMetadata.identifierInfo;\n if (identifierInfo != null) {\n !(identifierInfo.identifierField == null || typeof identifierInfo.identifierField === 'string') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: getRefetchMetadata(): Expected `identifierField` to be a string.') : invariant(false) : void 0;\n !(identifierInfo.identifierQueryVariableName == null || typeof identifierInfo.identifierQueryVariableName === 'string') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: getRefetchMetadata(): Expected `identifierQueryVariableName` to be a string.') : invariant(false) : void 0;\n }\n return {\n fragmentRefPathInResponse: fragmentRefPathInResponse,\n identifierInfo: identifierInfo,\n refetchableRequest: refetchableRequest,\n refetchMetadata: refetchMetadata\n };\n}\nmodule.exports = getRefetchMetadata;","'use strict';\n\nvar _require = require('./RelayDefaultHandleKey'),\n DEFAULT_HANDLE_KEY = _require.DEFAULT_HANDLE_KEY;\nvar invariant = require('invariant');\nfunction getRelayHandleKey(handleName, key, fieldName) {\n if (key && key !== DEFAULT_HANDLE_KEY) {\n return \"__\".concat(key, \"_\").concat(handleName);\n }\n !(fieldName != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'getRelayHandleKey: Expected either `fieldName` or `key` in `handle` to be provided') : invariant(false) : void 0;\n return \"__\".concat(fieldName, \"_\").concat(handleName);\n}\nmodule.exports = getRelayHandleKey;","'use strict';\n\nvar stableCopy = require('./stableCopy');\nvar invariant = require('invariant');\nfunction getRequestIdentifier(parameters, variables) {\n var requestID = parameters.cacheID != null ? parameters.cacheID : parameters.id;\n !(requestID != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'getRequestIdentifier: Expected request `%s` to have either a ' + 'valid `id` or `cacheID` property', parameters.name) : invariant(false) : void 0;\n return requestID + JSON.stringify(stableCopy(variables));\n}\nmodule.exports = getRequestIdentifier;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _createForOfIteratorHelper2 = _interopRequireDefault(require(\"@babel/runtime/helpers/createForOfIteratorHelper\"));\nvar invariant = require('invariant');\nfunction getValueAtPath(data, path) {\n var result = data;\n var _iterator = (0, _createForOfIteratorHelper2[\"default\"])(path),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var key = _step.value;\n if (result == null) {\n return null;\n }\n if (typeof key === 'number') {\n !Array.isArray(result) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: Expected an array when extracting value at path. ' + \"If you're seeing this, this is likely a bug in Relay.\") : invariant(false) : void 0;\n result = result[key];\n } else {\n !(typeof result === 'object' && !Array.isArray(result)) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Relay: Expected an object when extracting value at path. ' + \"If you're seeing this, this is likely a bug in Relay.\") : invariant(false) : void 0;\n result = result[key];\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n return result;\n}\nmodule.exports = getValueAtPath;","'use strict';\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\")[\"default\"];\nvar _createForOfIteratorHelper2 = _interopRequireDefault(require(\"@babel/runtime/helpers/createForOfIteratorHelper\"));\nvar _RelayErrorTrie = require(\"../store/RelayErrorTrie\");\nvar _RelayFeatureFlags = _interopRequireDefault(require(\"./RelayFeatureFlags\"));\nfunction handlePotentialSnapshotErrors(environment, missingRequiredFields, relayResolverErrors, errorResponseFields) {\n var _iterator = (0, _createForOfIteratorHelper2[\"default\"])(relayResolverErrors),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var resolverError = _step.value;\n environment.relayFieldLogger({\n kind: 'relay_resolver.error',\n owner: resolverError.field.owner,\n fieldPath: resolverError.field.path,\n error: resolverError.error\n });\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n if (_RelayFeatureFlags[\"default\"].ENABLE_FIELD_ERROR_HANDLING && errorResponseFields != null) {\n if (errorResponseFields != null) {\n var _iterator2 = (0, _createForOfIteratorHelper2[\"default\"])(errorResponseFields),\n _step2;\n try {\n for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n var fieldError = _step2.value;\n var path = fieldError.path,\n owner = fieldError.owner,\n error = fieldError.error;\n environment.relayFieldLogger({\n kind: 'relay_field_payload.error',\n owner: owner,\n fieldPath: path,\n error: error\n });\n }\n } catch (err) {\n _iterator2.e(err);\n } finally {\n _iterator2.f();\n }\n }\n if (_RelayFeatureFlags[\"default\"].ENABLE_FIELD_ERROR_HANDLING_THROW_BY_DEFAULT) {\n throw new _RelayErrorTrie.RelayFieldError(\"Relay: Unexpected response payload - this object includes an errors property in which you can access the underlying errors\", errorResponseFields.map(function (_ref) {\n var path = _ref.path,\n owner = _ref.owner,\n error = _ref.error;\n return error;\n }));\n }\n }\n if (missingRequiredFields != null) {\n switch (missingRequiredFields.action) {\n case 'THROW':\n {\n var _missingRequiredField = missingRequiredFields.field,\n _path = _missingRequiredField.path,\n _owner = _missingRequiredField.owner;\n environment.relayFieldLogger({\n kind: 'missing_field.throw',\n owner: _owner,\n fieldPath: _path\n });\n throw new Error(\"Relay: Missing @required value at path '\".concat(_path, \"' in '\").concat(_owner, \"'.\"));\n }\n case 'LOG':\n missingRequiredFields.fields.forEach(function (_ref2) {\n var path = _ref2.path,\n owner = _ref2.owner;\n environment.relayFieldLogger({\n kind: 'missing_field.log',\n owner: owner,\n fieldPath: path\n });\n });\n break;\n default:\n {\n missingRequiredFields.action;\n }\n }\n }\n}\nmodule.exports = handlePotentialSnapshotErrors;","'use strict';\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nfunction isEmptyObject(obj) {\n for (var _key in obj) {\n if (hasOwnProperty.call(obj, _key)) {\n return false;\n }\n }\n return true;\n}\nmodule.exports = isEmptyObject;","'use strict';\n\nfunction isPromise(p) {\n return !!p && typeof p.then === 'function';\n}\nmodule.exports = isPromise;","'use strict';\n\nfunction isScalarAndEqual(valueA, valueB) {\n return valueA === valueB && (valueA === null || typeof valueA !== 'object');\n}\nmodule.exports = isScalarAndEqual;","'use strict';\n\nfunction recycleNodesInto(prevData, nextData) {\n return recycleNodesIntoImpl(prevData, nextData, true);\n}\nfunction recycleNodesIntoImpl(prevData, nextData, canMutate) {\n if (prevData === nextData || typeof prevData !== 'object' || !prevData || prevData.constructor !== Object && !Array.isArray(prevData) || typeof nextData !== 'object' || !nextData || nextData.constructor !== Object && !Array.isArray(nextData)) {\n return nextData;\n }\n var canRecycle = false;\n var prevArray = Array.isArray(prevData) ? prevData : null;\n var nextArray = Array.isArray(nextData) ? nextData : null;\n if (prevArray && nextArray) {\n var canMutateNext = canMutate && !Object.isFrozen(nextArray);\n canRecycle = nextArray.reduce(function (wasEqual, nextItem, ii) {\n var prevValue = prevArray[ii];\n var nextValue = recycleNodesIntoImpl(prevValue, nextItem, canMutateNext);\n if (nextValue !== nextArray[ii] && canMutateNext) {\n nextArray[ii] = nextValue;\n }\n return wasEqual && nextValue === prevArray[ii];\n }, true) && prevArray.length === nextArray.length;\n } else if (!prevArray && !nextArray) {\n var prevObject = prevData;\n var nextObject = nextData;\n var prevKeys = Object.keys(prevObject);\n var nextKeys = Object.keys(nextObject);\n var _canMutateNext = canMutate && !Object.isFrozen(nextObject);\n canRecycle = nextKeys.reduce(function (wasEqual, key) {\n var prevValue = prevObject[key];\n var nextValue = recycleNodesIntoImpl(prevValue, nextObject[key], _canMutateNext);\n if (nextValue !== nextObject[key] && _canMutateNext) {\n nextObject[key] = nextValue;\n }\n return wasEqual && nextValue === prevObject[key];\n }, true) && prevKeys.length === nextKeys.length;\n }\n return canRecycle ? prevData : nextData;\n}\nmodule.exports = recycleNodesInto;","'use strict';\n\nfunction registerEnvironmentWithDevTools(environment) {\n var _global = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : undefined;\n var devToolsHook = _global && _global.__RELAY_DEVTOOLS_HOOK__;\n if (devToolsHook) {\n devToolsHook.registerEnvironment(environment);\n }\n}\nmodule.exports = registerEnvironmentWithDevTools;","'use strict';\n\nvar resolvedPromise = Promise.resolve();\nfunction resolveImmediate(callback) {\n resolvedPromise.then(callback)[\"catch\"](throwNext);\n}\nfunction throwNext(error) {\n setTimeout(function () {\n throw error;\n }, 0);\n}\nmodule.exports = resolveImmediate;","'use strict';\n\nmodule.exports = function shallowFreeze(value) {\n if (typeof value === 'object' && value != null && (Array.isArray(value) || value.constructor === Object)) {\n Object.freeze(value);\n }\n};","'use strict';\n\nfunction stableCopy(value) {\n if (!value || typeof value !== 'object') {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(stableCopy);\n }\n var keys = Object.keys(value).sort();\n var stable = {};\n for (var i = 0; i < keys.length; i++) {\n stable[keys[i]] = stableCopy(value[keys[i]]);\n }\n return stable;\n}\nmodule.exports = stableCopy;","'use strict';\n\nvar _window, _window$performance;\nvar isPerformanceNowAvailable = typeof window !== 'undefined' && typeof ((_window = window) === null || _window === void 0 ? void 0 : (_window$performance = _window.performance) === null || _window$performance === void 0 ? void 0 : _window$performance.now) === 'function';\nfunction currentTimestamp() {\n if (isPerformanceNowAvailable) {\n return window.performance.now();\n }\n return Date.now();\n}\nfunction withDuration(cb) {\n var startTime = currentTimestamp();\n var result = cb();\n return [currentTimestamp() - startTime, result];\n}\nmodule.exports = withDuration;","'use strict';\n\nvar areEqual = require(\"fbjs/lib/areEqual\");\nvar warning = require(\"fbjs/lib/warning\");\nvar WEAKMAP_SUPPORTED = typeof WeakMap === 'function';\nvar debugCache = WEAKMAP_SUPPORTED ? new WeakMap() : new Map();\nfunction withProvidedVariables(userSuppliedVariables, providedVariables) {\n if (providedVariables != null) {\n var operationVariables = {};\n Object.assign(operationVariables, userSuppliedVariables);\n Object.keys(providedVariables).forEach(function (varName) {\n var providerFunction = providedVariables[varName].get;\n var providerResult = providerFunction();\n if (!debugCache.has(providerFunction)) {\n debugCache.set(providerFunction, providerResult);\n operationVariables[varName] = providerResult;\n } else {\n var cachedResult = debugCache.get(providerFunction);\n if (process.env.NODE_ENV !== \"production\") {\n process.env.NODE_ENV !== \"production\" ? warning(areEqual(providerResult, cachedResult), 'Relay: Expected function `%s` for provider `%s` to be a pure function, ' + 'but got conflicting return values `%s` and `%s`', providerFunction.name, varName, providerResult, cachedResult) : void 0;\n }\n operationVariables[varName] = cachedResult;\n }\n });\n return operationVariables;\n } else {\n return userSuppliedVariables;\n }\n}\nwithProvidedVariables.tests_only_resetDebugCache = process.env.NODE_ENV !== \"production\" ? function () {\n debugCache = WEAKMAP_SUPPORTED ? new WeakMap() : new Map();\n} : undefined;\nmodule.exports = withProvidedVariables;","/*!\n* tabbable 6.2.0\n* @license MIT, https://github.com/focus-trap/tabbable/blob/master/LICENSE\n*/\n// NOTE: separate `:not()` selectors has broader browser support than the newer\n// `:not([inert], [inert] *)` (Feb 2023)\n// CAREFUL: JSDom does not support `:not([inert] *)` as a selector; using it causes\n// the entire query to fail, resulting in no nodes found, which will break a lot\n// of things... so we have to rely on JS to identify nodes inside an inert container\nvar candidateSelectors = ['input:not([inert])', 'select:not([inert])', 'textarea:not([inert])', 'a[href]:not([inert])', 'button:not([inert])', '[tabindex]:not(slot):not([inert])', 'audio[controls]:not([inert])', 'video[controls]:not([inert])', '[contenteditable]:not([contenteditable=\"false\"]):not([inert])', 'details>summary:first-of-type:not([inert])', 'details:not([inert])'];\nvar candidateSelector = /* #__PURE__ */candidateSelectors.join(',');\nvar NoElement = typeof Element === 'undefined';\nvar matches = NoElement ? function () {} : Element.prototype.matches || Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;\nvar getRootNode = !NoElement && Element.prototype.getRootNode ? function (element) {\n var _element$getRootNode;\n return element === null || element === void 0 ? void 0 : (_element$getRootNode = element.getRootNode) === null || _element$getRootNode === void 0 ? void 0 : _element$getRootNode.call(element);\n} : function (element) {\n return element === null || element === void 0 ? void 0 : element.ownerDocument;\n};\n\n/**\n * Determines if a node is inert or in an inert ancestor.\n * @param {Element} [node]\n * @param {boolean} [lookUp] If true and `node` is not inert, looks up at ancestors to\n * see if any of them are inert. If false, only `node` itself is considered.\n * @returns {boolean} True if inert itself or by way of being in an inert ancestor.\n * False if `node` is falsy.\n */\nvar isInert = function isInert(node, lookUp) {\n var _node$getAttribute;\n if (lookUp === void 0) {\n lookUp = true;\n }\n // CAREFUL: JSDom does not support inert at all, so we can't use the `HTMLElement.inert`\n // JS API property; we have to check the attribute, which can either be empty or 'true';\n // if it's `null` (not specified) or 'false', it's an active element\n var inertAtt = node === null || node === void 0 ? void 0 : (_node$getAttribute = node.getAttribute) === null || _node$getAttribute === void 0 ? void 0 : _node$getAttribute.call(node, 'inert');\n var inert = inertAtt === '' || inertAtt === 'true';\n\n // NOTE: this could also be handled with `node.matches('[inert], :is([inert] *)')`\n // if it weren't for `matches()` not being a function on shadow roots; the following\n // code works for any kind of node\n // CAREFUL: JSDom does not appear to support certain selectors like `:not([inert] *)`\n // so it likely would not support `:is([inert] *)` either...\n var result = inert || lookUp && node && isInert(node.parentNode); // recursive\n\n return result;\n};\n\n/**\n * Determines if a node's content is editable.\n * @param {Element} [node]\n * @returns True if it's content-editable; false if it's not or `node` is falsy.\n */\nvar isContentEditable = function isContentEditable(node) {\n var _node$getAttribute2;\n // CAREFUL: JSDom does not support the `HTMLElement.isContentEditable` API so we have\n // to use the attribute directly to check for this, which can either be empty or 'true';\n // if it's `null` (not specified) or 'false', it's a non-editable element\n var attValue = node === null || node === void 0 ? void 0 : (_node$getAttribute2 = node.getAttribute) === null || _node$getAttribute2 === void 0 ? void 0 : _node$getAttribute2.call(node, 'contenteditable');\n return attValue === '' || attValue === 'true';\n};\n\n/**\n * @param {Element} el container to check in\n * @param {boolean} includeContainer add container to check\n * @param {(node: Element) => boolean} filter filter candidates\n * @returns {Element[]}\n */\nvar getCandidates = function getCandidates(el, includeContainer, filter) {\n // even if `includeContainer=false`, we still have to check it for inertness because\n // if it's inert, all its children are inert\n if (isInert(el)) {\n return [];\n }\n var candidates = Array.prototype.slice.apply(el.querySelectorAll(candidateSelector));\n if (includeContainer && matches.call(el, candidateSelector)) {\n candidates.unshift(el);\n }\n candidates = candidates.filter(filter);\n return candidates;\n};\n\n/**\n * @callback GetShadowRoot\n * @param {Element} element to check for shadow root\n * @returns {ShadowRoot|boolean} ShadowRoot if available or boolean indicating if a shadowRoot is attached but not available.\n */\n\n/**\n * @callback ShadowRootFilter\n * @param {Element} shadowHostNode the element which contains shadow content\n * @returns {boolean} true if a shadow root could potentially contain valid candidates.\n */\n\n/**\n * @typedef {Object} CandidateScope\n * @property {Element} scopeParent contains inner candidates\n * @property {Element[]} candidates list of candidates found in the scope parent\n */\n\n/**\n * @typedef {Object} IterativeOptions\n * @property {GetShadowRoot|boolean} getShadowRoot true if shadow support is enabled; falsy if not;\n * if a function, implies shadow support is enabled and either returns the shadow root of an element\n * or a boolean stating if it has an undisclosed shadow root\n * @property {(node: Element) => boolean} filter filter candidates\n * @property {boolean} flatten if true then result will flatten any CandidateScope into the returned list\n * @property {ShadowRootFilter} shadowRootFilter filter shadow roots;\n */\n\n/**\n * @param {Element[]} elements list of element containers to match candidates from\n * @param {boolean} includeContainer add container list to check\n * @param {IterativeOptions} options\n * @returns {Array.}\n */\nvar getCandidatesIteratively = function getCandidatesIteratively(elements, includeContainer, options) {\n var candidates = [];\n var elementsToCheck = Array.from(elements);\n while (elementsToCheck.length) {\n var element = elementsToCheck.shift();\n if (isInert(element, false)) {\n // no need to look up since we're drilling down\n // anything inside this container will also be inert\n continue;\n }\n if (element.tagName === 'SLOT') {\n // add shadow dom slot scope (slot itself cannot be focusable)\n var assigned = element.assignedElements();\n var content = assigned.length ? assigned : element.children;\n var nestedCandidates = getCandidatesIteratively(content, true, options);\n if (options.flatten) {\n candidates.push.apply(candidates, nestedCandidates);\n } else {\n candidates.push({\n scopeParent: element,\n candidates: nestedCandidates\n });\n }\n } else {\n // check candidate element\n var validCandidate = matches.call(element, candidateSelector);\n if (validCandidate && options.filter(element) && (includeContainer || !elements.includes(element))) {\n candidates.push(element);\n }\n\n // iterate over shadow content if possible\n var shadowRoot = element.shadowRoot ||\n // check for an undisclosed shadow\n typeof options.getShadowRoot === 'function' && options.getShadowRoot(element);\n\n // no inert look up because we're already drilling down and checking for inertness\n // on the way down, so all containers to this root node should have already been\n // vetted as non-inert\n var validShadowRoot = !isInert(shadowRoot, false) && (!options.shadowRootFilter || options.shadowRootFilter(element));\n if (shadowRoot && validShadowRoot) {\n // add shadow dom scope IIF a shadow root node was given; otherwise, an undisclosed\n // shadow exists, so look at light dom children as fallback BUT create a scope for any\n // child candidates found because they're likely slotted elements (elements that are\n // children of the web component element (which has the shadow), in the light dom, but\n // slotted somewhere _inside_ the undisclosed shadow) -- the scope is created below,\n // _after_ we return from this recursive call\n var _nestedCandidates = getCandidatesIteratively(shadowRoot === true ? element.children : shadowRoot.children, true, options);\n if (options.flatten) {\n candidates.push.apply(candidates, _nestedCandidates);\n } else {\n candidates.push({\n scopeParent: element,\n candidates: _nestedCandidates\n });\n }\n } else {\n // there's not shadow so just dig into the element's (light dom) children\n // __without__ giving the element special scope treatment\n elementsToCheck.unshift.apply(elementsToCheck, element.children);\n }\n }\n }\n return candidates;\n};\n\n/**\n * @private\n * Determines if the node has an explicitly specified `tabindex` attribute.\n * @param {HTMLElement} node\n * @returns {boolean} True if so; false if not.\n */\nvar hasTabIndex = function hasTabIndex(node) {\n return !isNaN(parseInt(node.getAttribute('tabindex'), 10));\n};\n\n/**\n * Determine the tab index of a given node.\n * @param {HTMLElement} node\n * @returns {number} Tab order (negative, 0, or positive number).\n * @throws {Error} If `node` is falsy.\n */\nvar getTabIndex = function getTabIndex(node) {\n if (!node) {\n throw new Error('No node provided');\n }\n if (node.tabIndex < 0) {\n // in Chrome, , and elements get a default\n // `tabIndex` of -1 when the 'tabindex' attribute isn't specified in the DOM,\n // yet they are still part of the regular tab order; in FF, they get a default\n // `tabIndex` of 0; since Chrome still puts those elements in the regular tab\n // order, consider their tab index to be 0.\n // Also browsers do not return `tabIndex` correctly for contentEditable nodes;\n // so if they don't have a tabindex attribute specifically set, assume it's 0.\n if ((/^(AUDIO|VIDEO|DETAILS)$/.test(node.tagName) || isContentEditable(node)) && !hasTabIndex(node)) {\n return 0;\n }\n }\n return node.tabIndex;\n};\n\n/**\n * Determine the tab index of a given node __for sort order purposes__.\n * @param {HTMLElement} node\n * @param {boolean} [isScope] True for a custom element with shadow root or slot that, by default,\n * has tabIndex -1, but needs to be sorted by document order in order for its content to be\n * inserted into the correct sort position.\n * @returns {number} Tab order (negative, 0, or positive number).\n */\nvar getSortOrderTabIndex = function getSortOrderTabIndex(node, isScope) {\n var tabIndex = getTabIndex(node);\n if (tabIndex < 0 && isScope && !hasTabIndex(node)) {\n return 0;\n }\n return tabIndex;\n};\nvar sortOrderedTabbables = function sortOrderedTabbables(a, b) {\n return a.tabIndex === b.tabIndex ? a.documentOrder - b.documentOrder : a.tabIndex - b.tabIndex;\n};\nvar isInput = function isInput(node) {\n return node.tagName === 'INPUT';\n};\nvar isHiddenInput = function isHiddenInput(node) {\n return isInput(node) && node.type === 'hidden';\n};\nvar isDetailsWithSummary = function isDetailsWithSummary(node) {\n var r = node.tagName === 'DETAILS' && Array.prototype.slice.apply(node.children).some(function (child) {\n return child.tagName === 'SUMMARY';\n });\n return r;\n};\nvar getCheckedRadio = function getCheckedRadio(nodes, form) {\n for (var i = 0; i < nodes.length; i++) {\n if (nodes[i].checked && nodes[i].form === form) {\n return nodes[i];\n }\n }\n};\nvar isTabbableRadio = function isTabbableRadio(node) {\n if (!node.name) {\n return true;\n }\n var radioScope = node.form || getRootNode(node);\n var queryRadios = function queryRadios(name) {\n return radioScope.querySelectorAll('input[type=\"radio\"][name=\"' + name + '\"]');\n };\n var radioSet;\n if (typeof window !== 'undefined' && typeof window.CSS !== 'undefined' && typeof window.CSS.escape === 'function') {\n radioSet = queryRadios(window.CSS.escape(node.name));\n } else {\n try {\n radioSet = queryRadios(node.name);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('Looks like you have a radio button with a name attribute containing invalid CSS selector characters and need the CSS.escape polyfill: %s', err.message);\n return false;\n }\n }\n var checked = getCheckedRadio(radioSet, node.form);\n return !checked || checked === node;\n};\nvar isRadio = function isRadio(node) {\n return isInput(node) && node.type === 'radio';\n};\nvar isNonTabbableRadio = function isNonTabbableRadio(node) {\n return isRadio(node) && !isTabbableRadio(node);\n};\n\n// determines if a node is ultimately attached to the window's document\nvar isNodeAttached = function isNodeAttached(node) {\n var _nodeRoot;\n // The root node is the shadow root if the node is in a shadow DOM; some document otherwise\n // (but NOT _the_ document; see second 'If' comment below for more).\n // If rootNode is shadow root, it'll have a host, which is the element to which the shadow\n // is attached, and the one we need to check if it's in the document or not (because the\n // shadow, and all nodes it contains, is never considered in the document since shadows\n // behave like self-contained DOMs; but if the shadow's HOST, which is part of the document,\n // is hidden, or is not in the document itself but is detached, it will affect the shadow's\n // visibility, including all the nodes it contains). The host could be any normal node,\n // or a custom element (i.e. web component). Either way, that's the one that is considered\n // part of the document, not the shadow root, nor any of its children (i.e. the node being\n // tested).\n // To further complicate things, we have to look all the way up until we find a shadow HOST\n // that is attached (or find none) because the node might be in nested shadows...\n // If rootNode is not a shadow root, it won't have a host, and so rootNode should be the\n // document (per the docs) and while it's a Document-type object, that document does not\n // appear to be the same as the node's `ownerDocument` for some reason, so it's safer\n // to ignore the rootNode at this point, and use `node.ownerDocument`. Otherwise,\n // using `rootNode.contains(node)` will _always_ be true we'll get false-positives when\n // node is actually detached.\n // NOTE: If `nodeRootHost` or `node` happens to be the `document` itself (which is possible\n // if a tabbable/focusable node was quickly added to the DOM, focused, and then removed\n // from the DOM as in https://github.com/focus-trap/focus-trap-react/issues/905), then\n // `ownerDocument` will be `null`, hence the optional chaining on it.\n var nodeRoot = node && getRootNode(node);\n var nodeRootHost = (_nodeRoot = nodeRoot) === null || _nodeRoot === void 0 ? void 0 : _nodeRoot.host;\n\n // in some cases, a detached node will return itself as the root instead of a document or\n // shadow root object, in which case, we shouldn't try to look further up the host chain\n var attached = false;\n if (nodeRoot && nodeRoot !== node) {\n var _nodeRootHost, _nodeRootHost$ownerDo, _node$ownerDocument;\n attached = !!((_nodeRootHost = nodeRootHost) !== null && _nodeRootHost !== void 0 && (_nodeRootHost$ownerDo = _nodeRootHost.ownerDocument) !== null && _nodeRootHost$ownerDo !== void 0 && _nodeRootHost$ownerDo.contains(nodeRootHost) || node !== null && node !== void 0 && (_node$ownerDocument = node.ownerDocument) !== null && _node$ownerDocument !== void 0 && _node$ownerDocument.contains(node));\n while (!attached && nodeRootHost) {\n var _nodeRoot2, _nodeRootHost2, _nodeRootHost2$ownerD;\n // since it's not attached and we have a root host, the node MUST be in a nested shadow DOM,\n // which means we need to get the host's host and check if that parent host is contained\n // in (i.e. attached to) the document\n nodeRoot = getRootNode(nodeRootHost);\n nodeRootHost = (_nodeRoot2 = nodeRoot) === null || _nodeRoot2 === void 0 ? void 0 : _nodeRoot2.host;\n attached = !!((_nodeRootHost2 = nodeRootHost) !== null && _nodeRootHost2 !== void 0 && (_nodeRootHost2$ownerD = _nodeRootHost2.ownerDocument) !== null && _nodeRootHost2$ownerD !== void 0 && _nodeRootHost2$ownerD.contains(nodeRootHost));\n }\n }\n return attached;\n};\nvar isZeroArea = function isZeroArea(node) {\n var _node$getBoundingClie = node.getBoundingClientRect(),\n width = _node$getBoundingClie.width,\n height = _node$getBoundingClie.height;\n return width === 0 && height === 0;\n};\nvar isHidden = function isHidden(node, _ref) {\n var displayCheck = _ref.displayCheck,\n getShadowRoot = _ref.getShadowRoot;\n // NOTE: visibility will be `undefined` if node is detached from the document\n // (see notes about this further down), which means we will consider it visible\n // (this is legacy behavior from a very long way back)\n // NOTE: we check this regardless of `displayCheck=\"none\"` because this is a\n // _visibility_ check, not a _display_ check\n if (getComputedStyle(node).visibility === 'hidden') {\n return true;\n }\n var isDirectSummary = matches.call(node, 'details>summary:first-of-type');\n var nodeUnderDetails = isDirectSummary ? node.parentElement : node;\n if (matches.call(nodeUnderDetails, 'details:not([open]) *')) {\n return true;\n }\n if (!displayCheck || displayCheck === 'full' || displayCheck === 'legacy-full') {\n if (typeof getShadowRoot === 'function') {\n // figure out if we should consider the node to be in an undisclosed shadow and use the\n // 'non-zero-area' fallback\n var originalNode = node;\n while (node) {\n var parentElement = node.parentElement;\n var rootNode = getRootNode(node);\n if (parentElement && !parentElement.shadowRoot && getShadowRoot(parentElement) === true // check if there's an undisclosed shadow\n ) {\n // node has an undisclosed shadow which means we can only treat it as a black box, so we\n // fall back to a non-zero-area test\n return isZeroArea(node);\n } else if (node.assignedSlot) {\n // iterate up slot\n node = node.assignedSlot;\n } else if (!parentElement && rootNode !== node.ownerDocument) {\n // cross shadow boundary\n node = rootNode.host;\n } else {\n // iterate up normal dom\n node = parentElement;\n }\n }\n node = originalNode;\n }\n // else, `getShadowRoot` might be true, but all that does is enable shadow DOM support\n // (i.e. it does not also presume that all nodes might have undisclosed shadows); or\n // it might be a falsy value, which means shadow DOM support is disabled\n\n // Since we didn't find it sitting in an undisclosed shadow (or shadows are disabled)\n // now we can just test to see if it would normally be visible or not, provided it's\n // attached to the main document.\n // NOTE: We must consider case where node is inside a shadow DOM and given directly to\n // `isTabbable()` or `isFocusable()` -- regardless of `getShadowRoot` option setting.\n\n if (isNodeAttached(node)) {\n // this works wherever the node is: if there's at least one client rect, it's\n // somehow displayed; it also covers the CSS 'display: contents' case where the\n // node itself is hidden in place of its contents; and there's no need to search\n // up the hierarchy either\n return !node.getClientRects().length;\n }\n\n // Else, the node isn't attached to the document, which means the `getClientRects()`\n // API will __always__ return zero rects (this can happen, for example, if React\n // is used to render nodes onto a detached tree, as confirmed in this thread:\n // https://github.com/facebook/react/issues/9117#issuecomment-284228870)\n //\n // It also means that even window.getComputedStyle(node).display will return `undefined`\n // because styles are only computed for nodes that are in the document.\n //\n // NOTE: THIS HAS BEEN THE CASE FOR YEARS. It is not new, nor is it caused by tabbable\n // somehow. Though it was never stated officially, anyone who has ever used tabbable\n // APIs on nodes in detached containers has actually implicitly used tabbable in what\n // was later (as of v5.2.0 on Apr 9, 2021) called `displayCheck=\"none\"` mode -- essentially\n // considering __everything__ to be visible because of the innability to determine styles.\n //\n // v6.0.0: As of this major release, the default 'full' option __no longer treats detached\n // nodes as visible with the 'none' fallback.__\n if (displayCheck !== 'legacy-full') {\n return true; // hidden\n }\n // else, fallback to 'none' mode and consider the node visible\n } else if (displayCheck === 'non-zero-area') {\n // NOTE: Even though this tests that the node's client rect is non-zero to determine\n // whether it's displayed, and that a detached node will __always__ have a zero-area\n // client rect, we don't special-case for whether the node is attached or not. In\n // this mode, we do want to consider nodes that have a zero area to be hidden at all\n // times, and that includes attached or not.\n return isZeroArea(node);\n }\n\n // visible, as far as we can tell, or per current `displayCheck=none` mode, we assume\n // it's visible\n return false;\n};\n\n// form fields (nested) inside a disabled fieldset are not focusable/tabbable\n// unless they are in the _first_